111 lines
7.1 KiB
Java
111 lines
7.1 KiB
Java
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())); }
|
|||
|
|
}
|
|||
|
|
}
|