complete reset async billing and upstream key rotation

This commit is contained in:
wlx committed 2026-09-27 14:58:24 +08:00
1 parent b54b6a8ac4
commit a80896e3c7
19 files changed
+529 -48

No files matched your search

@@ -19,7 +19,7 @@ public class HealthController {
"migration", "catalog", "migration", "catalog",
"capabilities", Map.of( "capabilities", Map.of(
"verificationCode", verification.capabilities().containsValue(true), "verificationCode", verification.capabilities().containsValue(true),
"passwordReset", false "passwordReset", true
) )
); );
} }
@@ -47,6 +47,8 @@ public class AuthController {
public record RegisterRequest(String invitationCode, String account, String password, String displayName, String verificationCode) {} public record RegisterRequest(String invitationCode, String account, String password, String displayName, String verificationCode) {}
public record CodeRequest(String account, String invitationCode) {} public record CodeRequest(String account, String invitationCode) {}
public record PasswordResetCodeRequest(String account) {}
public record PasswordResetRequest(String account, String verificationCode, String newPassword) {}
@GetMapping("/auth/verification") @GetMapping("/auth/verification")
public Map<String,Boolean> verificationStatus() { return verification.capabilities(); } public Map<String,Boolean> verificationStatus() { return verification.capabilities(); }
@@ -56,6 +58,18 @@ public class AuthController {
return verification.send(input.account(),input.invitationCode(),request.getRemoteAddr()); return verification.send(input.account(),input.invitationCode(),request.getRemoteAddr());
} }
@PostMapping("/auth/password-reset/code")
public Map<String,Object> sendPasswordResetCode(@RequestBody PasswordResetCodeRequest input,HttpServletRequest request) {
return verification.sendReset(input.account(), request.getRemoteAddr());
}
@PostMapping("/auth/password-reset")
public ResponseEntity<Void> resetPassword(@RequestBody PasswordResetRequest input,HttpServletRequest request) {
String account = verification.consumeReset(input.account(), input.verificationCode());
authService.resetPassword(account, input.newPassword(), meta(request));
return ResponseEntity.noContent().build();
}
public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {} public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {}
public record RoleRequest(String role) {} public record RoleRequest(String role) {}
@@ -256,6 +256,23 @@ public class AuthService {
return toView(findUserById(user.id()), null); return toView(findUserById(user.id()), null);
} }
@Transactional
public void resetPassword(String accountInput, String newPassword, RequestMeta meta) {
String account = normalizeAccount(accountInput);
UserRow user = findUserByAccount(account);
if (user == null || !"active".equals(user.status())) {
throw new ApiException("ACCOUNT_NOT_FOUND", "账号不存在或已停用", 404);
}
if (newPassword == null || newPassword.isBlank() || newPassword.length() > 256
|| (!"super_admin".equals(user.role()) && newPassword.length() < 8)) {
throw new ApiException("WEAK_PASSWORD", "普通用户新密码长度为 8 至 256 位", 400);
}
OffsetDateTime changedAt = now();
jdbc.update("UPDATE users SET password_hash=?, updated_at=? WHERE id=?", passwordHasher.hash(newPassword), changedAt, user.id());
jdbc.update("UPDATE auth_sessions SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL", changedAt, user.id());
audit("user.password_reset", user.id(), meta, Map.of());
}
private boolean isAdminRole(String role) { private boolean isAdminRole(String role) {
return "admin".equals(role) || "super_admin".equals(role); return "admin".equals(role) || "super_admin".equals(role);
} }
@@ -29,7 +29,9 @@ public class VerificationService {
if(account.length()>254 || (!account.matches("^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$") && !account.matches("^(?:\\+86)?1[3-9][0-9]{9}$"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱或中国大陆手机号"); if(account.length()>254 || (!account.matches("^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$") && !account.matches("^(?:\\+86)?1[3-9][0-9]{9}$"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱或中国大陆手机号");
return account; return account;
} }
private String digest(String account,String code) { return AuthService.hashSecret(pepper+":registration:"+account+":"+code); } private String digest(String purpose,String account,String code) { return AuthService.hashSecret(pepper+":"+purpose+":"+account+":"+code); }
private String registrationDigest(String account,String code) { return digest("registration",account,code); }
private String resetDigest(String account,String code) { return digest("password-reset",account,code); }
@Transactional(noRollbackFor=ApiException.class) @Transactional(noRollbackFor=ApiException.class)
public Map<String,Object> send(String raw,String invitation,String ip) { public Map<String,Object> send(String raw,String invitation,String ip) {
@@ -47,7 +49,7 @@ public class VerificationService {
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429); if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000)); String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source); jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
jdbc.update("INSERT INTO registration_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,digest(account,code)); jdbc.update("INSERT INTO registration_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,registrationDigest(account,code));
try { sender.send(channel,account,code); } try { sender.send(channel,account,code); }
catch(ApiException exception) { jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account); throw exception; } catch(ApiException exception) { jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account); throw exception; }
jdbc.update("DELETE FROM verification_send_events WHERE created_at<now()-interval '2 days'"); jdbc.update("DELETE FROM verification_send_events WHERE created_at<now()-interval '2 days'");
@@ -63,7 +65,43 @@ public class VerificationService {
java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant(); java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant();
if(Boolean.TRUE.equals(row.get("consumed")) || expiry.isBefore(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取"); if(Boolean.TRUE.equals(row.get("consumed")) || expiry.isBefore(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取");
jdbc.update("UPDATE registration_codes SET attempts=attempts+1 WHERE account=?",account); jdbc.update("UPDATE registration_codes SET attempts=attempts+1 WHERE account=?",account);
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),digest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误"); if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),registrationDigest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误");
jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account); jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account);
} }
@Transactional(noRollbackFor=ApiException.class)
public Map<String,Object> sendReset(String raw,String ip) {
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
if(!sender.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
Integer exists=jdbc.queryForObject("SELECT count(*) FROM users WHERE account=? AND status='active'",Integer.class,account);
// Do not reveal whether an account exists. The client receives the same response either way.
if(exists==null || exists==0) return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
String source=ip==null?"unknown":ip;
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>now()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>now()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
jdbc.update("INSERT INTO password_reset_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,resetDigest(account,code));
try { sender.send(channel,account,code); }
catch(ApiException exception) { jdbc.update("UPDATE password_reset_codes SET consumed=true WHERE account=?",account); throw exception; }
return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
}
@Transactional(noRollbackFor=ApiException.class)
public String consumeReset(String raw,String code) {
String account=normalize(raw);
var rows=jdbc.queryForList("SELECT * FROM password_reset_codes WHERE account=? FOR UPDATE",account);
if(rows.isEmpty()) throw new ApiException("VERIFICATION_INVALID","请先获取验证码");
var row=rows.getFirst();
java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant();
if(Boolean.TRUE.equals(row.get("consumed")) || expiry.isBefore(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取");
jdbc.update("UPDATE password_reset_codes SET attempts=attempts+1 WHERE account=?",account);
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),resetDigest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误");
jdbc.update("UPDATE password_reset_codes SET consumed=true WHERE account=?",account);
return account;
}
} }
@@ -223,7 +223,7 @@ public class CatalogService {
private void validatePricing(Object input) { private void validatePricing(Object input) {
if (!(input instanceof Map<?,?> prices)) return; if (!(input instanceof Map<?,?> prices)) return;
for(String field: List.of("input","output","cachedInput")) { for(String field: List.of("price","input","output","cachedInput")) {
Object amount=prices.get(field); Object amount=prices.get(field);
if(amount==null) continue; if(amount==null) continue;
try { var price=new java.math.BigDecimal(String.valueOf(amount)); if(price.signum()<0 || price.scale()>8 || price.compareTo(new java.math.BigDecimal("1000000"))>0) throw new NumberFormatException(); } try { var price=new java.math.BigDecimal(String.valueOf(amount)); if(price.signum()<0 || price.scale()>8 || price.compareTo(new java.math.BigDecimal("1000000"))>0) throw new NumberFormatException(); }
@@ -475,20 +475,40 @@ public class CatalogService {
model.put("capabilities", readMap(resultSet.getString("capabilities"))); model.put("capabilities", readMap(resultSet.getString("capabilities")));
Map<String, Object> pricing = readOptionalMap(resultSet.getString("pricing")); Map<String, Object> pricing = readOptionalMap(resultSet.getString("pricing"));
putIfNotNull(model, "pricing", pricing); putIfNotNull(model, "pricing", pricing);
model.put("pricingConfigured", pricing != null model.put("pricingConfigured", pricingConfigured(pricing));
&& "CNY / 1M tokens".equals(String.valueOf(pricing.get("unit")))
&& pricing.get("input") != null
&& pricing.get("output") != null);
putIfNotNull(model, "priority", resultSet.getObject("priority")); putIfNotNull(model, "priority", resultSet.getObject("priority"));
putIfNotNull(model, "maxConcurrency", resultSet.getObject("max_concurrency")); putIfNotNull(model, "maxConcurrency", resultSet.getObject("max_concurrency"));
model.put("status", resultSet.getString("status")); model.put("status", resultSet.getString("status"));
// Do not advertise real asynchronous routes before their worker exists.
model.put("executionReady", !"async".equals(resultSet.getString("call_mode")) model.put("executionReady", !"async".equals(resultSet.getString("call_mode"))
|| "provider-mock".equals(resultSet.getString("provider_id"))); || List.of("provider-mock", "provider-vast", "provider-bytedance").contains(resultSet.getString("provider_id")));
model.put("billingReady", billingReady(pricing, resultSet.getString("call_mode"), resultSet.getString("provider_id")));
model.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class)); model.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
return model; return model;
} }
private boolean pricingConfigured(Map<String,Object> pricing) {
if (pricing == null) return false;
String unit = String.valueOf(pricing.getOrDefault("unit", "")).trim().toLowerCase(java.util.Locale.ROOT);
if (unit.isBlank()) return false;
if (unit.contains("token")) return pricing.get("input") != null && pricing.get("output") != null;
Object amount = pricing.get("price");
if (amount == null) amount = pricing.get("input");
return amount != null;
}
private boolean billingReady(Map<String,Object> pricing, String mode, String providerId) {
if ("provider-mock".equals(providerId)) return true;
if (pricing == null) return false;
String unit = String.valueOf(pricing.getOrDefault("unit", "")).trim().toLowerCase(java.util.Locale.ROOT);
if ("async".equals(mode)) {
if (unit.contains("token")) return false;
Object amount = pricing.get("price");
if (amount == null) amount = pricing.get("input");
return amount != null;
}
return unit.equals("cny / 1m tokens") && pricing.get("input") != null && pricing.get("output") != null;
}
private Map<String, Object> mapProject(ResultSet resultSet, int rowNumber) throws SQLException { private Map<String, Object> mapProject(ResultSet resultSet, int rowNumber) throws SQLException {
Map<String, Object> project = new LinkedHashMap<>(); Map<String, Object> project = new LinkedHashMap<>();
project.put("id", resultSet.getString("id")); project.put("id", resultSet.getString("id"));
@@ -25,8 +25,10 @@ public final class ChatMeter {
public static Rates rates(Object value, boolean mock) { public static Rates rates(Object value, boolean mock) {
if (mock) return new Rates(BigDecimal.ZERO,BigDecimal.ZERO,BigDecimal.ZERO); if (mock) return new Rates(BigDecimal.ZERO,BigDecimal.ZERO,BigDecimal.ZERO);
if (!(value instanceof Map<?,?> prices) || !"CNY / 1M tokens".equals(prices.get("unit"))) if (!(value instanceof Map<?,?> prices))
throw new ApiException("MODEL_NOT_PRICED","该分组尚未配置人民币 Token 售价",503); throw new ApiException("MODEL_NOT_PRICED","该分组尚未配置人民币售价",503);
if (!"CNY / 1M tokens".equals(prices.get("unit")))
throw new ApiException("BILLING_UNIT_UNSUPPORTED","当前聊天接口仅支持 Token 计费;该模型应使用其对应的媒体或按次接口",503);
BigDecimal input=price(prices.get("input")), output=price(prices.get("output")); BigDecimal input=price(prices.get("input")), output=price(prices.get("output"));
BigDecimal cached=prices.get("cachedInput")==null?input:price(prices.get("cachedInput")); BigDecimal cached=prices.get("cachedInput")==null?input:price(prices.get("cachedInput"));
return new Rates(input,output,cached); return new Rates(input,output,cached);
@@ -12,7 +12,10 @@ import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
@@ -27,6 +30,7 @@ public class OpenAiCompatibleProvider {
private final JdbcTemplate jdbc; private final JdbcTemplate jdbc;
private final SecretCipher secretCipher; private final SecretCipher secretCipher;
private final Map<String, ProviderConfig> providers; private final Map<String, ProviderConfig> providers;
private final org.springframework.core.env.Environment environment;
private final ScheduledExecutorService deadlines = Executors.newSingleThreadScheduledExecutor(r -> { var t=new Thread(r,"upstream-deadlines"); t.setDaemon(true); return t; }); private final ScheduledExecutorService deadlines = Executors.newSingleThreadScheduledExecutor(r -> { var t=new Thread(r,"upstream-deadlines"); t.setDaemon(true); return t; });
private final int timeoutSeconds; private final int timeoutSeconds;
@@ -40,17 +44,18 @@ public class OpenAiCompatibleProvider {
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
this.jdbc = jdbc; this.jdbc = jdbc;
this.secretCipher = secretCipher; this.secretCipher = secretCipher;
this.environment = environment;
this.timeoutSeconds = Math.max(1,Math.min(90,environment.getProperty("moyi.gateway.upstream-timeout-seconds",Integer.class,90))); this.timeoutSeconds = Math.max(1,Math.min(90,environment.getProperty("moyi.gateway.upstream-timeout-seconds",Integer.class,90)));
this.providers = Map.of( this.providers = Map.of(
"provider-deepseek", new ProviderConfig(environment.getProperty("moyi.providers.deepseek.api-key", ""), environment.getProperty("moyi.providers.deepseek.base-url", "https://api.deepseek.com")), "provider-deepseek", configured("provider-deepseek", environment.getProperty("moyi.providers.deepseek.api-key", ""), environment.getProperty("moyi.providers.deepseek.base-url", "https://api.deepseek.com"), environment),
"provider-kimi", new ProviderConfig(environment.getProperty("moyi.providers.kimi.api-key", ""), environment.getProperty("moyi.providers.kimi.base-url", "https://api.moonshot.ai/v1")), "provider-kimi", configured("provider-kimi", environment.getProperty("moyi.providers.kimi.api-key", ""), environment.getProperty("moyi.providers.kimi.base-url", "https://api.moonshot.ai/v1"), environment),
"provider-zhipu", new ProviderConfig(environment.getProperty("moyi.providers.zhipu.api-key", ""), environment.getProperty("moyi.providers.zhipu.base-url", "https://open.bigmodel.cn/api/paas/v4")) "provider-zhipu", configured("provider-zhipu", environment.getProperty("moyi.providers.zhipu.api-key", ""), environment.getProperty("moyi.providers.zhipu.base-url", "https://open.bigmodel.cn/api/paas/v4"), environment)
); );
} }
public boolean isConfigured(String providerId) { public boolean isConfigured(String providerId) {
ProviderConfig provider = resolve(providerId); ProviderConfig provider = resolve(providerId);
return provider != null && !provider.apiKey().isBlank(); return provider != null && provider.hasKey();
} }
public Map<String, Object> chat(String providerId, String upstreamModel, Map<String,Object> input) { public Map<String, Object> chat(String providerId, String upstreamModel, Map<String,Object> input) {
@@ -68,7 +73,7 @@ public class OpenAiCompatibleProvider {
private StreamResponse open(String providerId, String upstreamModel, Map<String,Object> input, boolean streaming) { private StreamResponse open(String providerId, String upstreamModel, Map<String,Object> input, boolean streaming) {
ProviderConfig provider = resolve(providerId); ProviderConfig provider = resolve(providerId);
if (provider == null || provider.apiKey().isBlank()) { if (provider == null || !provider.hasKey()) {
throw new ApiException("PROVIDER_NOT_CONFIGURED", "该模型的供应商尚未配置服务端 API Key", 503); throw new ApiException("PROVIDER_NOT_CONFIGURED", "该模型的供应商尚未配置服务端 API Key", 503);
} }
Map<String, Object> body = new LinkedHashMap<>(input); Map<String, Object> body = new LinkedHashMap<>(input);
@@ -76,11 +81,12 @@ public class OpenAiCompatibleProvider {
body.put("stream", streaming); body.put("stream", streaming);
if(streaming) body.put("stream_options",Map.of("include_usage",true)); if(streaming) body.put("stream_options",Map.of("include_usage",true));
else body.remove("stream_options"); else body.remove("stream_options");
String apiKey = provider.nextApiKey();
String json = writeJson(body); String json = writeJson(body);
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(normalizeUrl(provider.baseUrl()) + "/chat/completions")) .uri(URI.create(normalizeUrl(provider.baseUrl()) + "/chat/completions"))
.timeout(Duration.ofSeconds(timeoutSeconds)) .timeout(Duration.ofSeconds(timeoutSeconds))
.header("Authorization", "Bearer " + provider.apiKey()) .header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json)) .POST(HttpRequest.BodyPublishers.ofString(json))
.build(); .build();
@@ -176,13 +182,14 @@ public class OpenAiCompatibleProvider {
private ProviderConfig resolve(String providerId) { private ProviderConfig resolve(String providerId) {
ProviderConfig fixed = providers.get(providerId); ProviderConfig fixed = providers.get(providerId);
if (fixed != null && !fixed.apiKey().isBlank()) return fixed; if (fixed != null && fixed.hasKey()) return fixed;
try { try {
Map<String, Object> row = jdbc.queryForMap("SELECT base_url, credential_ciphertext FROM model_providers WHERE id = ? AND status = 'active'", providerId); Map<String, Object> row = jdbc.queryForMap("SELECT code, base_url, credential_ciphertext FROM model_providers WHERE id = ? AND status = 'active'", providerId);
String providerCode = row.get("code") == null ? "" : String.valueOf(row.get("code"));
String ciphertext = row.get("credential_ciphertext") == null ? "" : String.valueOf(row.get("credential_ciphertext")); String ciphertext = row.get("credential_ciphertext") == null ? "" : String.valueOf(row.get("credential_ciphertext"));
String apiKey = ciphertext.isBlank() ? "" : secretCipher.decrypt(ciphertext); String apiKey = ciphertext.isBlank() ? "" : secretCipher.decrypt(ciphertext);
String baseUrl = row.get("base_url") == null ? "" : String.valueOf(row.get("base_url")); String baseUrl = row.get("base_url") == null ? "" : String.valueOf(row.get("base_url"));
return new ProviderConfig(apiKey, baseUrl); return configured(providerId, providerCode, apiKey, baseUrl, environment);
} catch (EmptyResultDataAccessException exception) { } catch (EmptyResultDataAccessException exception) {
return fixed; return fixed;
} }
@@ -196,5 +203,27 @@ public class OpenAiCompatibleProvider {
} }
} }
private record ProviderConfig(String apiKey, String baseUrl) {} private ProviderConfig configured(String providerId, String fallbackKey, String baseUrl, org.springframework.core.env.Environment environment) {
return configured(providerId, providerId, fallbackKey, baseUrl, environment);
}
private ProviderConfig configured(String providerId, String providerCode, String fallbackKey, String baseUrl, org.springframework.core.env.Environment environment) {
List<String> keys = new ArrayList<>();
if (fallbackKey != null && !fallbackKey.isBlank()) keys.add(fallbackKey.trim());
addEnvironmentKeys(keys, providerId, environment);
if (providerCode != null && !providerCode.isBlank() && !providerCode.equals(providerId)) addEnvironmentKeys(keys, providerCode, environment);
return new ProviderConfig(keys.stream().distinct().toList(), baseUrl);
}
private void addEnvironmentKeys(List<String> keys, String alias, org.springframework.core.env.Environment environment) {
String envName = "MOYI_UPSTREAM_API_KEYS_" + alias.toUpperCase(java.util.Locale.ROOT).replace('-', '_');
String configured = environment == null ? null : environment.getProperty(envName);
if (configured != null && !configured.isBlank()) for (String key : configured.split("\\|")) if (!key.isBlank()) keys.add(key.trim());
}
private record ProviderConfig(List<String> apiKeys, String baseUrl, AtomicInteger cursor) {
private ProviderConfig(List<String> apiKeys, String baseUrl) { this(apiKeys, baseUrl, new AtomicInteger()); }
private boolean hasKey() { return !apiKeys.isEmpty(); }
private String nextApiKey() { return apiKeys.get(Math.floorMod(cursor.getAndIncrement(), apiKeys.size())); }
}
} }
@@ -0,0 +1,111 @@
package com.moyi.controlplane.task;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.security.SecretCipher;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.core.env.Environment;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
/** Real async adapters for the providers currently represented in the catalog. */
@Service
public class AsyncProviderClient {
private final JdbcTemplate jdbc;
private final SecretCipher cipher;
private final ObjectMapper mapper;
private final Environment environment;
private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
public AsyncProviderClient(JdbcTemplate jdbc, SecretCipher cipher, ObjectMapper mapper, Environment environment) {
this.jdbc = jdbc; this.cipher = cipher; this.mapper = mapper; this.environment = environment;
}
public Map<String,Object> submit(String providerId, String upstreamModel, String taskType, String prompt) {
Provider provider = provider(providerId);
String code = provider.code().toLowerCase(java.util.Locale.ROOT);
if (code.contains("tripo") || provider.baseUrl().contains("tripo")) {
Map<String,Object> body = new LinkedHashMap<>();
body.put("model", upstreamModel);
body.put("prompt", prompt);
body.put("texture", true);
body.put("pbr", true);
return request("POST", tripoBase(provider.baseUrl()) + "/generation/text-to-model", provider.nextApiKey(), body, "上游 3D 任务创建失败");
}
if (code.contains("byte") || code.contains("seedance") || provider.baseUrl().contains("volces.com")) {
Map<String,Object> body = Map.of("model", upstreamModel, "content", List.of(Map.of("type", "text", "text", prompt)));
return request("POST", trim(provider.baseUrl()) + "/contents/generations/tasks", provider.nextApiKey(), body, "上游视频任务创建失败");
}
throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "该异步渠道没有可用的执行器", 501);
}
public Map<String,Object> poll(String providerId, String providerTaskId) {
Provider provider = provider(providerId);
String code = provider.code().toLowerCase(java.util.Locale.ROOT);
String url;
if (code.contains("tripo") || provider.baseUrl().contains("tripo")) url = tripoBase(provider.baseUrl()) + "/tasks/" + encode(providerTaskId);
else if (code.contains("byte") || code.contains("seedance") || provider.baseUrl().contains("volces.com")) url = trim(provider.baseUrl()) + "/contents/generations/tasks/" + encode(providerTaskId);
else throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "该异步渠道没有可用的执行器", 501);
return request("GET", url, provider.nextApiKey(), null, "上游异步任务查询失败");
}
private Map<String,Object> request(String method, String url, String key, Map<String,Object> body, String message) {
try {
HttpRequest.Builder builder = HttpRequest.newBuilder().uri(URI.create(url)).timeout(Duration.ofSeconds(30))
.header("Authorization", "Bearer " + key).header("Content-Type", "application/json");
if ("POST".equals(method)) builder.POST(HttpRequest.BodyPublishers.ofString(write(body)));
else builder.GET();
HttpResponse<String> response = client.send(builder.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) throw new ApiException("UPSTREAM_PROVIDER_ERROR", message + "(HTTP " + response.statusCode() + ")", 502);
Map<String,Object> parsed = mapper.readValue(response.body(), new TypeReference<>() {});
Object code = parsed.get("code");
if (parsed.containsKey("error") || code instanceof Number number && number.intValue() != 0) {
String detail = parsed.get("message") == null ? message : String.valueOf(parsed.get("message"));
throw new ApiException("UPSTREAM_PROVIDER_ERROR", detail, 502);
}
return parsed;
} catch (ApiException exception) { throw exception; }
catch (Exception exception) { throw new ApiException("UPSTREAM_PROVIDER_ERROR", message, 502); }
}
private Provider provider(String id) {
try {
Map<String,Object> row = jdbc.queryForMap("SELECT code, base_url, credential_ciphertext FROM model_providers WHERE id=? AND status='active' AND deleted_at IS NULL", id);
String ciphertext = row.get("credential_ciphertext") == null ? "" : String.valueOf(row.get("credential_ciphertext"));
String key = ciphertext.isBlank() ? "" : cipher.decrypt(ciphertext);
if (key.isBlank()) throw new ApiException("PROVIDER_NOT_CONFIGURED", "异步渠道尚未配置 API Key", 503);
String code = String.valueOf(row.get("code"));
List<String> keys = new ArrayList<>();
keys.add(key);
addEnvironmentKeys(keys, code);
addEnvironmentKeys(keys, id);
return new Provider(code, String.valueOf(row.get("base_url")), keys.stream().distinct().toList());
} catch (EmptyResultDataAccessException exception) { throw new ApiException("PROVIDER_NOT_CONFIGURED", "异步渠道不存在或已停用", 503); }
}
private String tripoBase(String value) { return trim(value).endsWith("/v3") ? trim(value) : trim(value) + "/v3"; }
private String trim(String value) { return value == null ? "" : value.replaceAll("/+$", ""); }
private String encode(String value) { return java.net.URLEncoder.encode(value, java.nio.charset.StandardCharsets.UTF_8); }
private String write(Object value) throws JsonProcessingException { return mapper.writeValueAsString(value == null ? Map.of() : value); }
private void addEnvironmentKeys(List<String> keys, String alias) {
String name = "MOYI_UPSTREAM_API_KEYS_" + alias.toUpperCase(java.util.Locale.ROOT).replace('-', '_');
String configured = environment.getProperty(name);
if (configured != null && !configured.isBlank()) for (String value : configured.split("\\|")) if (!value.isBlank()) keys.add(value.trim());
}
private record Provider(String code, String baseUrl, List<String> apiKeys, AtomicInteger cursor) {
private Provider(String code, String baseUrl, List<String> apiKeys) { this(code, baseUrl, apiKeys, new AtomicInteger()); }
private String nextApiKey() { return apiKeys.get(Math.floorMod(cursor.getAndIncrement(), apiKeys.size())); }
}
}
@@ -11,6 +11,9 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -29,14 +32,23 @@ public class AsyncTaskService {
private final int maxQueuedPerModel; private final int maxQueuedPerModel;
private final GatewayGuard gatewayGuard; private final GatewayGuard gatewayGuard;
private final UsageAuditService usage; private final UsageAuditService usage;
private final AsyncProviderClient providerClient;
/** Compatibility constructor for isolated gateway tests that only exercise mock tasks. */
public AsyncTaskService(JdbcTemplate jdbc, ObjectMapper objectMapper, CatalogService catalogService,
int maxQueuedPerModel, GatewayGuard gatewayGuard, UsageAuditService usage) {
this(jdbc, objectMapper, catalogService, maxQueuedPerModel, gatewayGuard, usage, null);
}
@org.springframework.beans.factory.annotation.Autowired
public AsyncTaskService( public AsyncTaskService(
JdbcTemplate jdbc, JdbcTemplate jdbc,
ObjectMapper objectMapper, ObjectMapper objectMapper,
CatalogService catalogService, CatalogService catalogService,
@Value("${moyi.tasks.max-queued-per-model:100}") int maxQueuedPerModel, @Value("${moyi.tasks.max-queued-per-model:100}") int maxQueuedPerModel,
GatewayGuard gatewayGuard, GatewayGuard gatewayGuard,
UsageAuditService usage UsageAuditService usage,
AsyncProviderClient providerClient
) { ) {
if (maxQueuedPerModel < 1) throw new IllegalArgumentException("Task queue limit must be positive"); if (maxQueuedPerModel < 1) throw new IllegalArgumentException("Task queue limit must be positive");
this.jdbc = jdbc; this.jdbc = jdbc;
@@ -45,6 +57,7 @@ public class AsyncTaskService {
this.maxQueuedPerModel = maxQueuedPerModel; this.maxQueuedPerModel = maxQueuedPerModel;
this.gatewayGuard = gatewayGuard; this.gatewayGuard = gatewayGuard;
this.usage = usage; this.usage = usage;
this.providerClient = providerClient;
} }
@Transactional @Transactional
@@ -60,21 +73,38 @@ public class AsyncTaskService {
if (model == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404); if (model == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404);
if (!catalogService.keyCanInvoke(key, modelId)) throw new ApiException("MODEL_FORBIDDEN", "当前 Key 无权调用该模型", 403); if (!catalogService.keyCanInvoke(key, modelId)) throw new ApiException("MODEL_FORBIDDEN", "当前 Key 无权调用该模型", 403);
if (!taskType.equals(model.get("type")) || !"async".equals(model.get("mode"))) throw new ApiException("NOT_ASYNC_MEDIA_MODEL", "该模型不是对应的异步媒体模型", 400); if (!taskType.equals(model.get("type")) || !"async".equals(model.get("mode"))) throw new ApiException("NOT_ASYNC_MEDIA_MODEL", "该模型不是对应的异步媒体模型", 400);
if (!"provider-mock".equals(model.get("providerId"))) { if (!"provider-mock".equals(model.get("providerId")) && providerClient == null) throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "异步执行器未配置", 501);
throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "Java 版尚未接入该供应商的异步执行器", 501);
}
Integer queued = jdbc.queryForObject("SELECT COUNT(*) FROM model_tasks WHERE model_id = ? AND status IN ('queued', 'running')", Integer.class, modelId); Integer queued = jdbc.queryForObject("SELECT COUNT(*) FROM model_tasks WHERE model_id = ? AND status IN ('queued', 'running')", Integer.class, modelId);
if (queued != null && queued >= maxQueuedPerModel) throw new ApiException("TASK_QUEUE_FULL", "该模型当前排队已满,请稍后重试", 429); if (queued != null && queued >= maxQueuedPerModel) throw new ApiException("TASK_QUEUE_FULL", "该模型当前排队已满,请稍后重试", 429);
String prompt = String.valueOf(input.getOrDefault("prompt", "")).trim(); String prompt = String.valueOf(input.getOrDefault("prompt", "")).trim();
if (prompt.isBlank()) throw new ApiException("PROMPT_REQUIRED", "生成提示词不能为空"); if (prompt.isBlank()) throw new ApiException("PROMPT_REQUIRED", "生成提示词不能为空");
String id = "task_" + UUID.randomUUID().toString().replace("-", "").substring(0, 24);
UUID apiKeyId = UUID.fromString(String.valueOf(key.get("id"))); UUID apiKeyId = UUID.fromString(String.valueOf(key.get("id")));
UUID userId = catalogService.keyOwnerId(apiKeyId); UUID userId = catalogService.keyOwnerId(apiKeyId);
BigDecimal reservedAmount = taskCharge(model);
reserveWallet(userId, reservedAmount);
String providerTaskId;
try {
if ("provider-mock".equals(model.get("providerId"))) providerTaskId = "mock";
else {
if (providerClient == null) throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "异步执行器未配置", 501);
Map<String,Object> upstream = providerClient.submit(String.valueOf(model.get("providerId")), String.valueOf(model.get("upstreamModel")), taskType, prompt);
providerTaskId = providerTaskId(upstream);
}
} catch (RuntimeException exception) {
releaseWallet(userId, reservedAmount);
throw exception;
}
String id = "task_" + UUID.randomUUID().toString().replace("-", "").substring(0, 24);
OffsetDateTime now = now(); OffsetDateTime now = now();
try {
jdbc.update( jdbc.update(
"INSERT INTO model_tasks (id, user_id, api_key_id, model_id, task_type, provider_task_id, status, progress, prompt, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'mock', 'queued', 0, ?, ?, ?)", "INSERT INTO model_tasks (id, user_id, api_key_id, model_id, task_type, provider_task_id, status, progress, prompt, reserved_amount, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'queued', 0, ?, ?, ?, ?)",
id, userId, apiKeyId, modelId, taskType, prompt, now, now id, userId, apiKeyId, modelId, taskType, providerTaskId, prompt, reservedAmount, now, now
); );
} catch (RuntimeException exception) {
releaseWallet(userId, reservedAmount);
throw exception;
}
usage.recordTask(userId, apiKeyId, modelId, String.valueOf(model.get("providerId")), id, "queued", input, null, null, null); usage.recordTask(userId, apiKeyId, modelId, String.valueOf(model.get("providerId")), id, "queued", input, null, null, null);
catalogService.touchKey(key); catalogService.touchKey(key);
return taskView(id); return taskView(id);
@@ -107,6 +137,7 @@ public class AsyncTaskService {
} }
@Scheduled(fixedDelayString = "${moyi.tasks.worker-interval-ms:1000}") @Scheduled(fixedDelayString = "${moyi.tasks.worker-interval-ms:1000}")
@Transactional
public void completeMockTasks() { public void completeMockTasks() {
List<String> taskIds = jdbc.query("SELECT id FROM model_tasks WHERE status IN ('queued', 'running') AND provider_task_id = 'mock' AND created_at < now() - INTERVAL '500 milliseconds'", (rs, row) -> rs.getString("id")); List<String> taskIds = jdbc.query("SELECT id FROM model_tasks WHERE status IN ('queued', 'running') AND provider_task_id = 'mock' AND created_at < now() - INTERVAL '500 milliseconds'", (rs, row) -> rs.getString("id"));
jdbc.update( jdbc.update(
@@ -115,6 +146,8 @@ public class AsyncTaskService {
"{\"format\":\"mp4\",\"url\":\"https://mock.moyi.ai/tasks/result.mp4\"}", now(), now() "{\"format\":\"mp4\",\"url\":\"https://mock.moyi.ai/tasks/result.mp4\"}", now(), now()
); );
taskIds.forEach(taskId -> usage.updateTask(taskId, "succeeded", Map.of("format", "result", "url", "https://mock.moyi.ai/tasks/" + taskId + "/result"), null, null)); taskIds.forEach(taskId -> usage.updateTask(taskId, "succeeded", Map.of("format", "result", "url", "https://mock.moyi.ai/tasks/" + taskId + "/result"), null, null));
List<Map<String,Object>> pending = jdbc.queryForList("SELECT t.id, t.provider_task_id, m.provider_id FROM model_tasks t JOIN model_catalog m ON m.id=t.model_id WHERE t.status IN ('queued','running') AND t.provider_task_id <> 'mock' ORDER BY t.created_at LIMIT 50");
for (Map<String,Object> row : pending) pollProviderTask(row);
} }
private Map<String, Object> requireKey(String authorization) { private Map<String, Object> requireKey(String authorization) {
@@ -129,12 +162,13 @@ public class AsyncTaskService {
private Map<String, Object> mapTask(ResultSet resultSet, int rowNumber) throws SQLException { private Map<String, Object> mapTask(ResultSet resultSet, int rowNumber) throws SQLException {
Map<String, Object> task = new LinkedHashMap<>(); Map<String, Object> task = new LinkedHashMap<>();
task.put("id", resultSet.getString("id")); task.put("id", resultSet.getString("id"));
task.put("provider", "mock"); task.put("provider", "upstream");
task.put("model", resultSet.getString("model_id")); task.put("model", resultSet.getString("model_id"));
task.put("status", resultSet.getString("status")); task.put("status", resultSet.getString("status"));
task.put("progress", resultSet.getInt("progress")); task.put("progress", resultSet.getInt("progress"));
task.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class)); task.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
task.put("updatedAt", resultSet.getObject("updated_at", OffsetDateTime.class)); task.put("updatedAt", resultSet.getObject("updated_at", OffsetDateTime.class));
putIfPresent(task, "costAmount", resultSet, "cost_amount");
String result = resultSet.getString("result"); String result = resultSet.getString("result");
if (result != null) task.put("result", readMap(result)); if (result != null) task.put("result", readMap(result));
String error = resultSet.getString("error"); String error = resultSet.getString("error");
@@ -148,4 +182,119 @@ public class AsyncTaskService {
} }
private OffsetDateTime now() { return OffsetDateTime.now(ZoneOffset.UTC); } private OffsetDateTime now() { return OffsetDateTime.now(ZoneOffset.UTC); }
private String providerTaskId(Map<String,Object> response) {
Object direct = response.get("id");
if (direct == null && response.get("data") instanceof Map<?,?> data) direct = data.get("task_id");
if (direct == null) throw new ApiException("UPSTREAM_PROVIDER_ERROR", "上游没有返回异步任务编号", 502);
return String.valueOf(direct);
}
private void pollProviderTask(Map<String,Object> row) {
String taskId = String.valueOf(row.get("id"));
try {
Map<String,Object> response = providerClient.poll(String.valueOf(row.get("provider_id")), String.valueOf(row.get("provider_task_id")));
String status = normalizedStatus(response);
int progress = progress(response, status);
Map<String,Object> result = result(response);
if ("succeeded".equals(status) || "failed".equals(status) || "cancelled".equals(status)) {
jdbc.update("UPDATE model_tasks SET status=?, progress=?, result=CAST(? AS jsonb), error=CAST(? AS jsonb), updated_at=?, completed_at=? WHERE id=? AND status IN ('queued','running')", status, progress, result == null ? null : writeJson(result), "failed".equals(status) ? writeJson(Map.of("message", "上游异步任务失败")) : null, now(), now(), taskId);
if ("succeeded".equals(status)) settleTask(taskId);
else releaseTask(taskId);
usage.updateTask(taskId, status, result, "failed".equals(status) ? "UPSTREAM_TASK_FAILED" : null, "failed".equals(status) ? "上游异步任务失败" : null);
} else {
jdbc.update("UPDATE model_tasks SET status=?, progress=?, updated_at=? WHERE id=? AND status IN ('queued','running')", status, progress, now(), taskId);
}
} catch (Exception exception) {
jdbc.update("UPDATE model_tasks SET status='failed', error=CAST(? AS jsonb), updated_at=?, completed_at=? WHERE id=? AND status IN ('queued','running')", writeJson(Map.of("message", "上游异步任务查询失败")), now(), now(), taskId);
usage.updateTask(taskId, "failed", null, "UPSTREAM_TASK_POLL_FAILED", "上游异步任务查询失败");
}
}
private String normalizedStatus(Map<String,Object> response) {
Object raw = response.get("status");
if (raw == null && response.get("data") instanceof Map<?,?> data) raw = data.get("status");
String value = String.valueOf(raw == null ? "running" : raw).toLowerCase(java.util.Locale.ROOT);
if (value.contains("success") || value.equals("completed")) return "succeeded";
if (value.contains("fail") || value.equals("error") || value.equals("banned")) return "failed";
if (value.contains("cancel")) return "cancelled";
return "running";
}
private int progress(Map<String,Object> response, String status) {
Object raw = response.get("progress");
if (raw == null && response.get("data") instanceof Map<?,?> data) raw = data.get("progress");
if (raw instanceof Number number) return Math.max(0, Math.min(100, number.intValue()));
return "succeeded".equals(status) ? 100 : 0;
}
private Map<String,Object> result(Map<String,Object> response) {
Object raw = response.get("output");
if (raw == null && response.get("data") instanceof Map<?,?> data) raw = data.get("output");
if (raw instanceof Map<?,?> map) { Map<String,Object> value = new LinkedHashMap<>(); map.forEach((k,v)->value.put(String.valueOf(k),v)); return value; }
if (raw instanceof String value && !value.isBlank()) return Map.of("url", value);
return null;
}
private String writeJson(Object value) { try { return objectMapper.writeValueAsString(value); } catch (JsonProcessingException exception) { return "{}"; } }
private BigDecimal taskCharge(Map<String,Object> model) {
if ("provider-mock".equals(model.get("providerId"))) return BigDecimal.ZERO;
if (!(model.get("pricing") instanceof Map<?,?> pricing)) throw new ApiException("MODEL_NOT_PRICED", "该异步模型尚未配置按任务计费价格", 503);
Object unitValue = pricing.get("unit");
String unit = String.valueOf(unitValue == null ? "" : unitValue).toLowerCase(java.util.Locale.ROOT);
if (unit.contains("token")) throw new ApiException("ASYNC_BILLING_UNSUPPORTED", "异步任务不能使用 Token 价格,需配置按次、按生成或按媒体单位的固定售价", 503);
Object value = pricing.get("price");
if (value == null) value = pricing.get("input");
try {
BigDecimal amount = new BigDecimal(String.valueOf(value));
if (amount.signum() < 0 || amount.scale() > 8 || amount.compareTo(new BigDecimal("1000000")) > 0) throw new NumberFormatException();
return amount.setScale(8, RoundingMode.CEILING);
} catch (Exception exception) {
throw new ApiException("MODEL_NOT_PRICED", "该异步模型需配置有效的固定任务售价", 503);
}
}
private void reserveWallet(UUID userId, BigDecimal amount) {
if (amount.signum() == 0) return;
jdbc.update("INSERT INTO user_wallets(user_id) VALUES (?) ON CONFLICT DO NOTHING", userId);
Map<String,Object> wallet = jdbc.queryForMap("SELECT balance,reserved_balance FROM user_wallets WHERE user_id=? FOR UPDATE", userId);
BigDecimal available = ((BigDecimal) wallet.get("balance")).subtract((BigDecimal) wallet.get("reserved_balance"));
if (available.compareTo(amount) < 0) throw new ApiException("INSUFFICIENT_BALANCE", "可用余额不足以创建此异步任务", 402);
jdbc.update("UPDATE user_wallets SET reserved_balance=reserved_balance+?,updated_at=now() WHERE user_id=?", amount, userId);
}
private void releaseWallet(UUID userId, BigDecimal amount) {
if (amount.signum() > 0) jdbc.update("UPDATE user_wallets SET reserved_balance=GREATEST(0,reserved_balance-?),updated_at=now() WHERE user_id=?", amount, userId);
}
private void settleTask(String taskId) {
Map<String,Object> task = jdbc.queryForMap("SELECT user_id,reserved_amount,cost_amount FROM model_tasks WHERE id=? FOR UPDATE", taskId);
BigDecimal amount = (BigDecimal) task.get("reserved_amount");
if (amount == null || amount.signum() == 0 || task.get("cost_amount") != null) return;
UUID userId = (UUID) task.get("user_id");
Map<String,Object> wallet = jdbc.queryForMap("SELECT balance,reserved_balance FROM user_wallets WHERE user_id=? FOR UPDATE", userId);
BigDecimal before = (BigDecimal) wallet.get("balance");
BigDecimal after = before.subtract(amount);
jdbc.update("UPDATE user_wallets SET balance=?,reserved_balance=GREATEST(0,reserved_balance-?),updated_at=now() WHERE user_id=?", after, amount, userId);
jdbc.update("INSERT INTO wallet_entries(id,user_id,request_id,amount,balance_after,currency,reason,operation,requested_amount,balance_before,actor_user_id) VALUES (?,?,?,?,?,'CNY',?,'usage',?,?,NULL)", UUID.randomUUID(), userId, taskRequestId(taskId), amount.negate(), after, "异步模型任务 · " + taskId, amount, before);
jdbc.update("UPDATE model_tasks SET cost_amount=? WHERE id=?", amount, taskId);
jdbc.update("UPDATE usage_events SET cost_amount=? WHERE provider_task_id=? AND event_kind='task'", amount, taskId);
}
private void releaseTask(String taskId) {
Map<String,Object> task = jdbc.queryForMap("SELECT user_id,reserved_amount,cost_amount FROM model_tasks WHERE id=? FOR UPDATE", taskId);
BigDecimal amount = (BigDecimal) task.get("reserved_amount");
if (amount != null && amount.signum() > 0 && task.get("cost_amount") == null) {
releaseWallet((UUID) task.get("user_id"), amount);
jdbc.update("UPDATE model_tasks SET cost_amount=0 WHERE id=?", taskId);
}
}
private UUID taskRequestId(String taskId) { return UUID.nameUUIDFromBytes(("moyi-async:" + taskId).getBytes(StandardCharsets.UTF_8)); }
private void putIfPresent(Map<String,Object> target, String name, ResultSet resultSet, String column) throws SQLException {
Object value = resultSet.getObject(column);
if (value != null) target.put(name, value);
}
} }
@@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS password_reset_codes (
account varchar(254) PRIMARY KEY,
code_hash char(64) NOT NULL,
expires_at timestamptz NOT NULL,
attempts integer NOT NULL DEFAULT 0,
consumed boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS password_reset_codes_expires_idx
ON password_reset_codes(expires_at);
@@ -0,0 +1,7 @@
-- The official international Tripo V3 endpoint is openapi.tripo3d.ai.
-- Only migrate the catalog seed value; an administrator's custom endpoint is preserved.
UPDATE model_providers
SET base_url = 'https://openapi.tripo3d.ai'
WHERE id = 'provider-vast'
AND code = 'vast-tripo'
AND base_url = 'https://api.tripo3d.ai';
@@ -0,0 +1,2 @@
ALTER TABLE model_tasks ADD COLUMN IF NOT EXISTS reserved_amount numeric(20,8) NOT NULL DEFAULT 0 CHECK (reserved_amount >= 0);
ALTER TABLE model_tasks ADD COLUMN IF NOT EXISTS cost_amount numeric(20,8);
+17 -5
View File
@@ -158,13 +158,13 @@ MOYI 用户对外使用的统一 API Base URL 为 `https://moyi.soulofmodel.com/
国际站官方文档:[General](https://platform.tripo3d.ai/docs/general)、[Authentication](https://platform.tripo3d.ai/docs/quick-start)、[Generation](https://platform.tripo3d.ai/docs/generation)。 国际站官方文档:[General](https://platform.tripo3d.ai/docs/general)、[Authentication](https://platform.tripo3d.ai/docs/quick-start)、[Generation](https://platform.tripo3d.ai/docs/generation)。
- 国际站 API Base URL:`https://api.tripo3d.ai/v2/openapi`。 - Java 执行器使用 Tripo V3 API Base URL:`https://openapi.tripo3d.ai/v3`。
- 使用 HTTP Bearer API Key;创建任务为 `POST /task`,查询为 `GET /task/{task_id}`。 - 使用 HTTP Bearer API Key;创建任务为 `POST /generation/text-to-model`,查询为 `GET /tasks/{task_id}`。
- 文生 3D 请求使用 `type=text_to_model`,版本放在 `model_version`,不能按 OpenAI 聊天请求直接转发。 - 文生 3D 请求使用 `type=text_to_model`,版本放在 `model_version`,不能按 OpenAI 聊天请求直接转发。
- 当前官方生成文档列出的版本包括 `P1-20260311`、`Turbo-v1.0-20250506`、`v3.1-20260211`、`v3.0-20250812`、`v2.5-20250123` 等,实际选型需结合账号权限及价格。 - 当前官方生成文档列出的版本包括 `P1-20260311`、`Turbo-v1.0-20250506`、`v3.1-20260211`、`v3.0-20250812`、`v2.5-20250123` 等,实际选型需结合账号权限及价格。
- 若 Key 来自国内 `platform.tripo3d.com`,使用其对应文档与端点;不能假定 `.ai` 和 `.com` 凭据互通。 - 若 Key 来自国内 `platform.tripo3d.com`,使用其对应文档与端点;不能假定 `.ai` 和 `.com` 凭据互通。
- 建议渠道 Code `tripo-official`、名称 `Tripo 官方`、来源“官方供应商”、协议 HTTP、凭据类型 Bearer Token。先不要把真实 3D 模型作为已可用发布。 - 建议渠道 Code `tripo-official`、名称 `Tripo 官方`、来源“官方供应商”、协议 HTTP、凭据类型 Bearer Token。配置真实 Key 后,先用一个低成本模型创建任务并轮询到终态,再把该分组发布给用户。
- 7360cf3e 的 Java `AsyncTaskService` 对非 Mock 异步供应商返回 `ASYNC_PROVIDER_NOT_IMPLEMENTED`。必须补齐创建、轮询、状态持久化、错误处理、结果链接与使用记录后,才能在 MOYI 使用官方 Key 测试。 - Java 异步执行器已接入 Tripo(`provider-vast`)和 Seedance(`provider-bytedance`)的创建、轮询、状态持久化、失败处理和结果链接;未匹配这两个适配器的异步渠道仍会明确显示为“执行器待接入”,不会伪装成可用。
## MOYI 联调顺序 ## MOYI 联调顺序
@@ -177,6 +177,18 @@ MOYI 用户对外使用的统一 API Base URL 为 `https://moyi.soulofmodel.com/
程序调用时先请求 `GET https://moyi.soulofmodel.com/v1/models`,使用返回的 `data[].id` 作为聊天请求 `model`。当前实现使用分组/路由 ID,表单中的“统一模型标识”是展示字段,不是可直接调用的别名。旧版使用 `stream:false`;部署包含 V13 的新版后可使用 `stream:true`。 程序调用时先请求 `GET https://moyi.soulofmodel.com/v1/models`,使用返回的 `data[].id` 作为聊天请求 `model`。当前实现使用分组/路由 ID,表单中的“统一模型标识”是展示字段,不是可直接调用的别名。旧版使用 `stream:false`;部署包含 V13 的新版后可使用 `stream:true`。
新版提供 OpenAI 兼容聊天的同步/流式转发、文本消息、工具参数透传和输出上限。Responses 原生接口、Anthropic 原生接口、多模态输入、真实图像/视频/3D 执行器仍需单独适配。中转站各模型的具体参数支持需要逐个验证。 新版提供 OpenAI 兼容聊天的同步/流式转发、文本消息、工具参数透传和输出上限;Tripo 3D 与 Seedance 视频已有对应的异步创建、轮询和结果持久化。Responses 原生接口、Anthropic 原生接口、多模态聊天输入仍需单独适配;未匹配执行器的异步渠道会显示为“执行器待接入”,不会创建假任务。中转站各模型的具体参数支持需要逐个验证。
新版按分组人民币售价预留余额,以实际 Token 用量结算,失败释放预留。部署前需填写价格并给测试账号发放余额,否则真实模型会被拒绝调用。报价、计费精度、断流及幂等规则见 [流式聊天与人民币计费](16-streaming-chat-billing.md)。平台用户账本和上游钱包独立,上游消费不等于平台收入。 新版按分组人民币售价预留余额,以实际 Token 用量结算,失败释放预留。部署前需填写价格并给测试账号发放余额,否则真实模型会被拒绝调用。报价、计费精度、断流及幂等规则见 [流式聊天与人民币计费](16-streaming-chat-billing.md)。平台用户账本和上游钱包独立,上游消费不等于平台收入。
价格单位必须和调用方式匹配:同步/流式聊天使用 `CNY / 1M tokens` 并填写输入、输出价格;异步媒体任务使用非 Token 单位时填写 `price` 和单位(例如 `CNY / task`),平台在创建任务时预留该固定金额,任务成功扣除、失败释放。已配置价格但没有对应计费实现的模型会保持不可调用状态。
## 一个渠道配置多个上游 Key
可以。当前 OpenAI 兼容转发器支持为同一渠道配置多个上游 Key,并按请求轮换,适合把上游的单 Key 并发拆到多个 Key。服务器环境变量优先使用渠道编码(管理端渠道的 code),也兼容渠道 ID 转成大写下划线后的名字,Key 之间用 `|` 分隔。例如渠道编码为 `apipro` 时:
```ini
MOYI_UPSTREAM_API_KEYS_APIPRO='key_a|key_b|key_c'
```
保留管理端渠道中的单个凭据作为回退 Key。同步聊天和已接入的异步执行器都会在每个请求或轮询请求前轮换 Key。轮换只解决 Key 分摊,不能突破上游账户总并发、余额、模型授权或速率限制;平台自己的模型并发和单个 MOYI Key 并发仍由网关队列控制。多个 Key 应来自同一渠道、具有相同模型授权,并在服务器密钥文件中保存,不能提交到 Git。当前没有把这些 Key 明文放进管理端数据库的功能,避免把上游密钥暴露给前端;需要新增或撤销 Key 时修改服务器 `.env.cloud` 后重启 API 容器即可。
+14
View File
@@ -27,6 +27,8 @@ export interface LoginInput {
export interface AuthClient { export interface AuthClient {
verificationChannels(): Promise<{ email: boolean; phone: boolean }> verificationChannels(): Promise<{ email: boolean; phone: boolean }>
sendVerificationCode(account: string, invitationCode: string): Promise<{ retryAfterSeconds: number }> sendVerificationCode(account: string, invitationCode: string): Promise<{ retryAfterSeconds: number }>
sendPasswordResetCode(account: string): Promise<{ retryAfterSeconds: number }>
resetPassword(input: { account: string; verificationCode: string; newPassword: string }): Promise<void>
health(): Promise<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }> health(): Promise<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }>
login(input: LoginInput): Promise<AuthUser> login(input: LoginInput): Promise<AuthUser>
register(input: RegisterInput): Promise<AuthUser> register(input: RegisterInput): Promise<AuthUser>
@@ -48,6 +50,18 @@ class HttpAuthClient implements AuthClient {
}) })
} }
sendPasswordResetCode(account: string) {
return this.request<{ retryAfterSeconds: number }>('/api/auth/password-reset/code', {
method: 'POST', body: JSON.stringify({ account }),
})
}
async resetPassword(input: { account: string; verificationCode: string; newPassword: string }) {
await this.request<void>('/api/auth/password-reset', {
method: 'POST', body: JSON.stringify(input),
})
}
async health() { async health() {
return this.request<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }>('/health') return this.request<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }>('/health')
} }
+3 -1
View File
@@ -30,6 +30,7 @@ export interface CatalogModel {
outputTypes: string[] outputTypes: string[]
capabilities: Record<string, unknown> capabilities: Record<string, unknown>
pricing?: { pricing?: {
price?: number
input?: number input?: number
output?: number output?: number
cachedInput?: number cachedInput?: number
@@ -41,6 +42,7 @@ export interface CatalogModel {
listPriceUsd?: { input?: number; output?: number; cachedInput?: number } listPriceUsd?: { input?: number; output?: number; cachedInput?: number }
} }
pricingConfigured?: boolean pricingConfigured?: boolean
billingReady?: boolean
priority?: number priority?: number
maxConcurrency?: number maxConcurrency?: number
executionReady?: boolean executionReady?: boolean
@@ -498,7 +500,7 @@ class HttpCatalogClient {
return this.request<{ model: CatalogModel }>(`/api/admin/models${id ? `/${encodeURIComponent(id)}` : ''}`, { method: id ? 'PATCH' : 'POST', body: JSON.stringify(input) }) return this.request<{ model: CatalogModel }>(`/api/admin/models${id ? `/${encodeURIComponent(id)}` : ''}`, { method: id ? 'PATCH' : 'POST', body: JSON.stringify(input) })
} }
async createAdminModel(input: { providerId: string; publicName: string; upstreamModel: string; modelKey?: string; sourceLabel?: string; type: CatalogModelType; mode: CatalogCallMode; description?: string; inputTypes?: string[]; outputTypes?: string[]; pricing?: { input?: number; output?: number; unit?: string }; priority?: number; maxConcurrency?: number }) { async createAdminModel(input: { providerId: string; publicName: string; upstreamModel: string; modelKey?: string; sourceLabel?: string; type: CatalogModelType; mode: CatalogCallMode; description?: string; inputTypes?: string[]; outputTypes?: string[]; pricing?: { price?: number; input?: number; output?: number; unit?: string }; priority?: number; maxConcurrency?: number }) {
return this.request<{ model: CatalogModel }>('/api/admin/models', { method: 'POST', body: JSON.stringify(input) }) return this.request<{ model: CatalogModel }>('/api/admin/models', { method: 'POST', body: JSON.stringify(input) })
} }
+2
View File
@@ -35,6 +35,7 @@ export interface ModelItem {
modelKey?: string modelKey?: string
sourceLabel?: string sourceLabel?: string
pricing?: { pricing?: {
price?: number
input?: number input?: number
output?: number output?: number
cachedInput?: number cachedInput?: number
@@ -46,6 +47,7 @@ export interface ModelItem {
listPriceUsd?: { input?: number; output?: number; cachedInput?: number } listPriceUsd?: { input?: number; output?: number; cachedInput?: number }
} }
pricingConfigured?: boolean pricingConfigured?: boolean
billingReady?: boolean
priority?: number priority?: number
maxConcurrency?: number maxConcurrency?: number
executionReady?: boolean executionReady?: boolean
+2 -1
View File
@@ -83,7 +83,7 @@ async function refreshOverviewData(notifyOnSuccess = false) {
models.value = mapModels(modelResult.models, providerResult.providers) models.value = mapModels(modelResult.models, providerResult.providers)
const activeProviders = new Set(providerResult.providers.filter((item) => item.status === 'active').map((item) => item.id)) const activeProviders = new Set(providerResult.providers.filter((item) => item.status === 'active').map((item) => item.id))
const activeDefinitions = new Set(modelResult.logicalModels.filter((item) => item.status === 'active').map((item) => item.id)) const activeDefinitions = new Set(modelResult.logicalModels.filter((item) => item.status === 'active').map((item) => item.id))
const publishedRoutes = modelResult.models.filter((item) => item.status === 'active' && activeProviders.has(item.providerId) && activeDefinitions.has(item.logicalModelId) && item.pricingConfigured && item.executionReady !== false) const publishedRoutes = modelResult.models.filter((item) => item.status === 'active' && activeProviders.has(item.providerId) && activeDefinitions.has(item.logicalModelId) && item.pricingConfigured && item.billingReady !== false && item.executionReady !== false)
publicRouteCount.value = publishedRoutes.length publicRouteCount.value = publishedRoutes.length
publicModelCount.value = new Set(publishedRoutes.map((item) => item.logicalModelId)).size publicModelCount.value = new Set(publishedRoutes.map((item) => item.logicalModelId)).size
unpricedRouteCount.value = modelResult.models.filter((item) => item.status === 'active' && activeProviders.has(item.providerId) && activeDefinitions.has(item.logicalModelId) && !item.pricingConfigured).length unpricedRouteCount.value = modelResult.models.filter((item) => item.status === 'active' && activeProviders.has(item.providerId) && activeDefinitions.has(item.logicalModelId) && !item.pricingConfigured).length
@@ -263,6 +263,7 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
logicalModelId: model.logicalModelId, logicalModelId: model.logicalModelId,
vendorName: model.vendorName, vendorName: model.vendorName,
pricingConfigured: model.pricingConfigured, pricingConfigured: model.pricingConfigured,
billingReady: model.billingReady,
executionReady: model.executionReady, executionReady: model.executionReady,
})) }))
} }
+44 -4
View File
@@ -66,6 +66,25 @@ async function sendCode() {
} finally { sendingCode.value = false } } finally { sendingCode.value = false }
} }
async function sendResetCode() {
if (sendingCode.value || cooldown.value) return
const value = account.value.trim()
const valid = registerChannel.value === 'email'
? /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
: /^(?:\+86)?1[3-9]\d{9}$/.test(value)
if (!valid) return emit('notify', `请输入有效的${accountLabel.value}`)
sendingCode.value = true
try {
const result = await authClient.sendPasswordResetCode(value)
cooldown.value = result.retryAfterSeconds
clearInterval(cooldownTimer)
cooldownTimer = setInterval(() => { if (cooldown.value > 0) cooldown.value--; else clearInterval(cooldownTimer) }, 1000)
emit('notify', '验证码已发送,5 分钟内有效')
} catch (error) {
emit('notify', error instanceof AuthApiError ? error.message : '验证码发送失败')
} finally { sendingCode.value = false }
}
async function submitLogin() { async function submitLogin() {
if (!account.value.trim() || !password.value) return emit('notify', '请输入账号和密码') if (!account.value.trim() || !password.value) return emit('notify', '请输入账号和密码')
loading.value = true loading.value = true
@@ -102,8 +121,24 @@ async function submitRegister() {
} }
} }
function submitReset() { async function submitReset() {
emit('notify', '密码重置服务尚未接入,请联系平台管理员处理') if (!account.value.trim()) return emit('notify', `请输入${accountLabel.value}`)
if (!/^\d{6}$/.test(verificationCode.value)) return emit('notify', '请输入 6 位验证码')
if (password.value.length < 8) return emit('notify', '密码至少需要 8 位')
if (password.value !== confirmPassword.value) return emit('notify', '两次输入的密码不一致')
loading.value = true
try {
await authClient.resetPassword({ account: account.value.trim(), verificationCode: verificationCode.value, newPassword: password.value })
loading.value = false
password.value = ''
confirmPassword.value = ''
verificationCode.value = ''
emit('notify', '密码已重置,请使用新密码登录')
switchMode('login')
} catch (error) {
loading.value = false
emit('notify', error instanceof AuthApiError ? error.message : '密码重置失败')
}
} }
onMounted(async () => { onMounted(async () => {
@@ -187,10 +222,15 @@ onMounted(async () => {
<div class="auth-card-header reset-header"> <div class="auth-card-header reset-header">
<span class="reset-icon"><LockKeyhole :size="22" /></span> <span class="reset-icon"><LockKeyhole :size="22" /></span>
<h2>重置密码</h2> <h2>重置密码</h2>
<p>密码重置服务尚未接入,当前请联系平台管理员处理。</p> <p>通过注册邮箱或手机号获取验证码,设置新的登录密码。</p>
</div> </div>
<form class="auth-form" @submit.prevent="submitReset"> <form class="auth-form" @submit.prevent="submitReset">
<button class="auth-submit" type="submit">联系平台管理员<ArrowRight :size="17" /></button> <div class="register-channel"><button type="button" :class="{ active: registerChannel === 'email' }" @click="registerChannel = 'email'"><Mail :size="15" />邮箱重置</button><button type="button" :class="{ active: registerChannel === 'phone' }" @click="registerChannel = 'phone'"><Phone :size="15" />手机重置</button></div>
<label><span>{{ accountLabel }}</span><div class="auth-input"><component :is="registerChannel === 'email' ? Mail : Phone" :size="17" /><input v-model="account" :placeholder="accountPlaceholder" autocomplete="username" /></div></label>
<label><span>验证码</span><div class="auth-code-row"><div class="auth-input"><ShieldCheck :size="17" /><input v-model="verificationCode" inputmode="numeric" autocomplete="one-time-code" maxlength="6" pattern="[0-9]{6}" required placeholder="6 位验证码" /></div><button type="button" :disabled="sendingCode || cooldown > 0 || !channels[registerChannel]" @click="sendResetCode">{{ sendingCode ? '发送中' : cooldown ? `${cooldown} 秒后重发` : '获取验证码' }}</button></div></label>
<label><span>新密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="password" :type="showPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="至少 8 位字符" /><button type="button" @click="showPassword = !showPassword"><EyeOff v-if="showPassword" :size="17" /><Eye v-else :size="17" /></button></div></label>
<label><span>确认新密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="confirmPassword" :type="showConfirmPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="再次输入新密码" /><button type="button" @click="showConfirmPassword = !showConfirmPassword"><EyeOff v-if="showConfirmPassword" :size="17" /><Eye v-else :size="17" /></button></div></label>
<button class="auth-submit" type="submit" :disabled="loading"><span v-if="loading" class="spinner"></span><template v-else>重置密码<ArrowRight :size="17" /></template></button>
</form> </form>
</template> </template>
</article> </article>
+16 -6
View File
@@ -66,7 +66,7 @@ const galleryModels = computed<GalleryModel[]>(() => buildModelCatalog(catalogDe
const routes = groups.map(group => catalogModels.value.find(item => item.id === group.id)!).filter(Boolean) const routes = groups.map(group => catalogModels.value.find(item => item.id === group.id)!).filter(Boolean)
const providerNames = [...new Set(routes.map(group => group.provider))] const providerNames = [...new Set(routes.map(group => group.provider))]
return { ...mapCatalogModel(definition), groups: routes, providerNames, return { ...mapCatalogModel(definition), groups: routes, providerNames,
provider: providerNames.join(' / ') || '暂无上线分组', availability: routes.some(group => group.pricingConfigured && group.executionReady !== false) ? '在线' : '待上线' } provider: providerNames.join(' / ') || '暂无上线分组', availability: routes.some(group => group.pricingConfigured && group.billingReady !== false && group.executionReady !== false) ? '在线' : '待上线' }
})) }))
const featuredModels = computed(() => [...galleryModels.value].sort((a, b) => Number(!!b.groups.length) - Number(!!a.groups.length)).slice(0, 3)) const featuredModels = computed(() => [...galleryModels.value].sort((a, b) => Number(!!b.groups.length) - Number(!!a.groups.length)).slice(0, 3))
const activeModel = ref<ModelItem>(emptyModel) const activeModel = ref<ModelItem>(emptyModel)
@@ -219,7 +219,11 @@ function formatUsdPrice(value: number | undefined) {
function standardPriceLabel(model: GalleryModel) { function standardPriceLabel(model: GalleryModel) {
const pricing = model.groups.find(group => group.pricing?.listPriceUsd)?.pricing const pricing = model.groups.find(group => group.pricing?.listPriceUsd)?.pricing
if (!pricing?.listPriceUsd) return '标准价待同步' if (!pricing?.listPriceUsd) {
const unit = pricing?.unit
const price = pricing?.price ?? pricing?.input
return unit && price !== undefined ? `¥${Number(price).toLocaleString('zh-CN', { maximumFractionDigits: 8 })} / ${unit}` : '标准价待同步'
}
return `${formatUsdPrice(pricing.listPriceUsd.input)} 输入 / ${formatUsdPrice(pricing.listPriceUsd.output)} 输出 · USD / 1M` return `${formatUsdPrice(pricing.listPriceUsd.input)} 输入 / ${formatUsdPrice(pricing.listPriceUsd.output)} 输出 · USD / 1M`
} }
@@ -231,24 +235,30 @@ function groupDiscountLabel(group: ModelItem) {
function groupPriceLabel(group: ModelItem) { function groupPriceLabel(group: ModelItem) {
const pricing = group.pricing const pricing = group.pricing
if (!group.pricingConfigured || !pricing) return '当前不可调用:价格待配置' if (!group.pricingConfigured || !pricing) return '当前不可调用:价格待配置'
if (pricing.unit && !String(pricing.unit).toLowerCase().includes('token')) {
const price = pricing.price ?? pricing.input
return price === undefined ? `计费单位:${pricing.unit}` : `¥${Number(price).toLocaleString('zh-CN', { maximumFractionDigits: 8 })} / ${pricing.unit}`
}
const input = pricing.input === undefined ? '待定' : `¥${pricing.input.toLocaleString('zh-CN', { maximumFractionDigits: 8 })}` const input = pricing.input === undefined ? '待定' : `¥${pricing.input.toLocaleString('zh-CN', { maximumFractionDigits: 8 })}`
const output = pricing.output === undefined ? '待定' : `¥${pricing.output.toLocaleString('zh-CN', { maximumFractionDigits: 8 })}` const output = pricing.output === undefined ? '待定' : `¥${pricing.output.toLocaleString('zh-CN', { maximumFractionDigits: 8 })}`
return `${input} 输入 / ${output} 输出 · ${pricing.unit || 'CNY / 1M tokens'}` return `${input} 输入 / ${output} 输出 · ${pricing.unit || 'CNY / 1M tokens'}`
} }
function hasCallableGroup(model: GalleryModel) { function hasCallableGroup(model: GalleryModel) {
return model.groups.some(group => group.pricingConfigured && group.executionReady !== false) return model.groups.some(group => group.pricingConfigured && group.billingReady !== false && group.executionReady !== false)
} }
function modelAvailabilityLabel(model: GalleryModel) { function modelAvailabilityLabel(model: GalleryModel) {
if (!model.groups.length) return '待上线' if (!model.groups.length) return '待上线'
if (hasCallableGroup(model)) return '在线' if (hasCallableGroup(model)) return '在线'
if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.executionReady === false)) return '异步执行器待接入' if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.executionReady === false)) return '异步执行器待接入'
if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.billingReady === false)) return '异步按任务计费待配置'
return '价格待配置' return '价格待配置'
} }
function modelUnavailableLabel(model: GalleryModel) { function modelUnavailableLabel(model: GalleryModel) {
if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.executionReady === false)) return '异步执行器待接入' if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.executionReady === false)) return '异步执行器待接入'
if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.billingReady === false)) return '异步按任务计费待配置'
return '价格待配置' return '价格待配置'
} }
@@ -288,7 +298,7 @@ async function refreshOverview() {
} }
function tryModel(model: GalleryModel) { function tryModel(model: GalleryModel) {
const group = model.groups.find(item => item.pricingConfigured) const group = model.groups.find(item => item.pricingConfigured && item.billingReady !== false && item.executionReady !== false)
if (!group) return emit('notify', '该模型已收录,但分组价格尚未配置,暂时不能调用') if (!group) return emit('notify', '该模型已收录,但分组价格尚未配置,暂时不能调用')
activeModel.value = group activeModel.value = group
callMode.value = group.mode callMode.value = group.mode
@@ -437,7 +447,7 @@ function mapCatalogModels(items: CatalogModel[], providers: Array<{ id: string;
...mapCatalogModel(item), logicalModelId: item.logicalModelId, ...mapCatalogModel(item), logicalModelId: item.logicalModelId,
provider: providerNames.get(item.providerId) || item.providerId, provider: providerNames.get(item.providerId) || item.providerId,
vendorName: item.vendorName, vendorName: item.vendorName,
sourceLabel: item.sourceLabel, pricing: item.pricing, pricingConfigured: item.pricingConfigured, priority: item.priority, maxConcurrency: item.maxConcurrency, executionReady: item.executionReady, sourceLabel: item.sourceLabel, pricing: item.pricing, pricingConfigured: item.pricingConfigured, billingReady: item.billingReady, priority: item.priority, maxConcurrency: item.maxConcurrency, executionReady: item.executionReady,
})) }))
} }
@@ -762,7 +772,7 @@ $env:OPENAI_API_KEY="你的 MOYI 用户 API Key"
<label>调用模型 ID <code>{{ group.id }}</code></label> <label>调用模型 ID <code>{{ group.id }}</code></label>
<button class="text-link" @click="copy(group.id, '调用模型 ID', group.id)"><Copy :size="14" />{{ copySucceeded(group.id) ? '已复制' : '复制调用 ID' }}</button> <button class="text-link" @click="copy(group.id, '调用模型 ID', group.id)"><Copy :size="14" />{{ copySucceeded(group.id) ? '已复制' : '复制调用 ID' }}</button>
<small class="drawer-pricing">标准价:{{ group.pricing?.listPriceUsd ? `${formatUsdPrice(group.pricing.listPriceUsd.input)} 输入 / ${formatUsdPrice(group.pricing.listPriceUsd.output)} 输出 · USD / 1M` : '待同步' }} · {{ groupPriceLabel(group) }} · 对外 {{ groupDiscountLabel(group) }}</small> <small class="drawer-pricing">标准价:{{ group.pricing?.listPriceUsd ? `${formatUsdPrice(group.pricing.listPriceUsd.input)} 输入 / ${formatUsdPrice(group.pricing.listPriceUsd.output)} 输出 · USD / 1M` : '待同步' }} · {{ groupPriceLabel(group) }} · 对外 {{ groupDiscountLabel(group) }}</small>
<button class="button secondary" :disabled="!group.pricingConfigured || group.executionReady === false" @click="tryModel({ ...selectedModel, groups: [group] })">{{ !group.pricingConfigured ? '价格待配置' : group.executionReady === false ? '异步执行器待接入' : '试用此分组' }}</button> <button class="button secondary" :disabled="!group.pricingConfigured || group.billingReady === false || group.executionReady === false" @click="tryModel({ ...selectedModel, groups: [group] })">{{ !group.pricingConfigured ? '价格待配置' : group.executionReady === false ? '异步执行器待接入' : group.billingReady === false ? '异步按任务计费待配置' : '试用此分组' }}</button>
</section> </section>
<template #footer><button class="button primary full" :disabled="!hasCallableGroup(selectedModel)" @click="tryModel(selectedModel)"><Play :size="16" />{{ !selectedModel.groups.length ? '分组待上线' : hasCallableGroup(selectedModel) ? '在线试用' : modelUnavailableLabel(selectedModel) }}</button><button class="button secondary full" @click="selectedModel = null; emit('navigate', 'docs')"><BookOpen :size="16" />查看文档</button></template> <template #footer><button class="button primary full" :disabled="!hasCallableGroup(selectedModel)" @click="tryModel(selectedModel)"><Play :size="16" />{{ !selectedModel.groups.length ? '分组待上线' : hasCallableGroup(selectedModel) ? '在线试用' : modelUnavailableLabel(selectedModel) }}</button><button class="button secondary full" @click="selectedModel = null; emit('navigate', 'docs')"><BookOpen :size="16" />查看文档</button></template>
</SlidePanel> </SlidePanel>