diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/HealthController.java b/control-plane-java/src/main/java/com/moyi/controlplane/HealthController.java index 2a57d5e..048f1b0 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/HealthController.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/HealthController.java @@ -19,7 +19,7 @@ public class HealthController { "migration", "catalog", "capabilities", Map.of( "verificationCode", verification.capabilities().containsValue(true), - "passwordReset", false + "passwordReset", true ) ); } diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthController.java b/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthController.java index 16111b4..285c7e9 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthController.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthController.java @@ -47,6 +47,8 @@ public class AuthController { public record RegisterRequest(String invitationCode, String account, String password, String displayName, String verificationCode) {} public record CodeRequest(String account, String invitationCode) {} + public record PasswordResetCodeRequest(String account) {} + public record PasswordResetRequest(String account, String verificationCode, String newPassword) {} @GetMapping("/auth/verification") public Map verificationStatus() { return verification.capabilities(); } @@ -56,6 +58,18 @@ public class AuthController { return verification.send(input.account(),input.invitationCode(),request.getRemoteAddr()); } + @PostMapping("/auth/password-reset/code") + public Map sendPasswordResetCode(@RequestBody PasswordResetCodeRequest input,HttpServletRequest request) { + return verification.sendReset(input.account(), request.getRemoteAddr()); + } + + @PostMapping("/auth/password-reset") + public ResponseEntity 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 RoleRequest(String role) {} diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthService.java b/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthService.java index e9081dd..3759702 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthService.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/auth/AuthService.java @@ -256,6 +256,23 @@ public class AuthService { 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) { return "admin".equals(role) || "super_admin".equals(role); } diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/auth/VerificationService.java b/control-plane-java/src/main/java/com/moyi/controlplane/auth/VerificationService.java index 86681b6..fd8c3a3 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/auth/VerificationService.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/auth/VerificationService.java @@ -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","请输入有效邮箱或中国大陆手机号"); 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) public Map 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); 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 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); } 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=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取"); 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); } + + @Transactional(noRollbackFor=ApiException.class) + public Map 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; + } } diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/catalog/CatalogService.java b/control-plane-java/src/main/java/com/moyi/controlplane/catalog/CatalogService.java index 16bbb42..dbec2bb 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/catalog/CatalogService.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/catalog/CatalogService.java @@ -223,7 +223,7 @@ public class CatalogService { private void validatePricing(Object input) { 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); 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(); } @@ -475,20 +475,40 @@ public class CatalogService { model.put("capabilities", readMap(resultSet.getString("capabilities"))); Map pricing = readOptionalMap(resultSet.getString("pricing")); putIfNotNull(model, "pricing", pricing); - model.put("pricingConfigured", pricing != null - && "CNY / 1M tokens".equals(String.valueOf(pricing.get("unit"))) - && pricing.get("input") != null - && pricing.get("output") != null); + model.put("pricingConfigured", pricingConfigured(pricing)); putIfNotNull(model, "priority", resultSet.getObject("priority")); putIfNotNull(model, "maxConcurrency", resultSet.getObject("max_concurrency")); 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")) - || "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)); return model; } + private boolean pricingConfigured(Map 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 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 mapProject(ResultSet resultSet, int rowNumber) throws SQLException { Map project = new LinkedHashMap<>(); project.put("id", resultSet.getString("id")); diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/gateway/ChatMeter.java b/control-plane-java/src/main/java/com/moyi/controlplane/gateway/ChatMeter.java index ece4cbe..dc8a892 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/gateway/ChatMeter.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/gateway/ChatMeter.java @@ -25,8 +25,10 @@ public final class ChatMeter { public static Rates rates(Object value, boolean mock) { if (mock) return new Rates(BigDecimal.ZERO,BigDecimal.ZERO,BigDecimal.ZERO); - if (!(value instanceof Map prices) || !"CNY / 1M tokens".equals(prices.get("unit"))) - throw new ApiException("MODEL_NOT_PRICED","该分组尚未配置人民币 Token 售价",503); + if (!(value instanceof Map prices)) + 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 cached=prices.get("cachedInput")==null?input:price(prices.get("cachedInput")); return new Rates(input,output,cached); diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/provider/OpenAiCompatibleProvider.java b/control-plane-java/src/main/java/com/moyi/controlplane/provider/OpenAiCompatibleProvider.java index 8e6ac81..ab929b3 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/provider/OpenAiCompatibleProvider.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/provider/OpenAiCompatibleProvider.java @@ -12,7 +12,10 @@ import java.io.*; import java.nio.charset.StandardCharsets; 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 java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import jakarta.annotation.PreDestroy; @@ -27,6 +30,7 @@ public class OpenAiCompatibleProvider { private final JdbcTemplate jdbc; private final SecretCipher secretCipher; private final Map 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 int timeoutSeconds; @@ -40,17 +44,18 @@ public class OpenAiCompatibleProvider { this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); this.jdbc = jdbc; 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.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-kimi", new ProviderConfig(environment.getProperty("moyi.providers.kimi.api-key", ""), environment.getProperty("moyi.providers.kimi.base-url", "https://api.moonshot.ai/v1")), - "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-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", 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", 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) { ProviderConfig provider = resolve(providerId); - return provider != null && !provider.apiKey().isBlank(); + return provider != null && provider.hasKey(); } public Map chat(String providerId, String upstreamModel, Map input) { @@ -68,7 +73,7 @@ public class OpenAiCompatibleProvider { private StreamResponse open(String providerId, String upstreamModel, Map input, boolean streaming) { ProviderConfig provider = resolve(providerId); - if (provider == null || provider.apiKey().isBlank()) { + if (provider == null || !provider.hasKey()) { throw new ApiException("PROVIDER_NOT_CONFIGURED", "该模型的供应商尚未配置服务端 API Key", 503); } Map body = new LinkedHashMap<>(input); @@ -76,11 +81,12 @@ public class OpenAiCompatibleProvider { body.put("stream", streaming); if(streaming) body.put("stream_options",Map.of("include_usage",true)); else body.remove("stream_options"); + String apiKey = provider.nextApiKey(); String json = writeJson(body); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(normalizeUrl(provider.baseUrl()) + "/chat/completions")) .timeout(Duration.ofSeconds(timeoutSeconds)) - .header("Authorization", "Bearer " + provider.apiKey()) + .header("Authorization", "Bearer " + apiKey) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(json)) .build(); @@ -176,13 +182,14 @@ public class OpenAiCompatibleProvider { private ProviderConfig resolve(String providerId) { ProviderConfig fixed = providers.get(providerId); - if (fixed != null && !fixed.apiKey().isBlank()) return fixed; + if (fixed != null && fixed.hasKey()) return fixed; try { - Map row = jdbc.queryForMap("SELECT base_url, credential_ciphertext FROM model_providers WHERE id = ? AND status = 'active'", providerId); + Map 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 apiKey = ciphertext.isBlank() ? "" : secretCipher.decrypt(ciphertext); 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) { 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 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 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 apiKeys, String baseUrl, AtomicInteger cursor) { + private ProviderConfig(List 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())); } + } } diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/task/AsyncProviderClient.java b/control-plane-java/src/main/java/com/moyi/controlplane/task/AsyncProviderClient.java new file mode 100644 index 0000000..7d0c32b --- /dev/null +++ b/control-plane-java/src/main/java/com/moyi/controlplane/task/AsyncProviderClient.java @@ -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 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 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 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 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 request(String method, String url, String key, Map 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 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 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 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 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 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 apiKeys, AtomicInteger cursor) { + private Provider(String code, String baseUrl, List apiKeys) { this(code, baseUrl, apiKeys, new AtomicInteger()); } + private String nextApiKey() { return apiKeys.get(Math.floorMod(cursor.getAndIncrement(), apiKeys.size())); } + } +} diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/task/AsyncTaskService.java b/control-plane-java/src/main/java/com/moyi/controlplane/task/AsyncTaskService.java index 1dd5f62..faec877 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/task/AsyncTaskService.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/task/AsyncTaskService.java @@ -11,6 +11,9 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -29,14 +32,23 @@ public class AsyncTaskService { private final int maxQueuedPerModel; private final GatewayGuard gatewayGuard; 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( JdbcTemplate jdbc, ObjectMapper objectMapper, CatalogService catalogService, @Value("${moyi.tasks.max-queued-per-model:100}") int maxQueuedPerModel, GatewayGuard gatewayGuard, - UsageAuditService usage + UsageAuditService usage, + AsyncProviderClient providerClient ) { if (maxQueuedPerModel < 1) throw new IllegalArgumentException("Task queue limit must be positive"); this.jdbc = jdbc; @@ -45,6 +57,7 @@ public class AsyncTaskService { this.maxQueuedPerModel = maxQueuedPerModel; this.gatewayGuard = gatewayGuard; this.usage = usage; + this.providerClient = providerClient; } @Transactional @@ -60,21 +73,38 @@ public class AsyncTaskService { if (model == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404); 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 (!"provider-mock".equals(model.get("providerId"))) { - throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "Java 版尚未接入该供应商的异步执行器", 501); - } + if (!"provider-mock".equals(model.get("providerId")) && providerClient == null) throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "异步执行器未配置", 501); 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); String prompt = String.valueOf(input.getOrDefault("prompt", "")).trim(); 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 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 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(); - 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, ?, ?, ?)", - id, userId, apiKeyId, modelId, taskType, prompt, now, now - ); + try { + jdbc.update( + "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, 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); catalogService.touchKey(key); return taskView(id); @@ -107,6 +137,7 @@ public class AsyncTaskService { } @Scheduled(fixedDelayString = "${moyi.tasks.worker-interval-ms:1000}") + @Transactional public void completeMockTasks() { List 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( @@ -115,6 +146,8 @@ public class AsyncTaskService { "{\"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)); + List> 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 row : pending) pollProviderTask(row); } private Map requireKey(String authorization) { @@ -129,12 +162,13 @@ public class AsyncTaskService { private Map mapTask(ResultSet resultSet, int rowNumber) throws SQLException { Map task = new LinkedHashMap<>(); task.put("id", resultSet.getString("id")); - task.put("provider", "mock"); + task.put("provider", "upstream"); task.put("model", resultSet.getString("model_id")); task.put("status", resultSet.getString("status")); task.put("progress", resultSet.getInt("progress")); task.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class)); task.put("updatedAt", resultSet.getObject("updated_at", OffsetDateTime.class)); + putIfPresent(task, "costAmount", resultSet, "cost_amount"); String result = resultSet.getString("result"); if (result != null) task.put("result", readMap(result)); String error = resultSet.getString("error"); @@ -148,4 +182,119 @@ public class AsyncTaskService { } private OffsetDateTime now() { return OffsetDateTime.now(ZoneOffset.UTC); } + + private String providerTaskId(Map 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 row) { + String taskId = String.valueOf(row.get("id")); + try { + Map 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 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 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 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 result(Map 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 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 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 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 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 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 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 target, String name, ResultSet resultSet, String column) throws SQLException { + Object value = resultSet.getObject(column); + if (value != null) target.put(name, value); + } } diff --git a/control-plane-java/src/main/resources/db/migration/V18__password_reset.sql b/control-plane-java/src/main/resources/db/migration/V18__password_reset.sql new file mode 100644 index 0000000..9006557 --- /dev/null +++ b/control-plane-java/src/main/resources/db/migration/V18__password_reset.sql @@ -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); diff --git a/control-plane-java/src/main/resources/db/migration/V19__tripo_official_endpoint.sql b/control-plane-java/src/main/resources/db/migration/V19__tripo_official_endpoint.sql new file mode 100644 index 0000000..d0db42f --- /dev/null +++ b/control-plane-java/src/main/resources/db/migration/V19__tripo_official_endpoint.sql @@ -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'; diff --git a/control-plane-java/src/main/resources/db/migration/V20__async_task_billing.sql b/control-plane-java/src/main/resources/db/migration/V20__async_task_billing.sql new file mode 100644 index 0000000..198c25c --- /dev/null +++ b/control-plane-java/src/main/resources/db/migration/V20__async_task_billing.sql @@ -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); diff --git a/docs/15-relay-onboarding.md b/docs/15-relay-onboarding.md index 1d95e89..7bc237a 100644 --- a/docs/15-relay-onboarding.md +++ b/docs/15-relay-onboarding.md @@ -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)。 -- 国际站 API Base URL:`https://api.tripo3d.ai/v2/openapi`。 -- 使用 HTTP Bearer API Key;创建任务为 `POST /task`,查询为 `GET /task/{task_id}`。 +- Java 执行器使用 Tripo V3 API Base URL:`https://openapi.tripo3d.ai/v3`。 +- 使用 HTTP Bearer API Key;创建任务为 `POST /generation/text-to-model`,查询为 `GET /tasks/{task_id}`。 - 文生 3D 请求使用 `type=text_to_model`,版本放在 `model_version`,不能按 OpenAI 聊天请求直接转发。 - 当前官方生成文档列出的版本包括 `P1-20260311`、`Turbo-v1.0-20250506`、`v3.1-20260211`、`v3.0-20250812`、`v2.5-20250123` 等,实际选型需结合账号权限及价格。 - 若 Key 来自国内 `platform.tripo3d.com`,使用其对应文档与端点;不能假定 `.ai` 和 `.com` 凭据互通。 -- 建议渠道 Code `tripo-official`、名称 `Tripo 官方`、来源“官方供应商”、协议 HTTP、凭据类型 Bearer Token。先不要把真实 3D 模型作为已可用发布。 -- 7360cf3e 的 Java `AsyncTaskService` 对非 Mock 异步供应商返回 `ASYNC_PROVIDER_NOT_IMPLEMENTED`。必须补齐创建、轮询、状态持久化、错误处理、结果链接与使用记录后,才能在 MOYI 使用官方 Key 测试。 +- 建议渠道 Code `tripo-official`、名称 `Tripo 官方`、来源“官方供应商”、协议 HTTP、凭据类型 Bearer Token。配置真实 Key 后,先用一个低成本模型创建任务并轮询到终态,再把该分组发布给用户。 +- Java 异步执行器已接入 Tripo(`provider-vast`)和 Seedance(`provider-bytedance`)的创建、轮询、状态持久化、失败处理和结果链接;未匹配这两个适配器的异步渠道仍会明确显示为“执行器待接入”,不会伪装成可用。 ## 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`。 -新版提供 OpenAI 兼容聊天的同步/流式转发、文本消息、工具参数透传和输出上限。Responses 原生接口、Anthropic 原生接口、多模态输入、真实图像/视频/3D 执行器仍需单独适配。中转站各模型的具体参数支持需要逐个验证。 +新版提供 OpenAI 兼容聊天的同步/流式转发、文本消息、工具参数透传和输出上限;Tripo 3D 与 Seedance 视频已有对应的异步创建、轮询和结果持久化。Responses 原生接口、Anthropic 原生接口、多模态聊天输入仍需单独适配;未匹配执行器的异步渠道会显示为“执行器待接入”,不会创建假任务。中转站各模型的具体参数支持需要逐个验证。 新版按分组人民币售价预留余额,以实际 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 容器即可。 diff --git a/prototype/src/services/auth.ts b/prototype/src/services/auth.ts index 67a8bba..3c6606f 100644 --- a/prototype/src/services/auth.ts +++ b/prototype/src/services/auth.ts @@ -27,6 +27,8 @@ export interface LoginInput { export interface AuthClient { verificationChannels(): Promise<{ email: boolean; phone: boolean }> sendVerificationCode(account: string, invitationCode: string): Promise<{ retryAfterSeconds: number }> + sendPasswordResetCode(account: string): Promise<{ retryAfterSeconds: number }> + resetPassword(input: { account: string; verificationCode: string; newPassword: string }): Promise health(): Promise<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }> login(input: LoginInput): Promise register(input: RegisterInput): Promise @@ -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('/api/auth/password-reset', { + method: 'POST', body: JSON.stringify(input), + }) + } + async health() { return this.request<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }>('/health') } diff --git a/prototype/src/services/catalog.ts b/prototype/src/services/catalog.ts index cebac05..6f9ad4c 100644 --- a/prototype/src/services/catalog.ts +++ b/prototype/src/services/catalog.ts @@ -30,6 +30,7 @@ export interface CatalogModel { outputTypes: string[] capabilities: Record pricing?: { + price?: number input?: number output?: number cachedInput?: number @@ -41,6 +42,7 @@ export interface CatalogModel { listPriceUsd?: { input?: number; output?: number; cachedInput?: number } } pricingConfigured?: boolean + billingReady?: boolean priority?: number maxConcurrency?: number 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) }) } - 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) }) } diff --git a/prototype/src/types.ts b/prototype/src/types.ts index a85ec44..b71e793 100644 --- a/prototype/src/types.ts +++ b/prototype/src/types.ts @@ -35,6 +35,7 @@ export interface ModelItem { modelKey?: string sourceLabel?: string pricing?: { + price?: number input?: number output?: number cachedInput?: number @@ -46,6 +47,7 @@ export interface ModelItem { listPriceUsd?: { input?: number; output?: number; cachedInput?: number } } pricingConfigured?: boolean + billingReady?: boolean priority?: number maxConcurrency?: number executionReady?: boolean diff --git a/prototype/src/views/AdminConsole.vue b/prototype/src/views/AdminConsole.vue index 57b628c..b21ab8f 100644 --- a/prototype/src/views/AdminConsole.vue +++ b/prototype/src/views/AdminConsole.vue @@ -83,7 +83,7 @@ async function refreshOverviewData(notifyOnSuccess = false) { models.value = mapModels(modelResult.models, providerResult.providers) 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 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 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 @@ -263,6 +263,7 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod logicalModelId: model.logicalModelId, vendorName: model.vendorName, pricingConfigured: model.pricingConfigured, + billingReady: model.billingReady, executionReady: model.executionReady, })) } diff --git a/prototype/src/views/AuthView.vue b/prototype/src/views/AuthView.vue index 5ff1b77..bcb24f5 100644 --- a/prototype/src/views/AuthView.vue +++ b/prototype/src/views/AuthView.vue @@ -66,6 +66,25 @@ async function sendCode() { } 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() { if (!account.value.trim() || !password.value) return emit('notify', '请输入账号和密码') loading.value = true @@ -102,8 +121,24 @@ async function submitRegister() { } } -function submitReset() { - emit('notify', '密码重置服务尚未接入,请联系平台管理员处理') +async function submitReset() { + 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 () => { @@ -187,10 +222,15 @@ onMounted(async () => {

重置密码

-

密码重置服务尚未接入,当前请联系平台管理员处理。

+

通过注册邮箱或手机号获取验证码,设置新的登录密码。

- +
+ + + + +
diff --git a/prototype/src/views/UserConsole.vue b/prototype/src/views/UserConsole.vue index 3c74bf7..5838da7 100644 --- a/prototype/src/views/UserConsole.vue +++ b/prototype/src/views/UserConsole.vue @@ -66,7 +66,7 @@ const galleryModels = computed(() => buildModelCatalog(catalogDe const routes = groups.map(group => catalogModels.value.find(item => item.id === group.id)!).filter(Boolean) const providerNames = [...new Set(routes.map(group => group.provider))] 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 activeModel = ref(emptyModel) @@ -219,7 +219,11 @@ function formatUsdPrice(value: number | undefined) { function standardPriceLabel(model: GalleryModel) { 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` } @@ -231,24 +235,30 @@ function groupDiscountLabel(group: ModelItem) { function groupPriceLabel(group: ModelItem) { const pricing = group.pricing 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 output = pricing.output === undefined ? '待定' : `¥${pricing.output.toLocaleString('zh-CN', { maximumFractionDigits: 8 })}` return `${input} 输入 / ${output} 输出 · ${pricing.unit || 'CNY / 1M tokens'}` } 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) { if (!model.groups.length) 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.billingReady === false)) return '异步按任务计费待配置' return '价格待配置' } 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.billingReady === false)) return '异步按任务计费待配置' return '价格待配置' } @@ -288,7 +298,7 @@ async function refreshOverview() { } 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', '该模型已收录,但分组价格尚未配置,暂时不能调用') activeModel.value = group callMode.value = group.mode @@ -437,7 +447,7 @@ function mapCatalogModels(items: CatalogModel[], providers: Array<{ id: string; ...mapCatalogModel(item), logicalModelId: item.logicalModelId, provider: providerNames.get(item.providerId) || item.providerId, 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" 标准价:{{ group.pricing?.listPriceUsd ? `${formatUsdPrice(group.pricing.listPriceUsd.input)} 输入 / ${formatUsdPrice(group.pricing.listPriceUsd.output)} 输出 · USD / 1M` : '待同步' }} · {{ groupPriceLabel(group) }} · 对外 {{ groupDiscountLabel(group) }} - +