2026-05-19 16:05:09 +08:00
|
|
|
import { Connection, Client } from '@temporalio/client'
|
|
|
|
|
import { WorkflowTask, WorkflowTaskType } from '@/generated/prisma/client'
|
|
|
|
|
import { Executor } from './executor'
|
|
|
|
|
|
|
|
|
|
export const TASK_QUEUE_DB = 'db_queue'
|
|
|
|
|
|
|
|
|
|
export class TemporalExecutor implements Executor {
|
|
|
|
|
private client: Client | null = null
|
|
|
|
|
private connection: Connection | null = null
|
|
|
|
|
|
|
|
|
|
constructor(private address: string = 'localhost:7233') {}
|
|
|
|
|
|
|
|
|
|
async submit(task: WorkflowTask): Promise<string> {
|
|
|
|
|
const client = await this.getClient()
|
|
|
|
|
const workflowId = `${task.type}-${task.id}`
|
|
|
|
|
|
|
|
|
|
let workflowName: string
|
|
|
|
|
switch (task.type) {
|
|
|
|
|
case WorkflowTaskType.ai_embedding:
|
2026-05-27 23:40:14 +08:00
|
|
|
workflowName = 'agentEmbeddingWorkflow'
|
2026-05-19 16:05:09 +08:00
|
|
|
break
|
2026-05-28 20:14:11 +08:00
|
|
|
case WorkflowTaskType.query_embedding_for_search:
|
|
|
|
|
workflowName = 'queryEmbeddingForSearch'
|
|
|
|
|
break
|
2026-05-19 16:05:09 +08:00
|
|
|
case WorkflowTaskType.ai_metadata_autofill:
|
2026-05-27 23:40:14 +08:00
|
|
|
workflowName = 'agentAutofillWorkflow'
|
2026-05-19 16:05:09 +08:00
|
|
|
break
|
|
|
|
|
case WorkflowTaskType.chat:
|
2026-05-27 23:40:14 +08:00
|
|
|
workflowName = 'agentChatWorkflow'
|
2026-05-19 16:05:09 +08:00
|
|
|
break
|
|
|
|
|
case WorkflowTaskType.transcode:
|
|
|
|
|
workflowName = 'transcodeWorkflow'
|
|
|
|
|
break
|
|
|
|
|
default:
|
|
|
|
|
throw new Error(`Unknown task type: ${task.type}`)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const handle = await client.workflow.start(workflowName, {
|
|
|
|
|
taskQueue: TASK_QUEUE_DB,
|
|
|
|
|
workflowId,
|
|
|
|
|
args: [task],
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return handle.workflowId
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
start(): void {
|
|
|
|
|
// Client doesn't need explicit start
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
close(): void {
|
|
|
|
|
if (this.connection) {
|
|
|
|
|
this.connection.close()
|
|
|
|
|
this.connection = null
|
|
|
|
|
this.client = null
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async getClient(): Promise<Client> {
|
|
|
|
|
if (this.client) return this.client
|
|
|
|
|
this.connection = await Connection.connect({ address: this.address })
|
|
|
|
|
this.client = new Client({ connection: this.connection })
|
|
|
|
|
return this.client
|
|
|
|
|
}
|
|
|
|
|
}
|