feat: integrate Tripo 3D provider
This commit is contained in:
1 parent
ec51e8c802
commit
18a55346c6
9 files changed
+306
-6
No files matched your search
@@ -3,6 +3,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:ht
|
||||
import { parse as parseUrl } from 'node:url'
|
||||
import { AuthError, AuthService, MemoryAuthRepository, type AuthRepository } from './auth.js'
|
||||
import { CatalogService, MemoryCatalogRepository, type CallMode, type ModelType, type ProviderProtocol } from './catalog.js'
|
||||
import { TripoProvider, TripoProviderError } from './providers/tripo.js'
|
||||
|
||||
const config = {
|
||||
host: process.env.CONTROL_PLANE_HOST || '127.0.0.1',
|
||||
@@ -12,6 +13,8 @@ const config = {
|
||||
passwordPepper: process.env.AUTH_PASSWORD_PEPPER || 'development-only-pepper',
|
||||
databaseUrl: process.env.DATABASE_URL,
|
||||
nodeEnv: process.env.NODE_ENV || 'development',
|
||||
tripoApiKey: process.env.TRIPO_API_KEY,
|
||||
tripoBaseUrl: process.env.TRIPO_BASE_URL,
|
||||
}
|
||||
|
||||
let repository: AuthRepository = new MemoryAuthRepository()
|
||||
@@ -34,6 +37,11 @@ type MockTask = {
|
||||
result?: { format: string; url: string }
|
||||
}
|
||||
const mockTasks = new Map<string, MockTask>()
|
||||
const tripo = config.tripoApiKey ? new TripoProvider({
|
||||
apiKey: config.tripoApiKey,
|
||||
...(config.tripoBaseUrl ? { baseUrl: config.tripoBaseUrl } : {}),
|
||||
}) : undefined
|
||||
const tripoTaskOwners = new Map<string, { userId: string; model: string }>()
|
||||
|
||||
if (config.nodeEnv === 'production' && (!process.env.AUTH_PASSWORD_PEPPER || process.env.AUTH_PASSWORD_PEPPER.length < 32)) {
|
||||
throw new Error('AUTH_PASSWORD_PEPPER must contain at least 32 characters in production')
|
||||
@@ -57,7 +65,7 @@ const server = createServer(async (request, response) => {
|
||||
response.setHeader('Vary', 'Origin')
|
||||
}
|
||||
if (request.method === 'OPTIONS') {
|
||||
response.setHeader('Access-Control-Allow-Headers', 'Content-Type')
|
||||
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
|
||||
response.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
|
||||
response.writeHead(204)
|
||||
response.end()
|
||||
@@ -74,6 +82,7 @@ const server = createServer(async (request, response) => {
|
||||
server.listen(config.port, config.host, () => {
|
||||
console.log(`MOYI Control Plane listening on http://${config.host}:${config.port}`)
|
||||
console.log(config.databaseUrl ? 'Persistence: PostgreSQL' : 'Persistence: in-memory development store')
|
||||
console.log(tripo ? 'Tripo 3D Provider: enabled' : 'Tripo 3D Provider: mock mode')
|
||||
})
|
||||
|
||||
async function route(request: IncomingMessage, response: ServerResponse) {
|
||||
@@ -128,6 +137,23 @@ async function route(request: IncomingMessage, response: ServerResponse) {
|
||||
const model = await catalogModel(modelId)
|
||||
if (model.type !== '3d' || model.mode !== 'async') throw new AuthError('NOT_ASYNC_3D_MODEL', '该模型不是异步 3D 模型', 400)
|
||||
if (!catalog.canInvoke(keyRecord, model.id)) throw new AuthError('MODEL_FORBIDDEN', '当前 Key 无权调用该模型', 403)
|
||||
if (tripo) {
|
||||
const prompt = stringValue(body.prompt).trim()
|
||||
if (!prompt) throw new AuthError('PROMPT_REQUIRED', '3D 生成提示词不能为空')
|
||||
const taskId = await tripo.createTextToModel({
|
||||
prompt,
|
||||
model: stringValue(body.providerModel) || 'v3.1-20260211',
|
||||
...(body.negativePrompt ? { negative_prompt: stringValue(body.negativePrompt) } : {}),
|
||||
...(body.faceLimit !== undefined ? { face_limit: numberValue(body.faceLimit, 'faceLimit') } : {}),
|
||||
...(body.texture !== undefined ? { texture: booleanValue(body.texture, 'texture') } : {}),
|
||||
...(body.pbr !== undefined ? { pbr: booleanValue(body.pbr, 'pbr') } : {}),
|
||||
...(body.smartLowPoly !== undefined ? { smart_low_poly: booleanValue(body.smartLowPoly, 'smartLowPoly') } : {}),
|
||||
})
|
||||
tripoTaskOwners.set(taskId, { userId: keyRecord.userId, model: model.id })
|
||||
const task = await tripo.getTask(taskId)
|
||||
send(response, 202, { task: { ...task, model: model.id } })
|
||||
return
|
||||
}
|
||||
const now = new Date().toISOString()
|
||||
const task: MockTask = { id: `task_${randomToken(14)}`, userId: keyRecord.userId, model: model.id, status: 'queued', createdAt: now, updatedAt: now }
|
||||
mockTasks.set(task.id, task)
|
||||
@@ -145,6 +171,12 @@ async function route(request: IncomingMessage, response: ServerResponse) {
|
||||
const taskId = taskMatch?.[1]
|
||||
if (method === 'GET' && taskId) {
|
||||
const keyRecord = await authenticatePlatformKey(request)
|
||||
const tripoOwner = tripoTaskOwners.get(taskId)
|
||||
if (tripo && tripoOwner) {
|
||||
if (tripoOwner.userId !== keyRecord.userId) throw new AuthError('TASK_NOT_FOUND', '任务不存在', 404)
|
||||
send(response, 200, { task: { ...await tripo.getTask(taskId), model: tripoOwner.model } })
|
||||
return
|
||||
}
|
||||
const task = mockTasks.get(taskId)
|
||||
if (!task || task.userId !== keyRecord.userId) throw new AuthError('TASK_NOT_FOUND', '任务不存在', 404)
|
||||
send(response, 200, { task: publicTask(task) })
|
||||
@@ -352,6 +384,16 @@ function stringValue(value: unknown) {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
function numberValue(value: unknown, field: string) {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) throw new AuthError('INVALID_NUMBER', `${field} 必须是有效数字`)
|
||||
return value
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown, field: string) {
|
||||
if (typeof value !== 'boolean') throw new AuthError('INVALID_BOOLEAN', `${field} 必须是布尔值`)
|
||||
return value
|
||||
}
|
||||
|
||||
async function authenticatePlatformKey(request: IncomingMessage) {
|
||||
const authorization = request.headers.authorization || ''
|
||||
const match = authorization.match(/^Bearer\s+(.+)$/i)
|
||||
@@ -450,6 +492,11 @@ function handleError(response: ServerResponse, error: unknown) {
|
||||
send(response, error.statusCode, { error: { code: error.code, message: error.message } })
|
||||
return
|
||||
}
|
||||
if (error instanceof TripoProviderError) {
|
||||
console.error(`Tripo provider error: ${error.message}`)
|
||||
send(response, 502, { error: { code: 'TRIPO_PROVIDER_ERROR', message: '3D 模型供应商请求失败,请稍后重试' } })
|
||||
return
|
||||
}
|
||||
console.error(error)
|
||||
send(response, 500, { error: { code: 'INTERNAL_ERROR', message: '服务暂时不可用' } })
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user