2026-09-27 14:58:24 +08:00
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 ;
2026-09-27 18:05:35 +08:00
import java.util.concurrent.ConcurrentHashMap ;
import java.util.concurrent.ConcurrentMap ;
2026-09-27 14:58:24 +08:00
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 ;
2026-09-27 18:05:35 +08:00
/** Keep rotation state across submit/poll calls; rebuilding a Provider on
* every request otherwise selected the first upstream key forever. */
private final ConcurrentMap < String , AtomicInteger > keyCursors = new ConcurrentHashMap <> ();
2026-09-27 14:58:24 +08:00
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 );
String code = String . valueOf ( row . get ( "code" ));
List < String > keys = new ArrayList <> ();
2026-09-27 16:37:19 +08:00
if ( ! key . isBlank ()) keys . add ( key );
2026-09-27 14:58:24 +08:00
addEnvironmentKeys ( keys , code );
addEnvironmentKeys ( keys , id );
2026-09-27 16:37:19 +08:00
// Tripo's official API key may be supplied through the server secret
// environment so it never has to be committed or exposed in SQL.
if ( key . isBlank () && isTripo ( code , String . valueOf ( row . get ( "base_url" )))) {
addEnvironmentKeys ( keys , "TRIPO_API_KEY" );
addEnvironmentKeys ( keys , "MOYI_TRIPO_API_KEY" );
}
if ( keys . isEmpty ()) throw new ApiException ( "PROVIDER_NOT_CONFIGURED" , "异步渠道尚未配置 API Key" , 503 );
2026-09-27 18:05:35 +08:00
return new Provider ( code , String . valueOf ( row . get ( "base_url" )), keys . stream (). distinct (). toList (), keyCursors . computeIfAbsent ( id , ignored -> new AtomicInteger ()));
2026-09-27 14:58:24 +08:00
} 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 ) {
2026-09-27 16:37:19 +08:00
String name = alias . endsWith ( "_API_KEY" ) ? alias : "MOYI_UPSTREAM_API_KEYS_" + alias . toUpperCase ( java . util . Locale . ROOT ). replace ( '-' , '_' );
2026-09-27 14:58:24 +08:00
String configured = environment . getProperty ( name );
if ( configured != null && ! configured . isBlank ()) for ( String value : configured . split ( "\\|" )) if ( ! value . isBlank ()) keys . add ( value . trim ());
}
2026-09-27 16:37:19 +08:00
private boolean isTripo ( String code , String baseUrl ) {
String normalizedCode = code == null ? "" : code . toLowerCase ( java . util . Locale . ROOT );
String normalizedUrl = baseUrl == null ? "" : baseUrl . toLowerCase ( java . util . Locale . ROOT );
return normalizedCode . contains ( "tripo" ) || normalizedUrl . contains ( "tripo3d" );
}
2026-09-27 14:58:24 +08:00
private record Provider ( String code , String baseUrl , List < String > apiKeys , AtomicInteger cursor ) {
private String nextApiKey () { return apiKeys . get ( Math . floorMod ( cursor . getAndIncrement (), apiKeys . size ())); }
}
}