feat: replace preset metrics with live data

This commit is contained in:
wlx committed 2026-08-26 17:24:03 +08:00
1 parent 6dcc1504e2
commit 6de29ebd6d
10 files changed
+419 -326

No files matched your search

+116 -4
View File
@@ -27,6 +27,19 @@ const auth = new AuthService(repository, {
passwordPepper: config.passwordPepper,
})
const catalog = new CatalogService(new MemoryCatalogRepository())
type UsageEvent = {
id: string
userId: string
kind: 'call' | 'task'
model: string
status: 'queued' | 'running' | 'succeeded' | 'failed'
createdAt: string
updatedAt: string
latencyMs?: number
taskId?: string
inputUnits?: number
outputUnits?: number
}
type MockTask = {
id: string
userId: string
@@ -37,6 +50,7 @@ type MockTask = {
result?: { format: string; url: string }
}
const mockTasks = new Map<string, MockTask>()
const usageEvents: UsageEvent[] = []
const tripo = config.tripoApiKey ? new TripoProvider({
apiKey: config.tripoApiKey,
...(config.tripoBaseUrl ? { baseUrl: config.tripoBaseUrl } : {}),
@@ -112,6 +126,7 @@ async function route(request: IncomingMessage, response: ServerResponse) {
}
if (method === 'POST' && path === '/v1/chat/completions') {
const startedAt = Date.now()
const keyRecord = await authenticatePlatformKey(request)
const body = await readJson(request)
const modelId = stringValue(body.model)
@@ -119,13 +134,27 @@ async function route(request: IncomingMessage, response: ServerResponse) {
if (model.mode === 'async') throw new AuthError('ASYNC_MODEL', '该模型需要使用异步任务接口', 400)
if (!catalog.canInvoke(keyRecord, model.id)) throw new AuthError('MODEL_FORBIDDEN', '当前 Key 无权调用该模型', 403)
const prompt = extractPrompt(body.messages)
const content = `MOYI Mock 已收到:${prompt || '(空消息)'}`
const completedAt = new Date().toISOString()
usageEvents.push({
id: `usage_${randomToken(14)}`,
userId: keyRecord.userId,
kind: 'call',
model: model.id,
status: 'succeeded',
createdAt: completedAt,
updatedAt: completedAt,
latencyMs: Date.now() - startedAt,
inputUnits: prompt.length,
outputUnits: content.length,
})
send(response, 200, {
id: `chatcmpl-${randomToken(10)}`,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: model.id,
choices: [{ index: 0, message: { role: 'assistant', content: `MOYI Mock 已收到:${prompt || '(空消息)'}` }, finish_reason: 'stop' }],
usage: { prompt_tokens: prompt.length, completion_tokens: 12, total_tokens: prompt.length + 12 },
choices: [{ index: 0, message: { role: 'assistant', content }, finish_reason: 'stop' }],
usage: { prompt_tokens: prompt.length, completion_tokens: content.length, total_tokens: prompt.length + content.length },
})
return
}
@@ -150,6 +179,7 @@ async function route(request: IncomingMessage, response: ServerResponse) {
...(body.smartLowPoly !== undefined ? { smart_low_poly: booleanValue(body.smartLowPoly, 'smartLowPoly') } : {}),
})
tripoTaskOwners.set(taskId, { userId: keyRecord.userId, model: model.id })
recordTaskUsage(keyRecord.userId, model.id, taskId, 'queued')
send(response, 202, {
task: {
id: taskId,
@@ -165,11 +195,13 @@ async function route(request: IncomingMessage, response: ServerResponse) {
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)
recordTaskUsage(keyRecord.userId, model.id, task.id, 'queued')
setTimeout(() => {
const current = mockTasks.get(task.id)
if (!current) return
const updatedAt = new Date().toISOString()
mockTasks.set(task.id, { ...current, status: 'succeeded', updatedAt, result: { format: 'glb', url: `https://mock.moyi.ai/tasks/${task.id}/result.glb` } })
updateTaskUsage(task.id, 'succeeded', updatedAt)
}, 500)
send(response, 202, { task: publicTask(task) })
return
@@ -182,7 +214,11 @@ async function route(request: IncomingMessage, response: ServerResponse) {
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 } })
const providerTask = await tripo.getTask(taskId)
if (providerTask.status === 'queued' || providerTask.status === 'running' || providerTask.status === 'succeeded' || providerTask.status === 'failed') {
updateTaskUsage(taskId, providerTask.status)
}
send(response, 200, { task: { ...providerTask, model: tripoOwner.model } })
return
}
const task = mockTasks.get(taskId)
@@ -192,7 +228,11 @@ async function route(request: IncomingMessage, response: ServerResponse) {
}
if (method === 'GET' && path === '/health') {
send(response, 200, { status: 'ok', service: 'moyi-control-plane' })
send(response, 200, {
status: 'ok',
service: 'moyi-control-plane',
capabilities: { verificationCode: false, passwordReset: false },
})
return
}
@@ -244,6 +284,12 @@ async function route(request: IncomingMessage, response: ServerResponse) {
return
}
if (method === 'GET' && path === '/api/overview') {
const user = await auth.requireUser(token)
send(response, 200, buildOverview(user.id))
return
}
if (method === 'GET' && path === '/api/projects') {
const user = await auth.requireUser(token)
send(response, 200, { projects: await catalog.listProjects(user.id) })
@@ -426,6 +472,72 @@ function randomToken(length: number) {
return Buffer.from(randomBytes(Math.ceil(length * 0.75))).toString('base64url').slice(0, length)
}
function recordTaskUsage(userId: string, model: string, taskId: string, status: UsageEvent['status']) {
const now = new Date().toISOString()
usageEvents.push({
id: `usage_${randomToken(14)}`,
userId,
kind: 'task',
model,
status,
taskId,
createdAt: now,
updatedAt: now,
})
}
function updateTaskUsage(taskId: string, status: UsageEvent['status'], updatedAt = new Date().toISOString()) {
const event = usageEvents.find((item) => item.taskId === taskId)
if (!event) return
event.status = status
event.updatedAt = updatedAt
}
function buildOverview(userId: string) {
const now = new Date()
const startOfToday = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()))
const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1))
const events = usageEvents.filter((event) => event.userId === userId)
const calls = events.filter((event) => event.kind === 'call')
const tasks = events.filter((event) => event.kind === 'task')
const latencySamples = calls.flatMap((event) => event.latencyMs === undefined ? [] : [event.latencyMs])
const completedTasks = tasks.filter((event) => event.status === 'succeeded' || event.status === 'failed')
const series = Array.from({ length: 7 }, (_, index) => {
const date = new Date(startOfToday)
date.setUTCDate(date.getUTCDate() - (6 - index))
const nextDate = new Date(date)
nextDate.setUTCDate(nextDate.getUTCDate() + 1)
return {
date: date.toISOString().slice(0, 10),
count: events.filter((event) => {
const createdAt = new Date(event.createdAt)
return createdAt >= date && createdAt < nextDate
}).length,
}
})
return {
generatedAt: now.toISOString(),
callsToday: calls.filter((event) => new Date(event.createdAt) >= startOfToday).length,
callsThisMonth: calls.filter((event) => new Date(event.createdAt) >= startOfMonth).length,
...(latencySamples.length
? { averageLatencyMs: Math.round(latencySamples.reduce((total, value) => total + value, 0) / latencySamples.length) }
: {}),
asyncTasks: tasks.length,
...(completedTasks.length
? { asyncSuccessRate: completedTasks.filter((event) => event.status === 'succeeded').length / completedTasks.length * 100 }
: {}),
tasks: {
queued: tasks.filter((event) => event.status === 'queued').length,
running: tasks.filter((event) => event.status === 'running').length,
succeeded: tasks.filter((event) => event.status === 'succeeded').length,
failed: tasks.filter((event) => event.status === 'failed').length,
},
series,
ledger: [],
}
}
function publicTask(task: MockTask) {
return {
id: task.id,