mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-05 23:54:25 +00:00
Merge pull request #55 from shumaiOne/feat/workflow-bundle-integration
feat(workflow): integrate temporal workflow bundles
This commit is contained in:
@@ -113,15 +113,15 @@ The backend is built with:
|
|||||||
|
|
||||||
The project is a monorepo managed by **Bun Workspaces**. It follows a strictly decoupled architecture where each domain or layer is its own package:
|
The project is a monorepo managed by **Bun Workspaces**. It follows a strictly decoupled architecture where each domain or layer is its own package:
|
||||||
|
|
||||||
- **WebUI (`packages/webui`)**: React-based frontend.
|
- **WebUI (`packages/webui`)**: React-based frontend.
|
||||||
- **API (`packages/api`)**: Hono-based HTTP entry point. Handles requests and calls Core services.
|
- **API (`packages/api`)**: Hono-based HTTP entry point. Handles requests and calls Core services.
|
||||||
- **Core (`packages/core`)**: Business logic, services, and infrastructure utilities.
|
- **Core (`packages/core`)**: Business logic, services, and infrastructure utilities.
|
||||||
- **Database (`packages/db`)**: Prisma client, schema, and migrations.
|
- **Database (`packages/db`)**: Prisma client, schema, and migrations.
|
||||||
- **DTOs (`packages/dtos`)**: Shared type definitions and Zod schemas used by both API and WebUI.
|
- **DTOs (`packages/dtos`)**: Shared type definitions and Zod schemas used by both API and WebUI.
|
||||||
- **Workers**: Specialized packages for background task execution:
|
- **Workers**: Specialized packages for background task execution:
|
||||||
- `@shumai/workflow-core`: Common workflow engine logic.
|
- `@shumai/workflow-core`: Common workflow engine logic.
|
||||||
- `@shumai/agent`: AI agent workflows and activities.
|
- `@shumai/agent`: AI agent workflows and activities.
|
||||||
- `@shumai/transcode`: Media processing workflows and activities.
|
- `@shumai/transcode`: Media processing workflows and activities.
|
||||||
|
|
||||||
### Layered Communication Rules
|
### Layered Communication Rules
|
||||||
|
|
||||||
@@ -380,6 +380,10 @@ To prevent Temporal from indefinitely retrying fatal, expected business validati
|
|||||||
```
|
```
|
||||||
- **Environment Compatibility**: Always use `getActivities()` from `@shumai/workflow-core` to ensure the code works in both Local and Temporal environments.
|
- **Environment Compatibility**: Always use `getActivities()` from `@shumai/workflow-core` to ensure the code works in both Local and Temporal environments.
|
||||||
- **Activity Access**: Activities should be accessed via `getActivities()` within a workflow. Do not call services directly inside a workflow function to maintain Temporal compatibility.
|
- **Activity Access**: Activities should be accessed via `getActivities()` within a workflow. Do not call services directly inside a workflow function to maintain Temporal compatibility.
|
||||||
|
- **Queue Redirection**: Production Temporal workers use worker-specific unique queues for data locality (e.g., local disk access) and consistent state.
|
||||||
|
- Every workflow MUST first call `getAgentWorkerQueueActivity` or `getTranscodeWorkerQueueActivity` via the shared domain queue (e.g., `TaskQueueAgent` or `TaskQueueTranscode`) to obtain the specific queue name for that worker instance.
|
||||||
|
- ALL subsequent activities (including shared DB activities like updating task status) MUST be executed on that specific discovered queue.
|
||||||
|
- The shared domain worker ONLY registers the queue discovery activities. All other activities (shared and domain-specific) are registered on the specific worker.
|
||||||
|
|
||||||
### Activity Patterns
|
### Activity Patterns
|
||||||
|
|
||||||
|
|||||||
+11
-1
@@ -10,7 +10,17 @@ async function run() {
|
|||||||
initAgentWorkflows()
|
initAgentWorkflows()
|
||||||
|
|
||||||
console.log('🚀 Starting Agent Worker...')
|
console.log('🚀 Starting Agent Worker...')
|
||||||
await workflowService.startWorkers(TaskQueueAgent)
|
|
||||||
|
const options: { workflowBundle?: unknown; workflowsPath?: string } = {}
|
||||||
|
if (process.env.NODE_ENV === 'production') {
|
||||||
|
// @ts-ignore: Bun temporal plugin macro
|
||||||
|
const { default: workflowBundle } = await import('./workflows:::workflow')
|
||||||
|
options.workflowBundle = workflowBundle
|
||||||
|
} else {
|
||||||
|
options.workflowsPath = new URL('./workflows.ts', import.meta.url).pathname
|
||||||
|
}
|
||||||
|
|
||||||
|
await workflowService.startWorkers(TaskQueueAgent, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
run().catch((err) => {
|
run().catch((err) => {
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export * from '@shumai/agent/src/workflows/agent-autofill'
|
||||||
|
export * from '@shumai/agent/src/workflows/agent-chat'
|
||||||
|
export * from '@shumai/agent/src/workflows/agent-embedding'
|
||||||
|
export * from '@shumai/agent/src/workflows/agent-tool-call'
|
||||||
|
export * from '@shumai/agent/src/workflows/query-embedding-for-search'
|
||||||
@@ -1,16 +1,25 @@
|
|||||||
import { loadEnvConfig } from '@shumai/core/src/env-loader'
|
import { loadEnvConfig } from '@shumai/core/src/env-loader'
|
||||||
loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
|
loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
|
||||||
|
|
||||||
import { workflowService } from '@shumai/workflow-core'
|
|
||||||
import { TaskQueueTranscode } from '@shumai/workflow-core'
|
|
||||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||||
|
import { TaskQueueTranscode, workflowService } from '@shumai/workflow-core'
|
||||||
|
|
||||||
async function run() {
|
async function run() {
|
||||||
// Initialize workflows and activities
|
// Initialize workflows and activities
|
||||||
initTranscodeWorkflows()
|
initTranscodeWorkflows()
|
||||||
|
|
||||||
console.log('🚀 Starting Transcode Worker...')
|
console.log('🚀 Starting Transcode Worker...')
|
||||||
await workflowService.startWorkers(TaskQueueTranscode)
|
|
||||||
|
const options: { workflowBundle?: unknown; workflowsPath?: string } = {}
|
||||||
|
if (process.env.NODE_ENV === 'production') {
|
||||||
|
// @ts-ignore: Bun temporal plugin macro
|
||||||
|
const { default: workflowBundle } = await import('./workflows:::workflow')
|
||||||
|
options.workflowBundle = workflowBundle
|
||||||
|
} else {
|
||||||
|
options.workflowsPath = new URL('./workflows.ts', import.meta.url).pathname
|
||||||
|
}
|
||||||
|
|
||||||
|
await workflowService.startWorkers(TaskQueueTranscode, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
run().catch((err) => {
|
run().catch((err) => {
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from '@shumai/transcode/src/workflows/transcode'
|
||||||
@@ -3,7 +3,11 @@ import { DatabaseSessionStorage } from '../database-session-storage'
|
|||||||
import { prisma, AssetType, Prisma, type Skill } from '@shumai/db'
|
import { prisma, AssetType, Prisma, type Skill } from '@shumai/db'
|
||||||
import { logger } from '@shumai/core/src/logger'
|
import { logger } from '@shumai/core/src/logger'
|
||||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
import { type AgentTool, type AgentMessage, type SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
import {
|
||||||
|
type AgentTool,
|
||||||
|
type AgentMessage,
|
||||||
|
type SessionTreeEntry,
|
||||||
|
} from '@earendil-works/pi-agent-core'
|
||||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||||
import { ApplicationFailure } from '@temporalio/activity'
|
import { ApplicationFailure } from '@temporalio/activity'
|
||||||
import { assetService } from '@shumai/core/src/asset/asset'
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
|
|||||||
@@ -261,10 +261,7 @@ export async function extractAiMetadataActivity(
|
|||||||
return generatedFiles
|
return generatedFiles
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getEmbeddingContextActivity(params: {
|
export async function getEmbeddingContextActivity(params: { teamId: string; assetId: string }) {
|
||||||
teamId: string
|
|
||||||
assetId: string
|
|
||||||
}) {
|
|
||||||
const team = await prisma.team.findUnique({
|
const team = await prisma.team.findUnique({
|
||||||
where: { id: params.teamId },
|
where: { id: params.teamId },
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -28,17 +28,25 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
let placeholderCommentId: string | undefined
|
let placeholderCommentId: string | undefined
|
||||||
let tmpDir: string | undefined
|
let tmpDir: string | undefined
|
||||||
let transcodeWorkerQueue = ''
|
let transcodeWorkerQueue = ''
|
||||||
|
let agentWorkerQueue = ''
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 0. Discover queues
|
||||||
|
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||||
|
transcodeWorkerQueue = await executeActivity(
|
||||||
|
TaskQueueTranscode,
|
||||||
|
getTranscodeWorkerQueueActivity,
|
||||||
|
)
|
||||||
|
|
||||||
// Update status to processing
|
// Update status to processing
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'processing',
|
status: 'processing',
|
||||||
})
|
})
|
||||||
|
|
||||||
// 0. Create Placeholder Comment
|
// 0. Create Placeholder Comment
|
||||||
const payload = task.payload
|
const payload = task.payload
|
||||||
const placeholder = await executeActivity(TaskQueueAgent, createCommentActivity, {
|
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||||
assetId: task.assetId,
|
assetId: task.assetId,
|
||||||
message: '__AUTOFILL__',
|
message: '__AUTOFILL__',
|
||||||
sessionId: payload?.agent?.sessionId || task.id,
|
sessionId: payload?.agent?.sessionId || task.id,
|
||||||
@@ -47,7 +55,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
placeholderCommentId = placeholder.id
|
placeholderCommentId = placeholder.id
|
||||||
|
|
||||||
// 1. Get Asset
|
// 1. Get Asset
|
||||||
const asset = await executeActivity(TaskQueueAgent, getAssetActivity, task.assetId)
|
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
||||||
const key = asset?.storageKey?.key
|
const key = asset?.storageKey?.key
|
||||||
if (!asset || !asset.project || !key) {
|
if (!asset || !asset.project || !key) {
|
||||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||||
@@ -58,12 +66,6 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
// 2. Prepare Data (Images)
|
// 2. Prepare Data (Images)
|
||||||
const isImage = asset.mediaType?.startsWith('image/') || false
|
const isImage = asset.mediaType?.startsWith('image/') || false
|
||||||
|
|
||||||
// Extraction requires FFmpeg, run on Transcode worker
|
|
||||||
transcodeWorkerQueue = await executeActivity(
|
|
||||||
TaskQueueTranscode,
|
|
||||||
getTranscodeWorkerQueueActivity,
|
|
||||||
)
|
|
||||||
|
|
||||||
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
|
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
|
||||||
assetKey: key,
|
assetKey: key,
|
||||||
})
|
})
|
||||||
@@ -80,12 +82,12 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
if (generatedFiles.length === 0) {
|
if (generatedFiles.length === 0) {
|
||||||
// If no images could be extracted, we can't do much
|
// If no images could be extracted, we can't do much
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId) {
|
||||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
message: 'Autofill completed: No images could be extracted for analysis.',
|
message: 'Autofill completed: No images could be extracted for analysis.',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
})
|
})
|
||||||
@@ -93,15 +95,19 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3. Get Project Autofill Fields
|
// 3. Get Project Autofill Fields
|
||||||
const fields = await executeActivity(TaskQueueAgent, getProjectAutofillFieldsActivity, projectId)
|
const fields = await executeActivity(
|
||||||
|
agentWorkerQueue,
|
||||||
|
getProjectAutofillFieldsActivity,
|
||||||
|
projectId,
|
||||||
|
)
|
||||||
if (fields.length === 0) {
|
if (fields.length === 0) {
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId) {
|
||||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
message: 'Autofill completed: No autofill fields defined in project.',
|
message: 'Autofill completed: No autofill fields defined in project.',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
})
|
})
|
||||||
@@ -109,13 +115,11 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3b. Fetch Agent Context
|
// 3b. Fetch Agent Context
|
||||||
const context = await executeActivity(TaskQueueAgent, getAgentAutofillContextActivity, {
|
const context = await executeActivity(agentWorkerQueue, getAgentAutofillContextActivity, {
|
||||||
teamId,
|
teamId,
|
||||||
})
|
})
|
||||||
|
|
||||||
// 4. Call AI Service
|
// 4. Call AI Service
|
||||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
|
||||||
|
|
||||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||||
teamId,
|
teamId,
|
||||||
images: generatedFiles,
|
images: generatedFiles,
|
||||||
@@ -131,7 +135,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
if (aiResult.usage) {
|
if (aiResult.usage) {
|
||||||
// Update Usage
|
// Update Usage
|
||||||
await executeActivity(TaskQueueAgent, updateTaskUsageActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
inputTokens: aiResult.usage.inputTokens,
|
inputTokens: aiResult.usage.inputTokens,
|
||||||
outputTokens: aiResult.usage.outputTokens,
|
outputTokens: aiResult.usage.outputTokens,
|
||||||
@@ -147,7 +151,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
}))
|
}))
|
||||||
|
|
||||||
if (metadataUpdates.length > 0) {
|
if (metadataUpdates.length > 0) {
|
||||||
await executeActivity(TaskQueueAgent, updateAssetMetadataActivity, {
|
await executeActivity(agentWorkerQueue, updateAssetMetadataActivity, {
|
||||||
assetId: asset.id,
|
assetId: asset.id,
|
||||||
metadata: metadataUpdates,
|
metadata: metadataUpdates,
|
||||||
})
|
})
|
||||||
@@ -155,7 +159,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
// 7. Update Placeholder Comment
|
// 7. Update Placeholder Comment
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId) {
|
||||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
message: 'Autofill completed successfully.',
|
message: 'Autofill completed successfully.',
|
||||||
sessionId: aiResult.sessionId,
|
sessionId: aiResult.sessionId,
|
||||||
@@ -163,7 +167,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update status to completed
|
// Update status to completed
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
})
|
})
|
||||||
@@ -171,9 +175,9 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
|
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
|
||||||
|
|
||||||
// Update placeholder comment with error message
|
// Update placeholder comment with error message
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId && agentWorkerQueue) {
|
||||||
try {
|
try {
|
||||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
|
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
})
|
})
|
||||||
@@ -183,11 +187,13 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update status to failed
|
// Update status to failed
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
if (agentWorkerQueue) {
|
||||||
taskId: task.id,
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
status: 'failed',
|
taskId: task.id,
|
||||||
output: { error: err instanceof Error ? err.message : String(err) },
|
status: 'failed',
|
||||||
})
|
output: { error: err instanceof Error ? err.message : String(err) },
|
||||||
|
})
|
||||||
|
}
|
||||||
throw err
|
throw err
|
||||||
} finally {
|
} finally {
|
||||||
if (tmpDir && transcodeWorkerQueue) {
|
if (tmpDir && transcodeWorkerQueue) {
|
||||||
|
|||||||
@@ -19,10 +19,14 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
} = getActivities()
|
} = getActivities()
|
||||||
|
|
||||||
let placeholderCommentId: string | undefined
|
let placeholderCommentId: string | undefined
|
||||||
|
let agentWorkerQueue = ''
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 0. Discover queue
|
||||||
|
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||||
|
|
||||||
// Update status to processing
|
// Update status to processing
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'processing',
|
status: 'processing',
|
||||||
})
|
})
|
||||||
@@ -47,13 +51,13 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
nonRetryable: true,
|
nonRetryable: true,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
const userComment = await executeActivity(TaskQueueAgent, getCommentActivity, userCommentId)
|
const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
|
||||||
if (!userComment) {
|
if (!userComment) {
|
||||||
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Create Placeholder Comment
|
// 2. Create Placeholder Comment
|
||||||
const placeholder = await executeActivity(TaskQueueAgent, createCommentActivity, {
|
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||||
assetId: task.assetId,
|
assetId: task.assetId,
|
||||||
message: '__CHAT__',
|
message: '__CHAT__',
|
||||||
sessionId: sessionId || 'pending',
|
sessionId: sessionId || 'pending',
|
||||||
@@ -63,7 +67,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
placeholderCommentId = placeholder.id
|
placeholderCommentId = placeholder.id
|
||||||
|
|
||||||
// 3. Get Asset
|
// 3. Get Asset
|
||||||
const asset = await executeActivity(TaskQueueAgent, getAssetActivity, task.assetId)
|
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
||||||
if (!asset || !asset.project) {
|
if (!asset || !asset.project) {
|
||||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||||
}
|
}
|
||||||
@@ -71,7 +75,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
// 4. Initialize Session if missing
|
// 4. Initialize Session if missing
|
||||||
if (!sessionId) {
|
if (!sessionId) {
|
||||||
sessionId = await executeActivity(TaskQueueAgent, initializeAgentSessionActivity, {
|
sessionId = await executeActivity(agentWorkerQueue, initializeAgentSessionActivity, {
|
||||||
teamId,
|
teamId,
|
||||||
agentId: agentId,
|
agentId: agentId,
|
||||||
userCommentId,
|
userCommentId,
|
||||||
@@ -80,7 +84,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 4b. Fetch Agent Context
|
// 4b. Fetch Agent Context
|
||||||
const context = await executeActivity(TaskQueueAgent, getAgentChatContextActivity, {
|
const context = await executeActivity(agentWorkerQueue, getAgentChatContextActivity, {
|
||||||
teamId,
|
teamId,
|
||||||
agentId: agentId,
|
agentId: agentId,
|
||||||
})
|
})
|
||||||
@@ -96,7 +100,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const pathContext = await executeActivity(
|
const pathContext = await executeActivity(
|
||||||
TaskQueueAgent,
|
agentWorkerQueue,
|
||||||
getAssetPathContextActivity,
|
getAssetPathContextActivity,
|
||||||
task.assetId,
|
task.assetId,
|
||||||
)
|
)
|
||||||
@@ -126,8 +130,6 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
folderId = asset.parentId
|
folderId = asset.parentId
|
||||||
}
|
}
|
||||||
|
|
||||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
|
||||||
|
|
||||||
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
||||||
teamId,
|
teamId,
|
||||||
agentId: agentId,
|
agentId: agentId,
|
||||||
@@ -145,9 +147,9 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
// 7. Update Placeholder Comment
|
// 7. Update Placeholder Comment
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId) {
|
||||||
if (aiResult.text.trim() === '__NO_REPLY__') {
|
if (aiResult.text.trim() === '__NO_REPLY__') {
|
||||||
await executeActivity(TaskQueueAgent, deleteCommentActivity, placeholderCommentId)
|
await executeActivity(agentWorkerQueue, deleteCommentActivity, placeholderCommentId)
|
||||||
} else {
|
} else {
|
||||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
message: aiResult.text,
|
message: aiResult.text,
|
||||||
sessionId: aiResult.sessionId,
|
sessionId: aiResult.sessionId,
|
||||||
@@ -157,7 +159,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
// 8. Update Usage
|
// 8. Update Usage
|
||||||
if (aiResult.usage) {
|
if (aiResult.usage) {
|
||||||
await executeActivity(TaskQueueAgent, updateTaskUsageActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
inputTokens: aiResult.usage.inputTokens,
|
inputTokens: aiResult.usage.inputTokens,
|
||||||
outputTokens: aiResult.usage.outputTokens,
|
outputTokens: aiResult.usage.outputTokens,
|
||||||
@@ -166,7 +168,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update status to completed
|
// Update status to completed
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
output: { sessionId: aiResult.sessionId },
|
output: { sessionId: aiResult.sessionId },
|
||||||
@@ -175,14 +177,14 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
console.error(`AgentChat failed for task ${task.id}:`, err)
|
console.error(`AgentChat failed for task ${task.id}:`, err)
|
||||||
|
|
||||||
// Update placeholder comment with error message
|
// Update placeholder comment with error message
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId && agentWorkerQueue) {
|
||||||
try {
|
try {
|
||||||
const errorMessage =
|
const errorMessage =
|
||||||
err instanceof Error && err.message.startsWith('AI error:')
|
err instanceof Error && err.message.startsWith('AI error:')
|
||||||
? `AI error: ${err.message.substring(9)}`
|
? `AI error: ${err.message.substring(9)}`
|
||||||
: 'Sorry, I encountered an error while processing your request.'
|
: 'Sorry, I encountered an error while processing your request.'
|
||||||
|
|
||||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
message: errorMessage,
|
message: errorMessage,
|
||||||
})
|
})
|
||||||
@@ -192,11 +194,13 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update status to failed
|
// Update status to failed
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
if (agentWorkerQueue) {
|
||||||
taskId: task.id,
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
status: 'failed',
|
taskId: task.id,
|
||||||
output: { error: err instanceof Error ? err.message : String(err) },
|
status: 'failed',
|
||||||
})
|
output: { error: err instanceof Error ? err.message : String(err) },
|
||||||
|
})
|
||||||
|
}
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,17 +15,21 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
|||||||
} = getActivities()
|
} = getActivities()
|
||||||
|
|
||||||
let placeholderCommentId: string | undefined
|
let placeholderCommentId: string | undefined
|
||||||
|
let agentWorkerQueue = ''
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 0. Discover queue
|
||||||
|
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||||
|
|
||||||
// Update status to processing
|
// Update status to processing
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'processing',
|
status: 'processing',
|
||||||
})
|
})
|
||||||
|
|
||||||
// 0. Create Placeholder Comment
|
// 0. Create Placeholder Comment
|
||||||
const payload = task.payload
|
const payload = task.payload
|
||||||
const placeholder = await executeActivity(TaskQueueAgent, createCommentActivity, {
|
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||||
assetId: task.assetId,
|
assetId: task.assetId,
|
||||||
message: '__EMBEDDING__',
|
message: '__EMBEDDING__',
|
||||||
sessionId: payload?.agent?.sessionId || task.id,
|
sessionId: payload?.agent?.sessionId || task.id,
|
||||||
@@ -38,13 +42,11 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 1. Fetch Agent Context
|
// 1. Fetch Agent Context
|
||||||
const context = await executeActivity(TaskQueueAgent, getEmbeddingContextActivity, {
|
const context = await executeActivity(agentWorkerQueue, getEmbeddingContextActivity, {
|
||||||
teamId: task.teamId,
|
teamId: task.teamId,
|
||||||
assetId: task.assetId,
|
assetId: task.assetId,
|
||||||
})
|
})
|
||||||
|
|
||||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
|
||||||
|
|
||||||
// Call the activity to generate embeddings
|
// Call the activity to generate embeddings
|
||||||
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
|
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
|
||||||
teamId: task.teamId,
|
teamId: task.teamId,
|
||||||
@@ -54,7 +56,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
// Save computed embeddings
|
// Save computed embeddings
|
||||||
if (result.embeddings.length > 0) {
|
if (result.embeddings.length > 0) {
|
||||||
await executeActivity(TaskQueueAgent, saveAssetEmbeddingsActivity, {
|
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
|
||||||
assetId: task.assetId,
|
assetId: task.assetId,
|
||||||
embeddings: result.embeddings,
|
embeddings: result.embeddings,
|
||||||
})
|
})
|
||||||
@@ -62,7 +64,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
// Update Usage
|
// Update Usage
|
||||||
if (result.usage) {
|
if (result.usage) {
|
||||||
await executeActivity(TaskQueueAgent, updateTaskUsageActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
inputTokens: result.usage.inputTokens,
|
inputTokens: result.usage.inputTokens,
|
||||||
outputTokens: result.usage.outputTokens,
|
outputTokens: result.usage.outputTokens,
|
||||||
@@ -72,14 +74,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
// 7. Update Placeholder Comment
|
// 7. Update Placeholder Comment
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId) {
|
||||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
message: 'Embedding completed successfully.',
|
message: 'Embedding completed successfully.',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update status to completed
|
// Update status to completed
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
})
|
})
|
||||||
@@ -87,9 +89,9 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
|||||||
console.error(`AgentEmbeddingMedia failed for task ${task.id}:`, err)
|
console.error(`AgentEmbeddingMedia failed for task ${task.id}:`, err)
|
||||||
|
|
||||||
// Update placeholder comment with error message
|
// Update placeholder comment with error message
|
||||||
if (placeholderCommentId) {
|
if (placeholderCommentId && agentWorkerQueue) {
|
||||||
try {
|
try {
|
||||||
await executeActivity(TaskQueueAgent, updateCommentActivity, {
|
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||||
commentId: placeholderCommentId,
|
commentId: placeholderCommentId,
|
||||||
message: `Embedding failed: ${err instanceof Error ? err.message : String(err)}`,
|
message: `Embedding failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
})
|
})
|
||||||
@@ -99,11 +101,13 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update status to failed
|
// Update status to failed
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
if (agentWorkerQueue) {
|
||||||
taskId: task.id,
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
status: 'failed',
|
taskId: task.id,
|
||||||
output: { error: err instanceof Error ? err.message : String(err) },
|
status: 'failed',
|
||||||
})
|
output: { error: err instanceof Error ? err.message : String(err) },
|
||||||
|
})
|
||||||
|
}
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,17 @@ import type { WorkflowTask } from '@shumai/db'
|
|||||||
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
||||||
|
|
||||||
export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
||||||
const { updateTaskStatusActivity, executeAgentToolActivity } = getActivities()
|
const { updateTaskStatusActivity, executeAgentToolActivity, getAgentWorkerQueueActivity } =
|
||||||
|
getActivities()
|
||||||
|
|
||||||
|
let agentWorkerQueue = ''
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 0. Discover queue
|
||||||
|
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||||
|
|
||||||
// Update status to processing
|
// Update status to processing
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'processing',
|
status: 'processing',
|
||||||
})
|
})
|
||||||
@@ -22,8 +28,8 @@ export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
const { toolName, args, userId } = payload.agentToolCall
|
const { toolName, args, userId } = payload.agentToolCall
|
||||||
|
|
||||||
// Execute the agent activity on agent_queue
|
// Execute the agent activity on specific queue
|
||||||
const result = await executeActivity(TaskQueueAgent, executeAgentToolActivity, {
|
const result = await executeActivity(agentWorkerQueue, executeAgentToolActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
toolName,
|
toolName,
|
||||||
args,
|
args,
|
||||||
@@ -31,7 +37,7 @@ export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// Update status to completed with output
|
// Update status to completed with output
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
output: result,
|
output: result,
|
||||||
@@ -40,11 +46,13 @@ export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
|||||||
console.error(`AgentToolCall failed for task ${task.id}:`, err)
|
console.error(`AgentToolCall failed for task ${task.id}:`, err)
|
||||||
|
|
||||||
// Update status to failed
|
// Update status to failed
|
||||||
await executeActivity(TaskQueueAgent, updateTaskStatusActivity, {
|
if (agentWorkerQueue) {
|
||||||
taskId: task.id,
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
status: 'failed',
|
taskId: task.id,
|
||||||
output: { error: err instanceof Error ? err.message : String(err) },
|
status: 'failed',
|
||||||
})
|
output: { error: err instanceof Error ? err.message : String(err) },
|
||||||
|
})
|
||||||
|
}
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ import type { WorkflowTask } from '@shumai/db'
|
|||||||
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
||||||
|
|
||||||
export async function queryEmbeddingForSearch(task: WorkflowTask): Promise<void> {
|
export async function queryEmbeddingForSearch(task: WorkflowTask): Promise<void> {
|
||||||
const { generateTextEmbeddingActivity, updateWorkflowTaskActivity } = getActivities()
|
const { generateTextEmbeddingActivity, updateWorkflowTaskActivity, getAgentWorkerQueueActivity } =
|
||||||
|
getActivities()
|
||||||
|
|
||||||
|
let agentWorkerQueue = ''
|
||||||
|
|
||||||
const payload = task.payload as PrismaJson.WorkflowTaskPayload | null
|
const payload = task.payload as PrismaJson.WorkflowTaskPayload | null
|
||||||
const text = payload?.queryEmbeddingForSearch?.text
|
const text = payload?.queryEmbeddingForSearch?.text
|
||||||
@@ -12,21 +15,24 @@ export async function queryEmbeddingForSearch(task: WorkflowTask): Promise<void>
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 0. Discover queue
|
||||||
|
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||||
|
|
||||||
// 1. Mark as processing
|
// 1. Mark as processing
|
||||||
await executeActivity(TaskQueueAgent, updateWorkflowTaskActivity, {
|
await executeActivity(agentWorkerQueue, updateWorkflowTaskActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'processing',
|
status: 'processing',
|
||||||
heartbeat: true,
|
heartbeat: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
// 2. Generate embedding
|
// 2. Generate embedding
|
||||||
const result = await executeActivity(TaskQueueAgent, generateTextEmbeddingActivity, {
|
const result = await executeActivity(agentWorkerQueue, generateTextEmbeddingActivity, {
|
||||||
text,
|
text,
|
||||||
teamId: task.teamId!,
|
teamId: task.teamId!,
|
||||||
})
|
})
|
||||||
|
|
||||||
// 3. Save output and complete
|
// 3. Save output and complete
|
||||||
await executeActivity(TaskQueueAgent, updateWorkflowTaskActivity, {
|
await executeActivity(agentWorkerQueue, updateWorkflowTaskActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
output: { embedding: result.embedding },
|
output: { embedding: result.embedding },
|
||||||
@@ -36,13 +42,15 @@ export async function queryEmbeddingForSearch(task: WorkflowTask): Promise<void>
|
|||||||
})
|
})
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`queryEmbeddingForSearch failed for task ${task.id}:`, err)
|
console.error(`queryEmbeddingForSearch failed for task ${task.id}:`, err)
|
||||||
await executeActivity(TaskQueueAgent, updateWorkflowTaskActivity, {
|
if (agentWorkerQueue) {
|
||||||
taskId: task.id,
|
await executeActivity(agentWorkerQueue, updateWorkflowTaskActivity, {
|
||||||
status: 'failed',
|
taskId: task.id,
|
||||||
output: {
|
status: 'failed',
|
||||||
error: err instanceof Error ? err.message : String(err),
|
output: {
|
||||||
},
|
error: err instanceof Error ? err.message : String(err),
|
||||||
})
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { registerWorkflow, registerActivities } from '@shumai/workflow-core'
|
|
||||||
import { WorkflowTaskType } from '@shumai/db'
|
import { WorkflowTaskType } from '@shumai/db'
|
||||||
import { transcodeMedia } from './workflows/transcode'
|
import { registerActivities, registerWorkflow } from '@shumai/workflow-core'
|
||||||
import * as transcodeActivities from './activities/transcode'
|
import * as transcodeActivities from './activities/transcode'
|
||||||
|
import { transcodeMedia } from './workflows/transcode'
|
||||||
|
|
||||||
export function initTranscodeWorkflows() {
|
export function initTranscodeWorkflows() {
|
||||||
registerWorkflow(WorkflowTaskType.transcode, transcodeMedia)
|
registerWorkflow(WorkflowTaskType.transcode, transcodeMedia)
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import type { WorkflowTask } from '@shumai/db'
|
import type { WorkflowTask } from '@shumai/db'
|
||||||
|
import { executeActivity, getActivities, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||||
|
|
||||||
import { ApplicationFailure } from '@temporalio/workflow'
|
import { ApplicationFailure } from '@temporalio/workflow'
|
||||||
import {
|
|
||||||
getActivities,
|
|
||||||
executeActivity,
|
|
||||||
TaskQueueTranscode,
|
|
||||||
} from '@shumai/workflow-core'
|
|
||||||
|
|
||||||
export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||||
const {
|
const {
|
||||||
@@ -25,19 +22,22 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
|||||||
let workerQueue = ''
|
let workerQueue = ''
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 0. Get Worker-Specific Queue for Transcode
|
||||||
|
workerQueue = await executeActivity(TaskQueueTranscode, getTranscodeWorkerQueueActivity)
|
||||||
|
|
||||||
// 1. Update status to processing
|
// 1. Update status to processing
|
||||||
await executeActivity(TaskQueueTranscode, updateTaskStatusActivity, {
|
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'processing',
|
status: 'processing',
|
||||||
})
|
})
|
||||||
|
|
||||||
await executeActivity(TaskQueueTranscode, updateAssetStatusActivity, {
|
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||||
assetId: task.assetId,
|
assetId: task.assetId,
|
||||||
status: 'processing',
|
status: 'processing',
|
||||||
})
|
})
|
||||||
|
|
||||||
// 2. Get Asset
|
// 2. Get Asset
|
||||||
const asset = await executeActivity(TaskQueueTranscode, getAssetActivity, task.assetId)
|
const asset = await executeActivity(workerQueue, getAssetActivity, task.assetId)
|
||||||
const key = asset?.storageKey?.key
|
const key = asset?.storageKey?.key
|
||||||
if (!asset || !key) {
|
if (!asset || !key) {
|
||||||
throw ApplicationFailure.create({
|
throw ApplicationFailure.create({
|
||||||
@@ -46,9 +46,6 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Get Worker-Specific Queue for Transcode
|
|
||||||
workerQueue = await executeActivity(TaskQueueTranscode, getTranscodeWorkerQueueActivity)
|
|
||||||
|
|
||||||
// 4. Download Media to Tmp
|
// 4. Download Media to Tmp
|
||||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||||
assetKey: key,
|
assetKey: key,
|
||||||
@@ -173,29 +170,31 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 11. Update Asset Media and Status
|
// 11. Update Asset Media and Status
|
||||||
await executeActivity(TaskQueueTranscode, updateAssetMediaActivity, {
|
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||||
assetId: asset.id,
|
assetId: asset.id,
|
||||||
mediaInfo,
|
mediaInfo,
|
||||||
})
|
})
|
||||||
|
|
||||||
await executeActivity(TaskQueueTranscode, updateAssetStatusActivity, {
|
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||||
assetId: asset.id,
|
assetId: asset.id,
|
||||||
status: 'processed',
|
status: 'processed',
|
||||||
})
|
})
|
||||||
|
|
||||||
// 12. Update Task Status
|
// 12. Update Task Status
|
||||||
await executeActivity(TaskQueueTranscode, updateTaskStatusActivity, {
|
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
})
|
})
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`TranscodeMedia failed for task ${task.id}:`, err)
|
console.error(`TranscodeMedia failed for task ${task.id}:`, err)
|
||||||
// Update status to failed
|
// Update status to failed
|
||||||
await executeActivity(TaskQueueTranscode, updateTaskStatusActivity, {
|
if (workerQueue) {
|
||||||
taskId: task.id,
|
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||||
status: 'failed',
|
taskId: task.id,
|
||||||
output: { error: err instanceof Error ? err.message : String(err) },
|
status: 'failed',
|
||||||
})
|
output: { error: err instanceof Error ? err.message : String(err) },
|
||||||
|
})
|
||||||
|
}
|
||||||
throw err
|
throw err
|
||||||
} finally {
|
} finally {
|
||||||
if (tmpDir && workerQueue) {
|
if (tmpDir && workerQueue) {
|
||||||
|
|||||||
@@ -9,7 +9,9 @@ export async function getAgentWorkerQueueActivity(): Promise<string> {
|
|||||||
return 'agent_queue'
|
return 'agent_queue'
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAssetStatusActivity(params: { assetId: string }): Promise<AssetStatus | null> {
|
export async function getAssetStatusActivity(params: {
|
||||||
|
assetId: string
|
||||||
|
}): Promise<AssetStatus | null> {
|
||||||
const asset = await prisma.asset.findUnique({
|
const asset = await prisma.asset.findUnique({
|
||||||
where: { id: params.assetId },
|
where: { id: params.assetId },
|
||||||
select: { status: true },
|
select: { status: true },
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { WorkflowTask } from '@shumai/db'
|
import { prisma, registerWorkflowTrigger, WorkflowTask } from '@shumai/db'
|
||||||
|
import path from 'path'
|
||||||
|
import * as taskActivities from './activities/task'
|
||||||
import { Executor } from './executor'
|
import { Executor } from './executor'
|
||||||
import { LocalExecutor } from './local-executor'
|
import { LocalExecutor } from './local-executor'
|
||||||
import { TemporalExecutor } from './temporal-executor'
|
import { TemporalExecutor } from './temporal-executor'
|
||||||
import { prisma, registerWorkflowTrigger } from '@shumai/db'
|
|
||||||
|
|
||||||
export class WorkflowService {
|
export class WorkflowService {
|
||||||
private executor: Executor
|
private executor: Executor
|
||||||
@@ -56,7 +57,10 @@ export class WorkflowService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Starts Temporal workers for specific task queues
|
// Starts Temporal workers for specific task queues
|
||||||
async startWorkers(queue: string): Promise<void> {
|
async startWorkers(
|
||||||
|
queue: string,
|
||||||
|
options: { workflowBundle?: unknown; workflowsPath?: string } = {},
|
||||||
|
): Promise<void> {
|
||||||
const type = process.env.WORKFLOW_EXECUTOR || 'local'
|
const type = process.env.WORKFLOW_EXECUTOR || 'local'
|
||||||
if (type === 'temporal') {
|
if (type === 'temporal') {
|
||||||
const { Worker, NativeConnection } = await import('@temporalio/worker')
|
const { Worker, NativeConnection } = await import('@temporalio/worker')
|
||||||
@@ -85,17 +89,51 @@ export class WorkflowService {
|
|||||||
sharedActivities.getTranscodeWorkerQueueActivity = async () => workerSpecificQueue
|
sharedActivities.getTranscodeWorkerQueueActivity = async () => workerSpecificQueue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { workflowBundle, workflowsPath } = options
|
||||||
|
|
||||||
const sharedWorker = await Worker.create({
|
const sharedWorker = await Worker.create({
|
||||||
connection,
|
connection,
|
||||||
|
// The workflowBundle is a pre-bundled set of workflows, its internal structure
|
||||||
|
// is managed by the Temporal worker and doesn't need explicit typing here.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
...(workflowBundle ? { workflowBundle: workflowBundle as any } : {}),
|
||||||
|
...(workflowsPath ? { workflowsPath } : {}),
|
||||||
activities: sharedActivities,
|
activities: sharedActivities,
|
||||||
taskQueue: queue,
|
taskQueue: queue,
|
||||||
|
|
||||||
|
bundlerOptions: {
|
||||||
|
webpackConfigHook: (config) => {
|
||||||
|
config.resolve = config.resolve || {}
|
||||||
|
config.resolve.alias = {
|
||||||
|
...config.resolve.alias,
|
||||||
|
// Find the exact absolute path to the package directory
|
||||||
|
'@temporalio/workflow': path.dirname(
|
||||||
|
require.resolve('@temporalio/workflow/package.json'),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
return config
|
||||||
|
},
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const specificWorker = await Worker.create({
|
const specificWorker = await Worker.create({
|
||||||
connection,
|
connection,
|
||||||
// No workflows needed for the unique queue
|
// Register both domain-specific activities and shared task activities
|
||||||
activities,
|
activities: { ...activities, ...taskActivities },
|
||||||
taskQueue: workerSpecificQueue,
|
taskQueue: workerSpecificQueue,
|
||||||
|
bundlerOptions: {
|
||||||
|
webpackConfigHook: (config) => {
|
||||||
|
config.resolve = config.resolve || {}
|
||||||
|
config.resolve.alias = {
|
||||||
|
...config.resolve.alias,
|
||||||
|
// Find the exact absolute path to the package directory
|
||||||
|
'@temporalio/workflow': path.dirname(
|
||||||
|
require.resolve('@temporalio/workflow/package.json'),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
return config
|
||||||
|
},
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
await Promise.all([sharedWorker.run(), specificWorker.run()])
|
await Promise.all([sharedWorker.run(), specificWorker.run()])
|
||||||
|
|||||||
+4
-1
@@ -21,8 +21,11 @@
|
|||||||
"@shumai/db/test": ["packages/db/src/test.ts"],
|
"@shumai/db/test": ["packages/db/src/test.ts"],
|
||||||
"@shumai/dtos": ["packages/dtos/src/index.ts"],
|
"@shumai/dtos": ["packages/dtos/src/index.ts"],
|
||||||
"@shumai/workflow-core": ["packages/workflow-core/src/index.ts"],
|
"@shumai/workflow-core": ["packages/workflow-core/src/index.ts"],
|
||||||
|
"@shumai/workflow-core/src/*": ["packages/workflow-core/src/*"],
|
||||||
"@shumai/agent": ["packages/agent/src/index.ts"],
|
"@shumai/agent": ["packages/agent/src/index.ts"],
|
||||||
"@shumai/transcode": ["packages/transcode/src/index.ts"]
|
"@shumai/agent/src/*": ["packages/agent/src/*"],
|
||||||
|
"@shumai/transcode": ["packages/transcode/src/index.ts"],
|
||||||
|
"@shumai/transcode/src/*": ["packages/transcode/src/*"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"exclude": ["node_modules"]
|
"exclude": ["node_modules"]
|
||||||
|
|||||||
Reference in New Issue
Block a user