mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 14:04:50 +00:00
Compare commits
4
Commits
882b03e083
..
v0.6.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e05a23bcc2 | ||
|
|
d957ab2339 | ||
|
|
1fcd7245ea | ||
|
|
176b7f0eab |
@@ -74,3 +74,31 @@ jobs:
|
||||
provenance: false
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
# Extract metadata for Docker (Transcode Worker)
|
||||
- name: Extract metadata for Docker (Transcode Worker)
|
||||
id: meta-transcode
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
shumaione/shumai-transcode
|
||||
crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai-transcode
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=ref,event=branch,enable=${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && !inputs.pr && !inputs.tag) }}
|
||||
type=raw,value=pr-${{ inputs.pr }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.pr != '' && inputs.tag == '' }}
|
||||
type=raw,value=${{ inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.tag != '' }}
|
||||
labels: |
|
||||
org.opencontainers.image.revision=${{ steps.checkout.outputs.commit }}
|
||||
|
||||
# Build and push Docker image (Transcode Worker)
|
||||
- name: Build and push Docker image (Transcode Worker)
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
context: .
|
||||
file: ./Dockerfile.transcode
|
||||
push: true
|
||||
provenance: false
|
||||
tags: ${{ steps.meta-transcode.outputs.tags }}
|
||||
labels: ${{ steps.meta-transcode.outputs.labels }}
|
||||
|
||||
@@ -25,3 +25,5 @@ code_quality.md
|
||||
# Paraglide JS
|
||||
packages/webui/paraglide
|
||||
|
||||
runner-package.json
|
||||
|
||||
|
||||
@@ -391,7 +391,7 @@ We use **DBOS Transact** (`@dbos-inc/dbos-sdk`) as our unified workflow engine f
|
||||
|
||||
### Dynamic Registration
|
||||
|
||||
To avoid circular dependencies, workflows and activities are dynamically registered onto the workflow registry at bootstrap time via initializer functions (e.g., `initAgentWorkflows()`, `initTranscodeWorkflows()`).
|
||||
To avoid circular dependencies, workflows are dynamically registered onto the workflow registry at bootstrap time via initializer functions (e.g., `initAgentWorkflows()`, `initTranscodeWorkflows()`).
|
||||
|
||||
### Non-Retryable Error Handling
|
||||
|
||||
@@ -409,17 +409,27 @@ To prevent the engine from indefinitely retrying fatal, expected business valida
|
||||
|
||||
- **Definition**: Define workflows as exported async functions.
|
||||
```typescript
|
||||
import { activityA, activityB } from '../activities/my-activities'
|
||||
|
||||
export async function myWorkflow(task: WorkflowTask): Promise<void> {
|
||||
const { activityA, activityB } = getActivities()
|
||||
await activityA({ ... })
|
||||
await activityB({ ... })
|
||||
}
|
||||
```
|
||||
- **Activity Access**: Activities should be accessed via `getActivities()` within a workflow.
|
||||
- **Activity Invocation**: Workflows import and call activities directly as standard async functions.
|
||||
- **Queues**: Workflows are dispatched to dedicated task queues (e.g. `TaskQueueTranscode`, `TaskQueueAgent`) managed by DBOS.
|
||||
|
||||
### Activity Patterns
|
||||
|
||||
- **Definition**: Wrap exported activity functions with `defineStep` from `@shumai/workflow-core`.
|
||||
```typescript
|
||||
export const myActivity = defineStep(
|
||||
async function myActivity(params: MyActivityParams): Promise<MyActivityResult> {
|
||||
...
|
||||
},
|
||||
{ runOnCancel: false }, // optional: set runOnCancel: true for cleanup/status handlers
|
||||
)
|
||||
```
|
||||
- **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database directly. Database (Prisma) queries or updates are allowed in all activity types (e.g., agent or transcode) for simplicity.
|
||||
|
||||
### Worker Identity & Multi-Instance Deployments
|
||||
@@ -432,6 +442,10 @@ In multi-replica deployments (e.g., multiple transcode or agent worker instances
|
||||
- In Docker/container environments, `HOSTNAME` (container ID) is automatically used.
|
||||
- On bare metal/multi-process hosts, `process.pid` and an instance suffix are appended to guarantee uniqueness.
|
||||
|
||||
### Durable Step File Exchange
|
||||
|
||||
Intermediate files passed across steps must be saved to durable storage (S3) by the producing step, consuming steps must use `ensureLocalMediaFile` (or S3 fetch) rather than assuming local `/tmp` presence, and any purely temporary S3 scratch files must be cleaned up in a `finally` block.
|
||||
|
||||
## Import conventions
|
||||
|
||||
- When importing across workspace packages, always use absolute workspace imports (e.g. `import { prisma } from '@shumai/db'`, `import { teamService } from '@shumai/core/src/team/team'`).
|
||||
|
||||
+13
-5
@@ -10,13 +10,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Fixed
|
||||
|
||||
* **workflow**: Fix an issue where creating background tasks from within an active workflow step caused an invalid transition error during video processing
|
||||
* **cli**: Fix an issue where running `shumai regenerate-embeddings` would report success without enqueueing tasks to background workers
|
||||
* **workflow**: Fix an issue where multiple worker replicas could share the same executor identity and disrupt live workflows on startup recovery
|
||||
* **workflow**: Fix an issue where changes to queue concurrency environment variables were ignored after initial registration
|
||||
|
||||
### Changed
|
||||
|
||||
## [0.6.0] - 2026-10-20
|
||||
|
||||
### Added
|
||||
|
||||
* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete AWS EKS deployment example (`eks/`) featuring KEDA queue-driven autoscaling, idle-timeout auto-drain worker mode, and Scale-to-Zero On-Demand Graviton5 instances for media processing
|
||||
* **storage**: Support configuring a separate public endpoint (`AWS_PUBLIC_ENDPOINT_URL_S3`) for browser-facing presigned URLs while preserving internal cluster endpoints for backend workers
|
||||
|
||||
### Fixed
|
||||
|
||||
* **transcode**: Fix an issue where PDF, 3D model, and image background transcode workflows could fail with missing temporary file errors if a worker restarted or recovered midway through processing
|
||||
* **webui**: Improve file list and detail loading with matching skeleton layouts, a persistent sidebar carousel to eliminate layout shift, and smoothed video poster previews
|
||||
|
||||
### Changed
|
||||
|
||||
* **workflow**: Migrate the background workflow engine to DBOS, unifying all-in-one and dedicated worker deployments using the existing PostgreSQL database without requiring a separate Temporal cluster
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
#syntax=docker/dockerfile:1.7-labs
|
||||
# Stage 1: Builder
|
||||
FROM oven/bun:1.4.2 AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package.json bun.lock ./
|
||||
COPY --parents packages/*/package.json ./
|
||||
COPY --parents apps/*/package.json ./
|
||||
COPY patches/ ./patches/
|
||||
|
||||
# Install dependencies (including devDependencies for build tools)
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
# Copy source code
|
||||
COPY . .
|
||||
|
||||
# Build transcode worker bundle
|
||||
RUN bun run build.ts transcode
|
||||
|
||||
# Generate runner-package.json for the runner stage
|
||||
RUN bun run scripts/extract-runtime-deps.ts
|
||||
|
||||
# Stage 2: Runner
|
||||
FROM oven/bun:1.4.2 AS runner
|
||||
|
||||
# Install transcoding system dependencies and Jellyfin-FFmpeg (with VA-API/hardware acceleration support)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
curl \
|
||||
ca-certificates \
|
||||
gosu \
|
||||
poppler-utils \
|
||||
imagemagick \
|
||||
fonts-noto-cjk \
|
||||
libraw-bin \
|
||||
libimage-exiftool-perl \
|
||||
&& . /etc/os-release \
|
||||
&& TARGETARCH=$(dpkg --print-architecture) \
|
||||
&& FFMPEG_VERSION="8.1.2-5" \
|
||||
&& curl -fsSL -o /tmp/jellyfin-ffmpeg.deb "https://github.com/jellyfin/jellyfin-ffmpeg/releases/download/v${FFMPEG_VERSION}/jellyfin-ffmpeg8_${FFMPEG_VERSION}-${VERSION_CODENAME}_${TARGETARCH}.deb" \
|
||||
&& apt-get install -y --no-install-recommends /tmp/jellyfin-ffmpeg.deb \
|
||||
&& rm -f /tmp/jellyfin-ffmpeg.deb \
|
||||
&& ldconfig /usr/lib/jellyfin-ffmpeg/lib \
|
||||
&& ln -sf /usr/lib/jellyfin-ffmpeg/ffmpeg /usr/local/bin/ffmpeg \
|
||||
&& ln -sf /usr/lib/jellyfin-ffmpeg/ffprobe /usr/local/bin/ffprobe \
|
||||
&& ln -sf /usr/lib/jellyfin-ffmpeg/ffmpeg /usr/bin/ffmpeg \
|
||||
&& ln -sf /usr/lib/jellyfin-ffmpeg/ffprobe /usr/bin/ffprobe \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set up working directory and make it owned by the bun user, ensure video/render group access
|
||||
RUN usermod -a -G video,render bun 2>/dev/null || true \
|
||||
&& mkdir -p /app/data \
|
||||
&& chown -R bun:bun /app
|
||||
|
||||
# Switch to the non-root bun user
|
||||
USER bun
|
||||
WORKDIR /app
|
||||
|
||||
# Install runtime dependencies with exact matching versions extracted from the builder stage
|
||||
COPY --chown=bun:bun --from=builder /app/runner-package.json ./package.json
|
||||
RUN bun install
|
||||
|
||||
# Copy build artifacts
|
||||
COPY --chown=bun:bun --from=builder /app/dist ./
|
||||
|
||||
# Switch back to root at the end so the container runs the entrypoint as root
|
||||
USER root
|
||||
COPY scripts/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
|
||||
# Expose "bun transcode-worker.js" as "shumai-transcode" CLI command
|
||||
RUN printf '#!/bin/sh\nexec bun /app/transcode-worker.js "$@"\n' > /usr/local/bin/shumai-transcode \
|
||||
&& chmod +x /usr/local/bin/shumai-transcode
|
||||
|
||||
ENTRYPOINT ["docker-entrypoint.sh"]
|
||||
|
||||
# Default command: start transcode worker
|
||||
CMD ["shumai-transcode"]
|
||||
@@ -29,7 +29,8 @@ Shumai is an open-source Frame.io alternative built for creative teams to collab
|
||||
* **Frame-by-Frame Annotations & Comments**: Leave precise feedback with frame-specific drawing tools and timestamped comments on both video and image assets.
|
||||
* **Secure Sharing & Collections**: Create private share links and curated media collections for clients, stakeholders, and collaborators.
|
||||
* **Granular Access Control**: Manage workspace permissions with team-level and project-level role-based access control.
|
||||
* **Distributed Transcoding via Temporal**: Offload resource-intensive video transcoding to a background worker pool orchestrated by Temporal.
|
||||
* **Durable Workflows via DBOS**: Run background tasks and AI agent workflows orchestrated reliably by DBOS on PostgreSQL with automatic recovery and fault tolerance.
|
||||
* **Scalable Deployment on Kubernetes**: Horizontally autoscale video transcoding on multiple instances. See [EKS Deployment Example](eks/README.md).
|
||||
* **Custom Asset Metadata**: Define dynamic metadata fields tailored to your production pipeline.
|
||||
* **Share Link Watermarking**: Protect shared media with customizable text and image watermarks, and save watermark as reusable templates.
|
||||
* **Wide File Format Support**: Preview common creative file formats, including images (with PSD support), videos, audio, and documents, while allowing any file type to be uploaded and stored.
|
||||
@@ -73,7 +74,7 @@ The ultimate goal is an **agentic Kanban**, where agents and team members can wo
|
||||
|
||||
## Installation
|
||||
|
||||
Below is a quickstart guide for running Shumai with local storage. For advanced configuration options (including S3-compatible storage and Temporal workflow orchestration), see our [Documentation](https://docs.shumai.one/getting-started/overview).
|
||||
Below is a quickstart guide for running Shumai with local storage. For advanced configuration options (including S3-compatible storage and distributed worker orchestration), see our [Documentation](https://docs.shumai.one/getting-started/overview).
|
||||
|
||||
### Option 1: Docker Compose
|
||||
|
||||
|
||||
+3
-2
@@ -29,7 +29,8 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
|
||||
* **逐帧标注和评论**:支持按帧进行精确反馈,可以直接在视频和图片素材上画重点、写评论,还能留下时间戳。
|
||||
* **安全分享和合集管理**:可以生成私密分享链接,也能整理成精选合集,方便给客户、同事和合作方查看。
|
||||
* **细粒度权限控制**:支持按团队、项目设置角色权限,方便管理不同成员的访问范围。
|
||||
* **基于 Temporal 的分布式转码**:把吃资源的视频转码任务交给后台 worker 池处理,由 Temporal 统一调度。
|
||||
* **基于 DBOS 的持久化工作流**:后台任务与 AI 工作流基于 PostgreSQL 由 DBOS 统一持久化编排与调度,具备自动恢复和容错能力。
|
||||
* **Kubernetes 弹性扩缩容部署**:支持在多个实例上横向自动扩缩容视频转码工作负载。详见 [EKS 部署示例](eks/README.md)。
|
||||
* **自定义素材元数据**:可以按你的制作流程,自由定义动态元数据字段。
|
||||
* **分享链接水印**:通过可自定义的文字和图片水印保护共享媒体,并将水印配置保存为模板以便重复使用。
|
||||
* **丰富的文件格式支持**:支持预览常见创意文件格式,包括图片(支持 PSD)、视频、音频和文档,同时可上传和存储任意类型的文件。
|
||||
@@ -69,7 +70,7 @@ Shumai 也将项目管理融入了创意工作流程。 内置的看板可以帮
|
||||
|
||||
## 安装指南
|
||||
|
||||
以下是使用本地存储运行 Shumai 的快速上手指南。如需了解高级配置(包括 S3 兼容存储配置、Temporal 工作流编排等),请参阅我们的[官方文档](https://docs.shumai.one/getting-started/overview)。
|
||||
以下是使用本地存储运行 Shumai 的快速上手指南。如需了解高级配置(包括 S3 兼容存储配置、分布式 worker 编排等),请参阅我们的[官方文档](https://docs.shumai.one/getting-started/overview)。
|
||||
|
||||
### 方案一:使用 Docker Compose(推荐)
|
||||
<details>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/premiere-uxp",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "commonjs",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -14,9 +14,85 @@ async function run() {
|
||||
// Initialize workflows and activities
|
||||
initTranscodeWorkflows()
|
||||
|
||||
console.log('🚀 Starting Transcode Worker...')
|
||||
let idleTimeoutMs = process.env.SHUMAI_WORKER_IDLE_TIMEOUT_MS
|
||||
? parseInt(process.env.SHUMAI_WORKER_IDLE_TIMEOUT_MS, 10)
|
||||
: 0
|
||||
|
||||
const idleTimeoutArg = process.argv.find((arg) => arg.startsWith('--idle-timeout='))
|
||||
if (idleTimeoutArg) {
|
||||
const val = parseInt(idleTimeoutArg.split('=')[1], 10)
|
||||
if (!isNaN(val)) idleTimeoutMs = val
|
||||
}
|
||||
|
||||
if (idleTimeoutMs > 0) {
|
||||
console.log(
|
||||
`🚀 Starting Transcode Worker with idle timeout (${idleTimeoutMs / 1000}s auto-drain)...`,
|
||||
)
|
||||
} else {
|
||||
console.log('🚀 Starting Transcode Worker (persistent daemon mode)...')
|
||||
}
|
||||
|
||||
await workflowService.startWorkers(TaskQueueTranscode)
|
||||
|
||||
let isShuttingDown = false
|
||||
let idleTimer: Timer | null = null
|
||||
let activeWorkflows = 0
|
||||
|
||||
const shutdown = async () => {
|
||||
if (isShuttingDown) return
|
||||
isShuttingDown = true
|
||||
if (idleTimer) {
|
||||
clearTimeout(idleTimer)
|
||||
idleTimer = null
|
||||
}
|
||||
console.log('Shutting down Transcode Worker gracefully...')
|
||||
try {
|
||||
await workflowService.shutdownWorkers()
|
||||
} catch (err) {
|
||||
console.error('Error during Transcode Worker shutdown:', err)
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (idleTimeoutMs > 0) {
|
||||
const resetIdleTimer = () => {
|
||||
if (idleTimer) {
|
||||
clearTimeout(idleTimer)
|
||||
idleTimer = null
|
||||
}
|
||||
if (activeWorkflows === 0 && !isShuttingDown) {
|
||||
idleTimer = setTimeout(async () => {
|
||||
console.log(
|
||||
`[Transcode Worker] Inactive for ${idleTimeoutMs / 1000}s with no active workflows, shutting down.`,
|
||||
)
|
||||
await shutdown()
|
||||
}, idleTimeoutMs)
|
||||
}
|
||||
}
|
||||
|
||||
// Start idle timer immediately on startup in case no tasks are enqueued
|
||||
resetIdleTimer()
|
||||
|
||||
workflowService.getExecutor().on('workflowStarted', (task) => {
|
||||
activeWorkflows++
|
||||
console.log(
|
||||
`[Transcode Worker] Claimed task ${task.id} (active: ${activeWorkflows}), cancelling idle timer.`,
|
||||
)
|
||||
if (idleTimer) {
|
||||
clearTimeout(idleTimer)
|
||||
idleTimer = null
|
||||
}
|
||||
})
|
||||
|
||||
workflowService.getExecutor().on('workflowFinished', async ({ taskId }) => {
|
||||
activeWorkflows = Math.max(0, activeWorkflows - 1)
|
||||
console.log(`[Transcode Worker] Completed task ${taskId} (active: ${activeWorkflows}).`)
|
||||
resetIdleTimer()
|
||||
})
|
||||
}
|
||||
|
||||
process.on('SIGINT', shutdown)
|
||||
process.on('SIGTERM', shutdown)
|
||||
}
|
||||
|
||||
handleDaemonCommands('shumai-transcode', run).catch((err) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -109,6 +109,7 @@ async function run() {
|
||||
}
|
||||
|
||||
workflowService.start(listenQueues)
|
||||
workflowService.startStaleTaskRecovery()
|
||||
|
||||
const isProd = process.env.NODE_ENV === 'production'
|
||||
|
||||
@@ -206,8 +207,10 @@ async function run() {
|
||||
|
||||
console.log(`🚀 Server running at ${server.url}`)
|
||||
|
||||
const shutdown = () => {
|
||||
const shutdown = async () => {
|
||||
console.log('\nShutting down gracefully...')
|
||||
workflowService.stopStaleTaskRecovery()
|
||||
await workflowService.shutdownWorkers().catch(() => {})
|
||||
assetService.stopCleanupJob()
|
||||
server.stop(true)
|
||||
process.exit(0)
|
||||
|
||||
@@ -7,38 +7,42 @@ import { rm } from 'fs/promises'
|
||||
console.log('\n🚀 Starting build process...\n')
|
||||
|
||||
const outdir = 'dist'
|
||||
const target = process.argv[2] || 'all'
|
||||
|
||||
if (existsSync(outdir)) {
|
||||
if (existsSync(outdir) && target === 'all') {
|
||||
console.log(`🗑️ Cleaning previous build at ${outdir}`)
|
||||
await rm(outdir, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
await Bun.build({
|
||||
entrypoints: ['./apps/web/src/index.ts'],
|
||||
root: '.',
|
||||
target: 'bun',
|
||||
outdir: outdir,
|
||||
minify: true,
|
||||
splitting: true,
|
||||
naming: '[name].[ext]',
|
||||
plugins: [tailwindPlugin, bunPluginPino({ transports: ['pino-pretty'] })],
|
||||
external: ['@dbos-inc/dbos-sdk', 'pg', 'pdfkit'],
|
||||
// compile: {
|
||||
// outfile: 'Shumai',
|
||||
// autoloadBunfig: true,
|
||||
// autoloadDotenv: true,
|
||||
// autoloadTsconfig: true,
|
||||
// autoloadPackageJson: true,
|
||||
// },
|
||||
define: {
|
||||
'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
},
|
||||
})
|
||||
if (target === 'all' || target === 'web') {
|
||||
await Bun.build({
|
||||
entrypoints: ['./apps/web/src/index.ts'],
|
||||
root: '.',
|
||||
target: 'bun',
|
||||
outdir: outdir,
|
||||
minify: true,
|
||||
splitting: true,
|
||||
naming: '[name].[ext]',
|
||||
plugins: [tailwindPlugin, bunPluginPino({ transports: ['pino-pretty'] })],
|
||||
external: ['@dbos-inc/dbos-sdk', 'pg', 'pdfkit'],
|
||||
define: {
|
||||
'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
for (const worker of [
|
||||
{ entrypoint: './apps/transcode/src/index.ts', naming: 'transcode-worker.[ext]' },
|
||||
{ entrypoint: './apps/agent/src/index.ts', naming: 'agent-worker.[ext]' },
|
||||
]) {
|
||||
const allWorkers = [
|
||||
{
|
||||
name: 'transcode',
|
||||
entrypoint: './apps/transcode/src/index.ts',
|
||||
naming: 'transcode-worker.[ext]',
|
||||
},
|
||||
{ name: 'agent', entrypoint: './apps/agent/src/index.ts', naming: 'agent-worker.[ext]' },
|
||||
]
|
||||
|
||||
const workersToBuild = target === 'all' ? allWorkers : allWorkers.filter((w) => w.name === target)
|
||||
|
||||
for (const worker of workersToBuild) {
|
||||
await Bun.build({
|
||||
entrypoints: [worker.entrypoint],
|
||||
root: '.',
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"bin": {
|
||||
"shumai-agent": "./src/index.ts",
|
||||
},
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
"apps/cli": {
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"bin": {
|
||||
"shumai-cli": "./src/index.ts",
|
||||
},
|
||||
@@ -60,7 +60,7 @@
|
||||
},
|
||||
"apps/premiere-uxp": {
|
||||
"name": "@shumai/premiere-uxp",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@shumai/api": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
@@ -114,7 +114,7 @@
|
||||
},
|
||||
"apps/transcode": {
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"bin": {
|
||||
"shumai-transcode": "./src/index.ts",
|
||||
},
|
||||
@@ -126,7 +126,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/api": "workspace:*",
|
||||
@@ -146,7 +146,7 @@
|
||||
},
|
||||
"packages/agent": {
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.74",
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
@@ -169,7 +169,7 @@
|
||||
},
|
||||
"packages/api": {
|
||||
"name": "@shumai/api",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
"@shumai/core": "workspace:*",
|
||||
@@ -183,7 +183,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@shumai/core",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@ai-sdk/alibaba": "2.0.38",
|
||||
"@ai-sdk/amazon-bedrock": "5.0.67",
|
||||
@@ -244,7 +244,7 @@
|
||||
},
|
||||
"packages/db": {
|
||||
"name": "@shumai/db",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@prisma/adapter-pg": "7.10.0",
|
||||
@@ -260,7 +260,7 @@
|
||||
},
|
||||
"packages/dtos": {
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"zod": "4.5.4",
|
||||
@@ -268,7 +268,7 @@
|
||||
},
|
||||
"packages/e2e": {
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@google/genai": "2.28.0",
|
||||
@@ -283,11 +283,11 @@
|
||||
},
|
||||
"packages/tableprinter": {
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
},
|
||||
"packages/transcode": {
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -298,7 +298,7 @@
|
||||
},
|
||||
"packages/webui": {
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.7.0",
|
||||
"@dnd-kit/abstract": "0.5.0",
|
||||
@@ -400,7 +400,7 @@
|
||||
},
|
||||
"packages/workflow-core": {
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"dependencies": {
|
||||
"@dbos-inc/dbos-sdk": "5.2.11",
|
||||
"@shumai/core": "workspace:*",
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
services:
|
||||
# --- Shumai Application Services ---
|
||||
postgres:
|
||||
image: pgvector/pgvector:pg18
|
||||
container_name: shumai_postgres
|
||||
environment:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
shumai:
|
||||
image: shumaione/shumai:latest
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- shumai_data:/app/data
|
||||
environment:
|
||||
DATABASE_URL: postgres://shumai:shumai_password@postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
STORAGE_BACKEND: s3
|
||||
AWS_ENDPOINT_URL_S3: S3_ENDPOINT_URL
|
||||
S3_REGION: S3_REGION
|
||||
S3_BUCKET: BUCKET_NAME
|
||||
S3_ACCESS_KEY_ID: ID
|
||||
S3_SECRET_ACCESS_KEY: KEY
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
WORKFLOW_EXECUTOR: temporal
|
||||
TEMPORAL_ADDRESS: temporal:7233
|
||||
GEMINI_API_KEY: KEY
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
temporal:
|
||||
condition: service_healthy
|
||||
|
||||
# --- Temporal Services ---
|
||||
temporal:
|
||||
image: temporalio/auto-setup:latest
|
||||
container_name: temporal_server
|
||||
environment:
|
||||
- DB=postgres12
|
||||
- DB_PORT=5432
|
||||
- POSTGRES_USER=shumai
|
||||
- POSTGRES_PWD=shumai_password
|
||||
- POSTGRES_SEEDS=postgres
|
||||
- BIND_ON_IP=0.0.0.0
|
||||
ports:
|
||||
- '7233:7233'
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
'CMD-SHELL',
|
||||
'temporal operator cluster health --address localhost:7233 || temporal operator cluster health --address $$(hostname -i):7233',
|
||||
]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
start_period: 30s
|
||||
retries: 10
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
temporal-ui:
|
||||
image: temporalio/ui:latest
|
||||
container_name: temporal_ui
|
||||
environment:
|
||||
- TEMPORAL_ADDRESS=temporal:7233
|
||||
ports:
|
||||
- '8080:8080'
|
||||
depends_on:
|
||||
temporal:
|
||||
condition: service_healthy
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
shumai_data:
|
||||
@@ -3,6 +3,24 @@ title: "Changelog"
|
||||
description: "Recent updates, new features, and improvements in Shumai"
|
||||
---
|
||||
|
||||
<Update label="v0.6.0" description="October 20, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete AWS EKS deployment example (`eks/`) featuring KEDA queue-driven autoscaling, idle-timeout auto-drain worker mode, and Scale-to-Zero On-Demand Graviton5 instances for media processing
|
||||
* **storage**: Support configuring a separate public endpoint (`AWS_PUBLIC_ENDPOINT_URL_S3`) for browser-facing presigned URLs while preserving internal cluster endpoints for backend workers
|
||||
|
||||
### Fixed
|
||||
|
||||
* **transcode**: Fix an issue where PDF, 3D model, and image background transcode workflows could fail with missing temporary file errors if a worker restarted or recovered midway through processing
|
||||
* **webui**: Improve file list and detail loading with matching skeleton layouts, a persistent sidebar carousel to eliminate layout shift, and smoothed video poster previews
|
||||
|
||||
### Changed
|
||||
|
||||
* **workflow**: Migrate the background workflow engine to DBOS, unifying all-in-one and dedicated worker deployments using the existing PostgreSQL database without requiring a separate Temporal cluster
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="v0.5.3" description="October 16, 2026">
|
||||
|
||||
### Added
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
title: Deploy with Distributed Workers
|
||||
description: Configure a high-scale production deployment using dedicated background workers, DBOS, and S3-compatible storage.
|
||||
---
|
||||
|
||||
For production environments or workloads with high-volume video processing and heavy AI agent usage, running background tasks on a single server can cause bottlenecks. Shumai resolves this by decoupling the web dashboard from background processing through dedicated worker nodes orchestrated by **DBOS Transact**.
|
||||
|
||||
All background tasks (media transcoding, AI embeddings, agent tasks) are dispatched to durable task queues (`transcode_queue` and `agent_queue`) hosted directly in PostgreSQL. No separate external cluster (like Temporal) is required.
|
||||
|
||||
---
|
||||
|
||||
## How it Works
|
||||
|
||||
In a distributed deployment, the core Shumai web application handles user requests, database updates, and file uploads, while delegating durable background workflows to specialized worker instances via PostgreSQL task queues.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
UserUpload[User Uploads Video / Triggers Agent] --> WebApp[Shumai Web UI / API]
|
||||
WebApp -->|Enqueue Task| DB[(PostgreSQL / DBOS Queues)]
|
||||
DB -->|Queue: transcode_queue| TranscodeWorker[Transcode Worker Machine]
|
||||
DB -->|Queue: agent_queue| AgentWorker[Agent Worker Machine]
|
||||
```
|
||||
|
||||
- **Transcoding Workers**: Can be run on GPU-accelerated or high-CPU compute instances.
|
||||
- **AI Agent Workers**: Can be run on isolated, sandboxed hosts to safely execute automation scripts.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Storage Requirement**: Because the core application and the background workers run on separate machines in a distributed setup, **you must configure an S3-compatible storage backend** (such as AWS S3, Cloudflare R2, or MinIO). Local storage (`STORAGE_BACKEND=local`) is not supported in this mode because the workers and the web application do not share a common filesystem.
|
||||
|
||||
---
|
||||
|
||||
## Step 1: Deploy the Core Web Application
|
||||
|
||||
On your primary host machine, run PostgreSQL and the main Shumai web application.
|
||||
|
||||
To instruct the main web application to handle only API and UI traffic without running background worker queues locally, set `SHUMAI_WORKERS=none`:
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
STORAGE_BACKEND=s3
|
||||
AWS_ENDPOINT_URL_S3=https://your-s3-endpoint.com
|
||||
S3_BUCKET=shumai
|
||||
S3_REGION=us-east-1
|
||||
S3_ACCESS_KEY_ID=your-access-key-id
|
||||
S3_SECRET_ACCESS_KEY=your-secret-access-key
|
||||
SHUMAI_WORKERS=none
|
||||
BETTER_AUTH_SECRET=your-random-32-character-secret-key
|
||||
```
|
||||
|
||||
When started with `SHUMAI_WORKERS=none` (or `--workers=none`), the web server starts immediately without polling or consuming tasks from the transcode or agent queues.
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Configure & Run Dedicated Workers
|
||||
|
||||
On your specialized worker machines, configure each worker with a `.env` file referencing the shared PostgreSQL database and S3 storage:
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@<primary-host-ip>:5432/shumai_db?schema=public
|
||||
STORAGE_BACKEND=s3
|
||||
AWS_ENDPOINT_URL_S3=https://your-s3-endpoint.com
|
||||
S3_BUCKET=shumai
|
||||
S3_REGION=us-east-1
|
||||
S3_ACCESS_KEY_ID=your-access-key-id
|
||||
S3_SECRET_ACCESS_KEY=your-secret-access-key
|
||||
CONCURRENCY_TRANSCODE=1
|
||||
CONCURRENCY_AGENT=5
|
||||
```
|
||||
|
||||
### Media Transcoding Worker
|
||||
|
||||
Run this on your media processing nodes (requires system installations of `ffmpeg` and `ffprobe`):
|
||||
|
||||
```bash
|
||||
npm install -g @shumai-one/shumai-transcode
|
||||
shumai-transcode
|
||||
```
|
||||
|
||||
Alternatively, you can run the transcode worker using the dedicated lightweight Docker image:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name shumai-transcode-worker \
|
||||
--env-file .env \
|
||||
shumaione/shumai-transcode:latest
|
||||
```
|
||||
|
||||
(You can also use the all-in-one image: `docker run -d --name shumai-transcode-worker --env-file .env shumaione/shumai:latest shumai-transcode`.)
|
||||
|
||||
### AI Agent Worker
|
||||
|
||||
Run this on your sandboxed agent execution nodes (requires sandbox dependencies like `bubblewrap` or `sandbox-exec`):
|
||||
|
||||
```bash
|
||||
npm install -g @shumai-one/shumai-agent
|
||||
shumai-agent
|
||||
```
|
||||
|
||||
Alternatively, you can run the agent worker using the official Docker image:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name shumai-agent-worker \
|
||||
--env-file .env \
|
||||
--cap-add=SYS_ADMIN \
|
||||
shumaione/shumai:latest shumai-agent
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **For Bun Users:** Since the worker package binaries contain a `#!/usr/bin/env node` shebang, running `shumai-transcode` or `shumai-agent` directly will run under Node.js. If you wish to run them using Bun, prefix the commands with `bun run --bun` (e.g., `bun run --bun shumai-transcode` or `bun run --bun shumai-agent`).
|
||||
|
||||
---
|
||||
|
||||
## Worker Concurrency & Multi-Instance Deployments
|
||||
|
||||
### Concurrency Tuning
|
||||
|
||||
Workers pull tasks from PostgreSQL queues based on configurable concurrency limits:
|
||||
|
||||
- `CONCURRENCY_TRANSCODE`: Maximum concurrent video transcoding jobs per worker (defaults to `1`).
|
||||
- `CONCURRENCY_AGENT`: Maximum concurrent agent and embedding workflows per worker (defaults to `5`, recommend setting to `1` when paired with a local `embedding-server`).
|
||||
|
||||
### Replica Identity
|
||||
|
||||
When running multiple replicas of the transcode or agent worker across multiple machines or pods:
|
||||
|
||||
- `DbosExecutor` automatically derives a unique per-instance ID from the machine hostname and process ID to ensure startup recovery only re-enqueues tasks belonging to that specific instance.
|
||||
- **Custom Worker ID**: Set `SHUMAI_WORKERS_ID` (or `SHUMAI_WORKER_ID`) if you wish to assign an explicit identifier.
|
||||
- **Kubernetes**: In Kubernetes Pods, set `POD_NAME` (via Downward API `fieldRef: { fieldPath: metadata.name }`) to provide stable, unique per-pod identity across pod restarts.
|
||||
|
||||
---
|
||||
|
||||
## Scalable Deployment on Kubernetes & AWS EKS
|
||||
|
||||
For production cloud deployments requiring high-throughput media processing, Shumai can be deployed on Kubernetes or **AWS Elastic Kubernetes Service (AWS EKS)** with automated scale-to-zero queue-driven scaling via **KEDA (Kubernetes Event-driven Autoscaling)**.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
User([User / Web Browser]) -->|Port 80/3000| Server[Pod: shumai-server<br/>SHUMAI_WORKERS=agent]
|
||||
Server -->|Enqueue to transcode_queue| DB[(PostgreSQL: pgvector18<br/>dbos.workflow_status)]
|
||||
Server -->|Direct Uploads / Stream Proxies| Storage[(S3 / Garage Storage)]
|
||||
|
||||
KEDA[KEDA ScaledJob<br/>PostgreSQL Trigger<br/>min: 0, max: 10] -.->|Monitors Queue| DB
|
||||
KEDA -->|Spawns Jobs for queue| Job1[Job: shumai-transcode-1<br/>Auto-drain worker]
|
||||
KEDA -->|Spawns Jobs for queue| JobN[Job: shumai-transcode-N<br/>Auto-drain worker]
|
||||
|
||||
Job1 -->|Fetch Source / Store Proxies| Storage
|
||||
JobN -->|Fetch Source / Store Proxies| Storage
|
||||
Job1 -->|Mark Complete & Exit 0| DB
|
||||
JobN -->|Mark Complete & Exit 0| DB
|
||||
|
||||
CA[Cluster Autoscaler / Karpenter] -.->|Scale-to-Zero On-Demand Nodes<br/>0 to 10 instances| JobN
|
||||
```
|
||||
|
||||
### Key Architectural Highlights
|
||||
|
||||
- **Decoupled Stateless Workers**: The main web and API server, database, and storage run on reliable On-Demand compute (`c9g.large`, `SHUMAI_WORKERS=agent`), delegating media transcoding to background workers orchestrated via DBOS task queues in PostgreSQL.
|
||||
- **Dedicated Graviton5 On-Demand Compute (`c9g.xlarge`)**: Media encoding runs on 4 vCPU / 8 GiB RAM AWS Graviton5 On-Demand instances (~$0.174/hr), utilizing ARM64 vector optimizations and high-speed DDR5 memory without involuntary Spot interruptions.
|
||||
- **Queue-Driven Scale-to-Zero via KEDA**: KEDA monitors `dbos.workflow_status` for enqueued and pending transcode tasks and dynamically provisions Kubernetes `ScaledJob` resources (scaling 0 to 10). When the queue is empty, transcode nodes scale down to zero (`minSize: 0`), incurring **$0/hr** in worker costs.
|
||||
- **Idle-Timeout Auto-Drain**: Worker pods continuously process queued tasks with concurrency `1`. When the queue is fully drained and a pod has been idle for 10 seconds (`SHUMAI_WORKER_IDLE_TIMEOUT_MS=10000`), it exits `0` cleanly so the node can scale down, processing batch uploads without cold-start pod churn.
|
||||
- **Automated Stale Task Recovery**: The core web server runs an integrated recovery sweep that detects stale or orphaned tasks (e.g. from node crash) and resumes them automatically in DBOS, with a 3-attempt cap to safely handle poison-pill media.
|
||||
|
||||
### Complete Deployment Example & Source Code
|
||||
|
||||
For the full, production-ready manifests, declarative `eksctl` cluster configuration, and step-by-step walkthrough, see the **[EKS Deployment Example](https://github.com/shumaiOne/shumai/tree/main/eks)** in the Shumai repository:
|
||||
|
||||
👉 **[View the EKS Deployment Guide & Manifests on GitHub](https://github.com/shumaiOne/shumai/tree/main/eks)**
|
||||
|
||||
The repository includes:
|
||||
|
||||
- [`eks/eks-cluster.yaml`](https://github.com/shumaiOne/shumai/blob/main/eks/eks-cluster.yaml): Complete `eksctl` ClusterConfig with compute tiering.
|
||||
- [`eks/kustomization.yaml`](https://github.com/shumaiOne/shumai/blob/main/eks/kustomization.yaml): Single-command Kustomize deployment for all services.
|
||||
- Detailed instructions for setting up public endpoints, automated Cluster Autoscaler, and zero-downtime graceful shutdown.
|
||||
@@ -64,14 +64,15 @@ For example, if you deploy Shumai on a remote server at `http://123.456.7.8` and
|
||||
|
||||
## Workflow Config
|
||||
|
||||
Configures whether background transcoding and AI agents are executed locally or offloaded to a Temporal cluster.
|
||||
Configures background worker execution, concurrency limits, and worker identity for DBOS Transact queues.
|
||||
|
||||
| Variable | Description | Example / Default |
|
||||
| :---------------------- | :------------------------------------------------------------------------------------------------- | :------------------------------ |
|
||||
| `WORKFLOW_EXECUTOR` | Engine choice. Use `local` for in-process database polling, or `temporal` for distributed workers. | `local` (default) or `temporal` |
|
||||
| `TEMPORAL_ADDRESS` | Host and port of the Temporal cluster gRPC service. | `localhost:7233` (default) |
|
||||
| `CONCURRENCY_AGENT` | Maximum concurrent AI tasks executed by workers. Set to `1` when running local `embedding-server`. | `5` (default) |
|
||||
| `CONCURRENCY_TRANSCODE` | Maximum concurrent media transcoding tasks executed by workers. | `1` (default) |
|
||||
| Variable | Description | Example / Default |
|
||||
| :---------------------- | :-------------------------------------------------------------------------------------------------------------------------------- | :---------------- |
|
||||
| `SHUMAI_WORKERS` | Queues listened to by the web server. Options: `all` (default), `none` (API/UI only), `agent` (or `ai`), `transcode`. | `all` (default) |
|
||||
| `CONCURRENCY_TRANSCODE` | Maximum concurrent media transcoding tasks executed by workers. | `1` (default) |
|
||||
| `CONCURRENCY_AGENT` | Maximum concurrent AI tasks executed by workers. Set to `1` when running local `embedding-server`. | `5` (default) |
|
||||
| `SHUMAI_WORKER_ID` | Optional explicit instance ID for worker replicas in multi-node deployments (auto-derived from hostname and process ID if unset). | `worker-1` |
|
||||
| `POD_NAME` | Kubernetes pod name, used to provide stable per-pod worker identity across StatefulSet restarts. | `transcode-pod-0` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
---
|
||||
title: Deploy with Temporal
|
||||
description: Configure a high-scale production deployment using Temporal and S3-compatible storage.
|
||||
---
|
||||
|
||||
For production environments or workloads with high-volume video processing and heavy AI agent usage, running background tasks on a single server can cause bottlenecks. Shumai resolves this by offloading task queue management, retries, and background executions to **Temporal**.
|
||||
|
||||
This allows you to decouple workloads and run specialized worker nodes on separate, dedicated machines.
|
||||
|
||||
---
|
||||
|
||||
## How it Works
|
||||
|
||||
When configured for Temporal, the core Shumai web application does not process background jobs itself. Instead, it publishes tasks to a Temporal Cluster queue.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
UserUpload[User Uploads Video] --> WebApp[Shumai Web UI / API]
|
||||
WebApp -->|Register Task| Temporal[Temporal Cluster]
|
||||
Temporal -->|Queue: Transcoding| TranscodeWorker[Transcode Worker Machine]
|
||||
Temporal -->|Queue: AI Agents| AgentWorker[Agent Worker Machine]
|
||||
```
|
||||
|
||||
- **Transcoding Workers**: Can be run on GPU-accelerated or high-CPU compute instances.
|
||||
- **AI Agent Workers**: Can be run on isolated, sandboxed hosts to safely execute automation scripts.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Storage Requirement**: Because the core application and the background workers run on separate machines in a distributed setup, **you must configure an S3-compatible storage backend** (such as AWS S3, Cloudflare R2, or MinIO). Local storage (`STORAGE_BACKEND=local`) is not supported in this mode because the workers and the web application do not share a common filesystem.
|
||||
|
||||
---
|
||||
|
||||
## Step 1: Deploy the Core Stack
|
||||
|
||||
On your primary host machine, spin up the database, Temporal cluster services, and the main Shumai web application:
|
||||
|
||||
1. **Download the Temporal Stack Configuration**:
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/temporal/docker-compose.yaml
|
||||
```
|
||||
2. **Configure S3 Settings**:
|
||||
Open the `docker-compose.yaml` file and set your S3 credentials and endpoint environment variables under the `shumai` service.
|
||||
3. **Start the Services**:
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
This exposes the web application on port `3000`, the database on `5432`, the Temporal gRPC service on `7233`, and the Temporal management dashboard on `8080`.
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Configure & Run Workers
|
||||
|
||||
On your specialized worker machines, you will run the dedicated background worker services. Each worker requires a `.env` file referencing the database, S3 storage, and the Temporal cluster:
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@<primary-host-ip>:5432/shumai_db?schema=public
|
||||
WORKFLOW_EXECUTOR=temporal
|
||||
TEMPORAL_ADDRESS=<primary-host-ip>:7233
|
||||
STORAGE_BACKEND=s3
|
||||
AWS_ENDPOINT_URL_S3=https://your-s3-endpoint.com
|
||||
S3_BUCKET=shumai
|
||||
S3_REGION=us-east-1
|
||||
S3_ACCESS_KEY_ID=your-access-key-id
|
||||
S3_SECRET_ACCESS_KEY=your-secret-access-key
|
||||
```
|
||||
|
||||
### Media Transcoding Worker
|
||||
|
||||
Run this on your media processing nodes (requires system installations of `ffmpeg` and `ffprobe`):
|
||||
|
||||
```bash
|
||||
npm install -g @shumai-one/shumai-transcode
|
||||
shumai-transcode
|
||||
```
|
||||
|
||||
### AI Agent Worker
|
||||
|
||||
Run this on your sandboxed agent execution nodes (requires sandbox dependencies like `bubblewrap` or `sandbox-exec`):
|
||||
|
||||
```bash
|
||||
npm install -g @shumai-one/shumai-agent
|
||||
shumai-agent
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **For Bun Users:** Since the worker package binaries contain a `#!/usr/bin/env node` shebang, running `shumai-transcode` or `shumai-agent` directly will run under Node.js. If you wish to run them using Bun, prefix the commands with `bun run --bun` (e.g., `bun run --bun shumai-transcode` or `bun run --bun shumai-agent`).
|
||||
+2
-2
@@ -76,8 +76,8 @@
|
||||
"pages": ["configuration/env-variables", "configuration/hardware-transcoding"]
|
||||
},
|
||||
{
|
||||
"group": "Temporal Deployment",
|
||||
"pages": ["configuration/temporal"]
|
||||
"group": "Distributed Deployment",
|
||||
"pages": ["configuration/distributed"]
|
||||
},
|
||||
{
|
||||
"group": "Releases",
|
||||
|
||||
@@ -32,6 +32,6 @@ Ideal for small teams, local development, or low-volume workflows. In this setup
|
||||
|
||||
### 2. High-Scale Distributed Deployment
|
||||
|
||||
Recommended for production environments with high-volume video uploads. In this setup, background tasks are managed via a centralized queue (Temporal). This allows you to offload heavy workloads to specialized worker machines (for example, putting video transcoding tasks on high-CPU/GPU machines and AI agents on separate sandboxed environments).
|
||||
Recommended for production environments with high-volume video uploads. In this setup, background tasks are managed via durable queues (orchestrated by DBOS directly in PostgreSQL). This allows you to offload heavy workloads to specialized worker machines (for example, putting video transcoding tasks on high-CPU/GPU machines and AI agents on separate sandboxed environments).
|
||||
|
||||
_Note: S3-compatible cloud storage is required for distributed deployments so that all workers can access the uploaded files._
|
||||
|
||||
@@ -27,9 +27,9 @@ Docker Compose automatically configures and spins up all required services (the
|
||||
3. **Access the Dashboard**:
|
||||
Open your browser and navigate to **`http://localhost:3000`** to access the Shumai Web UI.
|
||||
|
||||
### Production Deployments (Temporal)
|
||||
### Production Deployments (Distributed Workers)
|
||||
|
||||
If you are deploying Shumai for a production team with high-volume video uploads, we recommend setting up a distributed deployment using **Temporal** and an S3-compatible storage backend. This offloads resource-heavy video transcoding and AI agents to separate, dedicated worker nodes to keep your main dashboard fast and responsive. For setup instructions, see the [Deploy with Temporal](/configuration/temporal) guide.
|
||||
If you are deploying Shumai for a production team with high-volume video uploads, we recommend setting up a distributed deployment using dedicated workers and an S3-compatible storage backend. This offloads resource-heavy video transcoding and AI agents to separate, dedicated worker nodes to keep your main dashboard fast and responsive. For setup instructions, see the [Deploy with Distributed Workers](/configuration/distributed) guide.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -77,6 +77,6 @@ The **FFmpeg Threads** slider controls the maximum number of CPU threads used by
|
||||
|
||||
## Processing Architecture
|
||||
|
||||
Transcoding is resource-intensive. Depending on your scaling needs, your administrator can run the transcode engine on the main server (Single-Server mode) or delegate tasks to specialized transcoding worker machines (Temporal Worker mode).
|
||||
Transcoding is resource-intensive. Depending on your scaling needs, your administrator can run the transcode engine on the main server (Single-Server mode) or delegate tasks to specialized transcoding worker machines (Dedicated Worker mode).
|
||||
|
||||
In all modes, the processing machine must have system media utilities (`ffmpeg` and `ffprobe`) installed. See the [Temporal Deployment Guide](/configuration/temporal) for setting up distributed transcoding workers.
|
||||
In all modes, the processing machine must have system media utilities (`ffmpeg` and `ffprobe`) installed. See the [Distributed Deployment Guide](/configuration/distributed) for setting up dedicated transcoding workers.
|
||||
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
# Shumai on AWS EKS with KEDA & Scale-to-Zero On-Demand Workers
|
||||
|
||||
This directory contains a complete, production-ready Kubernetes deployment example for running Shumai on **Amazon Elastic Kubernetes Service (Amazon EKS)**, using **KEDA (Kubernetes Event-driven Autoscaling)** and **Scale-to-Zero On-Demand AWS Graviton5 instances** for compute-intensive media processing.
|
||||
|
||||
The example should also be straightforward to adapt to any standard Kubernetes cluster.
|
||||
|
||||
To demonstrate a fully self-hosted setup, it uses Garage as an S3-compatible object storage solution. However, if you're deploying on AWS, consider using **Amazon S3** instead of running your own S3-compatible storage server, as it is managed and highly scalable.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```text
|
||||
[ User / Internet ]
|
||||
│
|
||||
┌────────────────────┴────────────────────┐
|
||||
│ (Port 80/3000) │ (Port 3900)
|
||||
▼ ▼
|
||||
┌───────────────────────┐ ┌───────────────────────┐
|
||||
│ shumai-server (ELB) │ │ garage-public (ELB) │
|
||||
└───────────┬───────────┘ └───────────┬───────────┘
|
||||
│ │ Direct Browser Uploads
|
||||
│ ▼ (Presigned URLs)
|
||||
┌───────────────────┼─────────────────────────────────────────────────────────────────┐
|
||||
│ General Workload Node (c9g.large On-Demand, ~$0.087/hr) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌───────────────────────┐ Enqueue DBOS Tasks ┌───────────────────┐ │
|
||||
│ │ shumai-server ├────────────────────────►│ shumai-postgres │ │
|
||||
│ │(SHUMAI_WORKERS=agent) │ (transcode_queue) │ (pgvector:pg18) │ │
|
||||
│ │ [Stale Recovery Loop] │ │ │ │
|
||||
│ └───────────┬───────────┘ └─────────┬─────────┘ │
|
||||
│ │ Internal S3 Traffic │ │
|
||||
│ ▼ │ │
|
||||
│ ┌───────────────────────┐ │ │
|
||||
│ │ garage-s3 │ │ │
|
||||
│ │ (dxflrs/garage) │ │ │
|
||||
│ └───────────▲───────────┘ │ │
|
||||
└───────────────────┼───────────────────────────────────────────────┼─────────────────┘
|
||||
│ Read Source / Write Proxies │
|
||||
│ │ KEDA monitors
|
||||
│ ▼ dbos.workflow_status
|
||||
│ ┌───────────────────────────────────────┐
|
||||
│ │ KEDA Controller: ScaledJob │
|
||||
│ │ Spawns Jobs based on pending tasks │
|
||||
│ └───────────────────┬───────────────────┘
|
||||
│ │
|
||||
│ ▼ Creates K8s Jobs
|
||||
┌───────────────────┴─────────────────────────────────────────────────────────────────┐
|
||||
│ Transcode Compute Pool (c9g.xlarge Graviton5 On-Demand, minSize: 0, maxSize: 5) │
|
||||
│ │
|
||||
│ ┌──────────────────────────┐ ┌──────────────────────────┐ ┌────────────────────┐ │
|
||||
│ │ Job: transcode-job-1 │ │ Job: transcode-job-2 │ │Job: transcode-job-N│ │
|
||||
│ │ (Auto-Drain Worker) │ │ (Auto-Drain Worker) │ │ (Auto-Drain Worker)│ │
|
||||
│ └────────────┬─────────────┘ └────────────┬─────────────┘ └──────────┬─────────┘ │
|
||||
│ ▼ ▼ ▼ │
|
||||
│ ┌──────────────────────────┐ ┌──────────────────────────┐ ┌────────────────────┐ │
|
||||
│ │ Node 1: c9g.xlarge │ │ Node 2: c9g.xlarge │ │ Node N: c9g.xlarge │ │
|
||||
│ │ (On-Demand) │ │ (On-Demand) │ │ (On-Demand) │ │
|
||||
│ └──────────────────────────┘ └──────────────────────────┘ └────────────────────┘ │
|
||||
│ │
|
||||
│ Scale-to-Zero: When queue is empty, 0 Jobs run and 0 EC2 instances are billed! │
|
||||
└─────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core Design Principles
|
||||
|
||||
### 1. Scale-to-Zero On-Demand Instances (`minSize: 0`)
|
||||
|
||||
Media transcoding with FFmpeg is bursty: hours may pass with zero transcoding activity, followed by sudden batches of 4K video uploads.
|
||||
|
||||
- **Zero Idle Cost**: The transcode node group [`eks/eks-cluster.yaml`](./eks-cluster.yaml) is configured with `minSize: 0` and `desiredCapacity: 0`. When no media transcoding tasks are active, **zero transcode EC2 instances exist**, costing **$0/hr**.
|
||||
- **No Spot Interruption Risk**: Transcoding jobs run on AWS Graviton5 **On-Demand** instances (`c9g.xlarge`, ~$0.174/hr). This eliminates the risk of Spot instances being reclaimed mid-encode by AWS, preventing wasted CPU cycles and avoiding unexpected transcoding delays.
|
||||
|
||||
### 2. KEDA `ScaledJob` vs. `Deployment` / `StatefulSet`
|
||||
|
||||
Standard Kubernetes Horizontal Pod Autoscaler (HPA) scales `Deployment` replicas based on metrics like CPU utilization. However, HPAs on Deployments suffer from severe limitations during video processing:
|
||||
1. When a 1-minute video finishes on Pod A while a 30-minute video is still encoding on Pod B, CPU drops and HPA reduces replica count, which can arbitrarily terminate Pod B mid-encode.
|
||||
2. StatefulSets scale down in strict ordinal order (`pod-4`, `pod-3`, etc.), which would terminate `pod-4` even if `pod-4` is the only pod currently transcoding!
|
||||
|
||||
**KEDA `ScaledJob` solves this natively**:
|
||||
- KEDA queries PostgreSQL directly:
|
||||
```sql
|
||||
SELECT COUNT(*) FROM dbos.workflow_status WHERE queue_name = 'transcode_queue' AND status IN ('ENQUEUED', 'PENDING');
|
||||
```
|
||||
- KEDA spawns independent Kubernetes `Job` pods based on enqueued workload.
|
||||
- Each Job runs the transcode worker with an idle timeout (`SHUMAI_WORKER_IDLE_TIMEOUT_MS=10000`).
|
||||
- When the job drains its tasks and becomes idle, the pod exits `0` and Kubernetes marks the Job completed.
|
||||
- Completing or terminating one job **never impacts any other job**!
|
||||
|
||||
### 3. Idle-Timeout Auto-Drain (10s Inactivity Shutdown)
|
||||
|
||||
In [`eks/shumai-transcode.yaml`](./shumai-transcode.yaml), the worker container runs with `SHUMAI_WORKER_IDLE_TIMEOUT_MS: "10000"`:
|
||||
- **Concurrency Isolation**: Transcode concurrency is set to `1` per pod (`CONCURRENCY_TRANSCODE=1`). Each pod has exclusive access to the node's 4 vCPUs for FFmpeg.
|
||||
- **Batch Processing Without Cold Starts**: Unlike single-task execution, a running worker continuously pulls tasks from `transcode_queue`. When a user uploads 100 images or multiple video files, a warm worker processes them back-to-back in seconds without restarting the container or control plane churn.
|
||||
- **Automatic Scale-to-Zero**: When `activeWorkflows === 0` and no new task arrives within 10 consecutive seconds, the worker initiates graceful DBOS shutdown and exits with code `0`.
|
||||
- The completed Job pod terminates, freeing the node so Cluster Autoscaler can terminate the EC2 instance down to zero.
|
||||
|
||||
---
|
||||
|
||||
## Step-by-Step Deployment Guide
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- [AWS CLI](https://aws.amazon.com/cli/) installed and configured (`aws configure`).
|
||||
- [`eksctl`](https://eksctl.io/) installed.
|
||||
- [`kubectl`](https://kubernetes.io/docs/tasks/tools/) installed.
|
||||
- [`helm`](https://helm.sh/) installed.
|
||||
|
||||
### Step 1: Provision the EKS Cluster
|
||||
|
||||
Create the cluster using the declarative [`eks/eks-cluster.yaml`](./eks-cluster.yaml) configuration:
|
||||
|
||||
```bash
|
||||
eksctl create cluster -f eks/eks-cluster.yaml
|
||||
```
|
||||
|
||||
This provisions:
|
||||
- An EKS 1.31 control plane in `us-east-1` across multiple AZs. *(Note: AWS Graviton5 `c9g` instances are available in `us-east-1`. If deploying to a region where `c9g` is not yet offered, substitute `c7g.large` / `c7g.xlarge` or `c8g` in `eks/eks-cluster.yaml`.)*
|
||||
- `shumai-general`: 1x `c9g.large` On-Demand instance (labeled `workload: general`) for API, database, and storage.
|
||||
- `shumai-transcode`: Scale-to-zero `c9g.xlarge` On-Demand instance pool (`minSize: 0`, `maxSize: 5`, `desiredCapacity: 0`, tainted `dedicated=transcode:NoSchedule`).
|
||||
- AWS EBS CSI Driver with IAM OIDC roles.
|
||||
|
||||
### Step 2: Install KEDA
|
||||
|
||||
Install KEDA using Helm:
|
||||
|
||||
```bash
|
||||
helm repo add kedacore https://kedacore.github.io/charts
|
||||
helm repo update
|
||||
helm install keda kedacore/keda --namespace keda --create-namespace
|
||||
```
|
||||
|
||||
Wait for the KEDA operator to reach `Running` state:
|
||||
|
||||
```bash
|
||||
kubectl wait --namespace keda --for=condition=ready pod -l app.kubernetes.io/name=keda-operator --timeout=120s
|
||||
```
|
||||
|
||||
### Step 3: Deploy the Shumai Stack
|
||||
|
||||
Deploy all components with Kustomize:
|
||||
|
||||
```bash
|
||||
kubectl apply -k eks/
|
||||
```
|
||||
|
||||
This applies:
|
||||
- [`eks/storageclass.yaml`](./storageclass.yaml): Configures `gp3` as the default StorageClass using `ebs.csi.aws.com` with `WaitForFirstConsumer` binding and dynamic EBS volume expansion.
|
||||
- PostgreSQL (`pgvector:pg18`) with durable EBS storage.
|
||||
- Garage S3 object store with automatic bucket and CORS initialization (`garage-init` job).
|
||||
- Shumai API & Web server.
|
||||
- KEDA `ScaledJob` for transcode worker auto-scaling.
|
||||
|
||||
Wait for the core database and storage services to initialize:
|
||||
|
||||
```bash
|
||||
# Wait for PostgreSQL and Garage S3 pods to become Ready
|
||||
kubectl wait --namespace shumai --for=condition=ready pod -l app=shumai-postgres --timeout=180s
|
||||
kubectl wait --namespace shumai --for=condition=ready pod -l app=garage --timeout=180s
|
||||
|
||||
# Wait for the bucket initialization job to complete
|
||||
kubectl wait --namespace shumai --for=condition=complete job/garage-init --timeout=180s
|
||||
|
||||
# Verify all pods in the shumai namespace
|
||||
kubectl get pods -n shumai -o wide
|
||||
```
|
||||
|
||||
*(Note: On first startup, `shumai-server` automatically runs database migrations against PostgreSQL; this may take 30–60 seconds before the server reaches `Running (1/1)`.)*
|
||||
|
||||
### Step 4: Configure Public Access & S3 Endpoint
|
||||
|
||||
AWS automatically provisions external Elastic Load Balancers for `shumai-server` and `garage-public`. Because AWS takes 30–60 seconds to allocate external hostnames, wait for the hostnames to become available:
|
||||
|
||||
```bash
|
||||
# Wait for AWS to assign external hostnames to the LoadBalancers
|
||||
echo "Waiting for LoadBalancer external hostnames..."
|
||||
until [ -n "$(kubectl get svc garage-public -n shumai -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')" ]; do
|
||||
sleep 5
|
||||
done
|
||||
|
||||
GARAGE_ELB=$(kubectl get svc garage-public -n shumai -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')
|
||||
SERVER_ELB=$(kubectl get svc shumai-server -n shumai -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')
|
||||
|
||||
echo "Garage S3 Hostname: http://${GARAGE_ELB}:3900"
|
||||
echo "Shumai Web UI: http://${SERVER_ELB}"
|
||||
```
|
||||
|
||||
Inject the public Garage S3 hostname into `shumai-server` so that browsers generate correct presigned upload URLs:
|
||||
|
||||
```bash
|
||||
kubectl set env deployment/shumai-server -n shumai AWS_PUBLIC_ENDPOINT_URL_S3="http://${GARAGE_ELB}:3900"
|
||||
```
|
||||
|
||||
*(Note: In production with custom domains, point your DNS CNAME records to the load balancers and configure `AWS_PUBLIC_ENDPOINT_URL_S3: https://s3.mycompany.com` in [`eks/config.yaml`](./config.yaml).)*
|
||||
|
||||
### Step 5: Deploy Kubernetes Cluster Autoscaler
|
||||
|
||||
Deploy Cluster Autoscaler to dynamically provision `c9g.xlarge` EC2 nodes when KEDA jobs are created:
|
||||
|
||||
```bash
|
||||
curl -s https://raw.githubusercontent.com/kubernetes/autoscaler/master/cluster-autoscaler/cloudprovider/aws/examples/cluster-autoscaler-autodiscover.yaml \
|
||||
| sed 's/<YOUR CLUSTER NAME>/shumai-eks/g' \
|
||||
| kubectl apply -f -
|
||||
|
||||
# Pin autoscaler to the general workload node
|
||||
kubectl patch deployment cluster-autoscaler -n kube-system -p '{"spec":{"template":{"spec":{"nodeSelector":{"workload":"general"}}}}}'
|
||||
```
|
||||
|
||||
### Step 6: Test Scale-to-Zero Queue-Driven Autoscaling
|
||||
|
||||
1. Open `http://${SERVER_ELB}` in your browser and register an account via **Sign Up**. *(The first registered account automatically becomes the instance administrator).*
|
||||
2. Create a project and upload a batch of 5–10 video files simultaneously.
|
||||
3. Observe KEDA detecting pending DBOS tasks and spawning individual Kubernetes Jobs:
|
||||
```bash
|
||||
kubectl get scaledjobs -n shumai
|
||||
kubectl get jobs -n shumai -w
|
||||
kubectl get pods -n shumai -l app=shumai-transcode -o wide
|
||||
kubectl get nodes -L role,workload
|
||||
```
|
||||
4. Watch Cluster Autoscaler dynamically provision dedicated `c9g.xlarge` Graviton5 EC2 instances for the Jobs.
|
||||
5. As each video finishes transcoding, its worker pod exits `0` and completes immediately.
|
||||
6. Once all jobs are done, KEDA holds 0 jobs, and Cluster Autoscaler terminates all transcode EC2 instances, returning the transcode pool to **0 nodes ($0/hr)**!
|
||||
|
||||
### Step 7: Cluster Teardown & Cost Cleanup
|
||||
|
||||
When you are finished testing, delete all resources to prevent ongoing cloud charges:
|
||||
|
||||
```bash
|
||||
# 1. Delete Kubernetes namespace first to release AWS ELB load balancers and EBS volumes
|
||||
# (Important: Wait for this to complete so AWS SecurityGroups can be deleted without dependency conflicts)
|
||||
kubectl delete namespace shumai
|
||||
|
||||
# 2. Uninstall KEDA
|
||||
helm uninstall keda -n keda
|
||||
kubectl delete namespace keda
|
||||
|
||||
# 3. Delete the EKS cluster and CloudFormation stacks
|
||||
eksctl delete cluster -f eks/eks-cluster.yaml --wait
|
||||
|
||||
# 4. Confirm all AWS resources are released
|
||||
aws eks list-clusters --region us-east-1
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: shumai-config
|
||||
namespace: shumai
|
||||
data:
|
||||
# S3 Storage Configuration (Garage S3)
|
||||
STORAGE_BACKEND: 's3'
|
||||
AWS_ENDPOINT_URL_S3: 'http://garage.shumai.svc.cluster.local:3900'
|
||||
S3_BUCKET: 'shumai'
|
||||
S3_REGION: 'garage'
|
||||
S3_FORCE_PATH_STYLE: 'true'
|
||||
|
||||
# Server & Worker Configuration
|
||||
SHUMAI_SERVER_PORT: '3000'
|
||||
CONCURRENCY_TRANSCODE: '1'
|
||||
SHUMAI_WORKER_DRAIN_TIMEOUT_MS: '290000'
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: shumai-secret
|
||||
namespace: shumai
|
||||
type: Opaque
|
||||
stringData:
|
||||
DATABASE_URL: 'postgresql://shumai:shumai_password@shumai-postgres.shumai.svc.cluster.local:5432/shumai_db?schema=public'
|
||||
KEDA_DATABASE_URL: 'postgresql://shumai:shumai_password@shumai-postgres.shumai.svc.cluster.local:5432/shumai_db?sslmode=disable'
|
||||
BETTER_AUTH_SECRET: 'qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw='
|
||||
S3_ACCESS_KEY_ID: 'GKshumaiaccesskeyid001'
|
||||
S3_SECRET_ACCESS_KEY: 'shumaisecretaccesskey00000000000000001'
|
||||
GARAGE_ADMIN_TOKEN: 'admin-secret-token'
|
||||
@@ -0,0 +1,57 @@
|
||||
apiVersion: eksctl.io/v1alpha5
|
||||
kind: ClusterConfig
|
||||
|
||||
metadata:
|
||||
name: shumai-eks
|
||||
region: us-east-1
|
||||
version: '1.31'
|
||||
|
||||
iam:
|
||||
withOIDC: true
|
||||
|
||||
addons:
|
||||
- name: aws-ebs-csi-driver
|
||||
wellKnownPolicies:
|
||||
ebsCSIController: true
|
||||
|
||||
managedNodeGroups:
|
||||
# General system workload: Web UI, REST API, DBOS PostgreSQL, and Garage S3
|
||||
# Runs on On-Demand instances to guarantee database & storage durability without spot interruptions
|
||||
- name: shumai-general
|
||||
instanceType: c9g.large # 2 vCPU, 4 GiB RAM (Graviton5 On-Demand, ~$0.087/hr)
|
||||
spot: false
|
||||
minSize: 1
|
||||
maxSize: 2
|
||||
desiredCapacity: 1
|
||||
amiFamily: AmazonLinux2023
|
||||
volumeSize: 50
|
||||
volumeType: gp3
|
||||
labels:
|
||||
workload: general
|
||||
iam:
|
||||
withAddonPolicies:
|
||||
autoScaler: true
|
||||
ebs: true
|
||||
|
||||
# Transcoding compute pool: High-CPU media processing
|
||||
# Uses On-Demand instances with scale-to-zero (minSize: 0) managed by Cluster Autoscaler / Karpenter
|
||||
- name: shumai-transcode
|
||||
instanceType: c9g.xlarge # 4 vCPU, 8 GiB RAM (Graviton5 On-Demand, ~$0.174/hr)
|
||||
spot: false
|
||||
minSize: 0
|
||||
maxSize: 5
|
||||
desiredCapacity: 0
|
||||
amiFamily: AmazonLinux2023
|
||||
volumeSize: 50
|
||||
volumeType: gp3
|
||||
labels:
|
||||
workload: transcode
|
||||
role: transcode
|
||||
taints:
|
||||
- key: dedicated
|
||||
value: transcode
|
||||
effect: NoSchedule
|
||||
iam:
|
||||
withAddonPolicies:
|
||||
autoScaler: true
|
||||
ebs: true
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: garage-config
|
||||
namespace: shumai
|
||||
data:
|
||||
garage.toml: |
|
||||
metadata_dir = "/var/lib/garage/meta"
|
||||
data_dir = "/var/lib/garage/data"
|
||||
db_engine = "sqlite"
|
||||
replication_factor = 1
|
||||
|
||||
rpc_bind_addr = "0.0.0.0:3901"
|
||||
rpc_secret = "c7d7e35b7501a91e5cfb3874026315579930f367fa3b7e4a1e94cf67484a86cf"
|
||||
|
||||
[s3_api]
|
||||
s3_region = "garage"
|
||||
api_bind_addr = "0.0.0.0:3900"
|
||||
root_domain = ".s3.garage"
|
||||
|
||||
[admin]
|
||||
api_bind_addr = "0.0.0.0:3903"
|
||||
admin_token = "admin-secret-token"
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: garage
|
||||
namespace: shumai
|
||||
labels:
|
||||
app: garage
|
||||
spec:
|
||||
ports:
|
||||
- port: 3900
|
||||
name: s3-api
|
||||
- port: 3901
|
||||
name: rpc
|
||||
- port: 3903
|
||||
name: admin
|
||||
selector:
|
||||
app: garage
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: garage-public
|
||||
namespace: shumai
|
||||
labels:
|
||||
app: garage
|
||||
spec:
|
||||
type: LoadBalancer
|
||||
ports:
|
||||
- port: 3900
|
||||
targetPort: 3900
|
||||
name: s3-api
|
||||
selector:
|
||||
app: garage
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: garage
|
||||
namespace: shumai
|
||||
spec:
|
||||
serviceName: garage
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: garage
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: garage
|
||||
spec:
|
||||
affinity:
|
||||
nodeAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
nodeSelectorTerms:
|
||||
- matchExpressions:
|
||||
- key: eks.amazonaws.com/nodegroup
|
||||
operator: In
|
||||
values:
|
||||
- shumai-general
|
||||
- shumai-general-spot
|
||||
- matchExpressions:
|
||||
- key: workload
|
||||
operator: In
|
||||
values:
|
||||
- general
|
||||
containers:
|
||||
- name: garage
|
||||
image: dxflrs/garage:v2.4.1
|
||||
imagePullPolicy: IfNotPresent
|
||||
command: ['/garage', 'server']
|
||||
ports:
|
||||
- containerPort: 3900
|
||||
name: s3-api
|
||||
- containerPort: 3901
|
||||
name: rpc
|
||||
- containerPort: 3903
|
||||
name: admin
|
||||
volumeMounts:
|
||||
- name: config
|
||||
mountPath: /etc/garage.toml
|
||||
subPath: garage.toml
|
||||
- name: garage-meta
|
||||
mountPath: /var/lib/garage/meta
|
||||
- name: garage-data
|
||||
mountPath: /var/lib/garage/data
|
||||
volumes:
|
||||
- name: config
|
||||
configMap:
|
||||
name: garage-config
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: garage-meta
|
||||
spec:
|
||||
accessModes: ['ReadWriteOnce']
|
||||
resources:
|
||||
requests:
|
||||
storage: 1Gi
|
||||
- metadata:
|
||||
name: garage-data
|
||||
spec:
|
||||
accessModes: ['ReadWriteOnce']
|
||||
resources:
|
||||
requests:
|
||||
storage: 10Gi
|
||||
---
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: garage-init
|
||||
namespace: shumai
|
||||
spec:
|
||||
backoffLimit: 10
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: garage-init
|
||||
spec:
|
||||
restartPolicy: OnFailure
|
||||
containers:
|
||||
- name: init
|
||||
image: alpine:3.20
|
||||
env:
|
||||
- name: S3_BUCKET
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: shumai-config
|
||||
key: S3_BUCKET
|
||||
- name: S3_ACCESS_KEY_ID
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: shumai-secret
|
||||
key: S3_ACCESS_KEY_ID
|
||||
- name: S3_SECRET_ACCESS_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: shumai-secret
|
||||
key: S3_SECRET_ACCESS_KEY
|
||||
- name: GARAGE_ADMIN_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: shumai-secret
|
||||
key: GARAGE_ADMIN_TOKEN
|
||||
command:
|
||||
- /bin/sh
|
||||
- -c
|
||||
- |
|
||||
set -e
|
||||
apk add --no-cache curl jq aws-cli >/dev/null 2>&1
|
||||
|
||||
echo "Waiting for Garage Admin API to respond..."
|
||||
until curl -s -f -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" http://garage:3903/v2/GetClusterStatus >/dev/null 2>&1; do
|
||||
sleep 2
|
||||
done
|
||||
|
||||
echo "Garage Admin API is online. Retrieving cluster status..."
|
||||
STATUS=$(curl -s -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" http://garage:3903/v2/GetClusterStatus)
|
||||
NODE_ID=$(echo "$STATUS" | jq -r '.nodes[0].id // empty')
|
||||
if [ -z "$NODE_ID" ]; then
|
||||
echo "Error: Node ID not found"
|
||||
exit 1
|
||||
fi
|
||||
echo "Discovered Node ID: $NODE_ID"
|
||||
|
||||
ROLE=$(echo "$STATUS" | jq -r '.nodes[0].role // empty')
|
||||
if [ -z "$ROLE" ] || [ "$ROLE" = "null" ]; then
|
||||
echo "Assigning layout role to node..."
|
||||
curl -s -f -X POST http://garage:3903/v2/UpdateClusterLayout \
|
||||
-H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"roles\": [{\"id\": \"$NODE_ID\", \"zone\": \"dc1\", \"capacity\": 10737418240, \"tags\": []}]}" >/dev/null
|
||||
|
||||
echo "Applying cluster layout (version 1)..."
|
||||
curl -s -f -X POST http://garage:3903/v2/ApplyClusterLayout \
|
||||
-H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"version": 1}' >/dev/null || true
|
||||
fi
|
||||
|
||||
echo "Importing S3 Access Key..."
|
||||
curl -s -f -X POST http://garage:3903/v2/ImportKey \
|
||||
-H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"name\": \"shumai-key\", \"accessKeyId\": \"${S3_ACCESS_KEY_ID}\", \"secretAccessKey\": \"${S3_SECRET_ACCESS_KEY}\"}" >/dev/null || true
|
||||
|
||||
echo "Creating S3 bucket '${S3_BUCKET}'..."
|
||||
BUCKET_RESP=$(curl -s -X POST http://garage:3903/v2/CreateBucket \
|
||||
-H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"globalAlias\": \"${S3_BUCKET}\"}")
|
||||
echo "$BUCKET_RESP"
|
||||
|
||||
BUCKET_ID=$(echo "$BUCKET_RESP" | jq -r '.id // empty')
|
||||
if [ -z "$BUCKET_ID" ]; then
|
||||
# Fetch existing bucket ID if already created
|
||||
BUCKET_ID=$(curl -s -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" "http://garage:3903/v2/GetBucketInfo?globalAlias=${S3_BUCKET}" | jq -r '.id // empty')
|
||||
fi
|
||||
|
||||
if [ -n "$BUCKET_ID" ]; then
|
||||
echo "Granting bucket permissions for key on bucket ID $BUCKET_ID..."
|
||||
curl -s -f -X POST http://garage:3903/v2/AllowBucketKey \
|
||||
-H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"bucketId\": \"${BUCKET_ID}\", \"accessKeyId\": \"${S3_ACCESS_KEY_ID}\", \"permissions\": {\"read\": true, \"write\": true, \"owner\": true}}" >/dev/null || true
|
||||
fi
|
||||
|
||||
echo "Configuring S3 bucket CORS for web uploads..."
|
||||
AWS_ACCESS_KEY_ID=${S3_ACCESS_KEY_ID} \
|
||||
AWS_SECRET_ACCESS_KEY=${S3_SECRET_ACCESS_KEY} \
|
||||
AWS_DEFAULT_REGION=garage \
|
||||
aws --endpoint-url http://garage:3900 s3api put-bucket-cors \
|
||||
--bucket "${S3_BUCKET}" \
|
||||
--cors-configuration '{"CORSRules":[{"AllowedHeaders":["*"],"AllowedMethods":["GET","PUT","POST","DELETE","HEAD"],"AllowedOrigins":["*"],"ExposeHeaders":["ETag"],"MaxAgeSeconds":3000}]}' || true
|
||||
|
||||
echo "✅ Garage S3 storage cluster initialized successfully!"
|
||||
@@ -0,0 +1,11 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
|
||||
resources:
|
||||
- namespace.yaml
|
||||
- storageclass.yaml
|
||||
- config.yaml
|
||||
- postgres.yaml
|
||||
- garage.yaml
|
||||
- shumai-server.yaml
|
||||
- shumai-transcode.yaml
|
||||
@@ -0,0 +1,4 @@
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: shumai
|
||||
@@ -0,0 +1,79 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: shumai-postgres
|
||||
namespace: shumai
|
||||
labels:
|
||||
app: shumai-postgres
|
||||
spec:
|
||||
ports:
|
||||
- port: 5432
|
||||
name: postgres
|
||||
selector:
|
||||
app: shumai-postgres
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: shumai-postgres
|
||||
namespace: shumai
|
||||
spec:
|
||||
serviceName: shumai-postgres
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: shumai-postgres
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: shumai-postgres
|
||||
spec:
|
||||
affinity:
|
||||
nodeAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
nodeSelectorTerms:
|
||||
- matchExpressions:
|
||||
- key: eks.amazonaws.com/nodegroup
|
||||
operator: In
|
||||
values:
|
||||
- shumai-general
|
||||
- shumai-general-spot
|
||||
- matchExpressions:
|
||||
- key: workload
|
||||
operator: In
|
||||
values:
|
||||
- general
|
||||
containers:
|
||||
- name: postgres
|
||||
image: pgvector/pgvector:pg18
|
||||
ports:
|
||||
- containerPort: 5432
|
||||
name: postgres
|
||||
env:
|
||||
- name: POSTGRES_USER
|
||||
value: 'shumai'
|
||||
- name: POSTGRES_PASSWORD
|
||||
value: 'shumai_password'
|
||||
- name: POSTGRES_DB
|
||||
value: 'shumai_db'
|
||||
- name: PGDATA
|
||||
value: '/var/lib/postgresql/18/docker/pgdata'
|
||||
readinessProbe:
|
||||
exec:
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- pg_isready -U shumai -d shumai_db
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- name: postgres-data
|
||||
mountPath: /var/lib/postgresql/18/docker
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: postgres-data
|
||||
spec:
|
||||
accessModes: ['ReadWriteOnce']
|
||||
resources:
|
||||
requests:
|
||||
storage: 5Gi
|
||||
@@ -0,0 +1,85 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: shumai-server
|
||||
namespace: shumai
|
||||
labels:
|
||||
app: shumai-server
|
||||
spec:
|
||||
type: LoadBalancer
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 3000
|
||||
name: http
|
||||
- port: 3000
|
||||
targetPort: 3000
|
||||
name: http-alt
|
||||
selector:
|
||||
app: shumai-server
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: shumai-server
|
||||
namespace: shumai
|
||||
labels:
|
||||
app: shumai-server
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: shumai-server
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: shumai-server
|
||||
spec:
|
||||
affinity:
|
||||
nodeAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
nodeSelectorTerms:
|
||||
- matchExpressions:
|
||||
- key: eks.amazonaws.com/nodegroup
|
||||
operator: In
|
||||
values:
|
||||
- shumai-general
|
||||
- shumai-general-spot
|
||||
- matchExpressions:
|
||||
- key: workload
|
||||
operator: In
|
||||
values:
|
||||
- general
|
||||
containers:
|
||||
- name: server
|
||||
image: shumaione/shumai:latest
|
||||
imagePullPolicy: Always
|
||||
env:
|
||||
- name: SHUMAI_WORKERS
|
||||
value: 'agent'
|
||||
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: shumai-config
|
||||
- secretRef:
|
||||
name: shumai-secret
|
||||
ports:
|
||||
- containerPort: 3000
|
||||
name: http
|
||||
resources:
|
||||
requests:
|
||||
cpu: 250m
|
||||
memory: 512Mi
|
||||
limits:
|
||||
cpu: 2000m
|
||||
memory: 2Gi
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /
|
||||
port: 3000
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 5
|
||||
livenessProbe:
|
||||
tcpSocket:
|
||||
port: 3000
|
||||
initialDelaySeconds: 15
|
||||
periodSeconds: 10
|
||||
@@ -0,0 +1,90 @@
|
||||
apiVersion: keda.sh/v1alpha1
|
||||
kind: TriggerAuthentication
|
||||
metadata:
|
||||
name: keda-postgres-auth
|
||||
namespace: shumai
|
||||
spec:
|
||||
secretTargetRef:
|
||||
- parameter: connection
|
||||
name: shumai-secret
|
||||
key: KEDA_DATABASE_URL
|
||||
---
|
||||
apiVersion: keda.sh/v1alpha1
|
||||
kind: ScaledJob
|
||||
metadata:
|
||||
name: shumai-transcode-scaler
|
||||
namespace: shumai
|
||||
labels:
|
||||
app: shumai-transcode
|
||||
spec:
|
||||
jobTargetRef:
|
||||
parallelism: 1
|
||||
completions: 1
|
||||
backoffLimit: 0
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: shumai-transcode
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
terminationGracePeriodSeconds: 300
|
||||
tolerations:
|
||||
- key: dedicated
|
||||
operator: Equal
|
||||
value: transcode
|
||||
effect: NoSchedule
|
||||
affinity:
|
||||
nodeAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
nodeSelectorTerms:
|
||||
- matchExpressions:
|
||||
- key: role
|
||||
operator: In
|
||||
values:
|
||||
- transcode
|
||||
- matchExpressions:
|
||||
- key: workload
|
||||
operator: In
|
||||
values:
|
||||
- transcode
|
||||
- matchExpressions:
|
||||
- key: eks.amazonaws.com/nodegroup
|
||||
operator: In
|
||||
values:
|
||||
- shumai-transcode
|
||||
containers:
|
||||
- name: worker
|
||||
image: shumaione/shumai-transcode:latest
|
||||
imagePullPolicy: Always
|
||||
env:
|
||||
- name: POD_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: SHUMAI_WORKER_IDLE_TIMEOUT_MS
|
||||
value: '10000'
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: shumai-config
|
||||
- secretRef:
|
||||
name: shumai-secret
|
||||
resources:
|
||||
requests:
|
||||
cpu: 3000m
|
||||
memory: 4Gi
|
||||
limits:
|
||||
cpu: 3900m
|
||||
memory: 6Gi
|
||||
pollingInterval: 10
|
||||
successfulJobsHistoryLimit: 5
|
||||
failedJobsHistoryLimit: 10
|
||||
maxReplicaCount: 5
|
||||
scalingStrategy:
|
||||
strategy: default
|
||||
triggers:
|
||||
- type: postgresql
|
||||
metadata:
|
||||
query: "SELECT COUNT(*) FROM dbos.workflow_status WHERE queue_name = 'transcode_queue' AND status IN ('ENQUEUED', 'PENDING');"
|
||||
targetQueryValue: '1'
|
||||
authenticationRef:
|
||||
name: keda-postgres-auth
|
||||
@@ -0,0 +1,12 @@
|
||||
apiVersion: storage.k8s.io/v1
|
||||
kind: StorageClass
|
||||
metadata:
|
||||
name: gp3
|
||||
annotations:
|
||||
storageclass.kubernetes.io/is-default-class: 'true'
|
||||
provisioner: ebs.csi.aws.com
|
||||
volumeBindingMode: WaitForFirstConsumer
|
||||
allowVolumeExpansion: true
|
||||
parameters:
|
||||
type: gp3
|
||||
fsType: ext4
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shumai",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+465
-276
@@ -2,11 +2,17 @@ import { GoogleGenAI } from '@google/genai'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { ulid } from 'ulid'
|
||||
import { ApplicationFailure, defineStep } from '@shumai/workflow-core'
|
||||
import { prisma } from '@shumai/db'
|
||||
import sharp from 'sharp'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
export interface Usage {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
@@ -112,42 +118,44 @@ export interface GenerateTextEmbeddingParams {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export async function generateTextEmbeddingActivity(params: GenerateTextEmbeddingParams): Promise<{
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
if (provider !== 'gemma-embedding-2-openai' && !process.env.GEMINI_API_KEY) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await textEmbeddingService.generateEmbedding(params.text, {
|
||||
teamId: params.teamId,
|
||||
skipCache: true,
|
||||
})
|
||||
|
||||
return {
|
||||
embedding: result.embedding,
|
||||
usage: {
|
||||
model: result.usage?.model || provider,
|
||||
inputTokens: result.usage?.inputTokens ?? 0,
|
||||
outputTokens: result.usage?.outputTokens ?? 0,
|
||||
},
|
||||
export const generateTextEmbeddingActivity = defineStep(
|
||||
async function generateTextEmbeddingActivity(params: GenerateTextEmbeddingParams): Promise<{
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
if (provider !== 'gemma-embedding-2-openai' && !process.env.GEMINI_API_KEY) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
|
||||
try {
|
||||
const result = await textEmbeddingService.generateEmbedding(params.text, {
|
||||
teamId: params.teamId,
|
||||
skipCache: true,
|
||||
})
|
||||
|
||||
return {
|
||||
embedding: result.embedding,
|
||||
usage: {
|
||||
model: result.usage?.model || provider,
|
||||
inputTokens: result.usage?.inputTokens ?? 0,
|
||||
outputTokens: result.usage?.outputTokens ?? 0,
|
||||
},
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
throw ApplicationFailure.create({
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
throw ApplicationFailure.create({
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export interface ExtractAiMetadataParams {
|
||||
assetKey: string
|
||||
@@ -156,7 +164,7 @@ export interface ExtractAiMetadataParams {
|
||||
isImage: boolean
|
||||
}
|
||||
|
||||
export async function extractAiMetadataActivity(
|
||||
export const extractAiMetadataActivity = defineStep(async function extractAiMetadataActivity(
|
||||
params: ExtractAiMetadataParams,
|
||||
): Promise<string[]> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -207,50 +215,51 @@ export async function extractAiMetadataActivity(
|
||||
}
|
||||
|
||||
return generatedFiles
|
||||
}
|
||||
})
|
||||
|
||||
export async function getEmbeddingContextActivity(params: { teamId: string; assetId: string }) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
|
||||
}
|
||||
|
||||
const agent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId: params.teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding feature is disabled or agent not found',
|
||||
nonRetryable: true,
|
||||
export const getEmbeddingContextActivity = defineStep(
|
||||
async function getEmbeddingContextActivity(params: { teamId: string; assetId: string }) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
}
|
||||
if (!team) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
|
||||
}
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (!asset) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get asset', nonRetryable: true })
|
||||
}
|
||||
if (!asset.mediaType) {
|
||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||
}
|
||||
const agent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId: params.teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding feature is disabled or agent not found',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const parsedDuration = parseFloat(process.env.EMBEDDING_CHUNK_DURATION || '')
|
||||
const chunkDuration =
|
||||
Number.isFinite(parsedDuration) && parsedDuration > 0 ? parsedDuration : 60.0
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (!asset) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get asset', nonRetryable: true })
|
||||
}
|
||||
if (!asset.mediaType) {
|
||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||
}
|
||||
|
||||
const parsedOverlap = parseFloat(process.env.EMBEDDING_CHUNK_OVERLAP || '')
|
||||
const chunkOverlap = Number.isFinite(parsedOverlap) && parsedOverlap >= 0 ? parsedOverlap : 5.0
|
||||
const embeddingProvider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
const parsedDuration = parseFloat(process.env.EMBEDDING_CHUNK_DURATION || '')
|
||||
const chunkDuration =
|
||||
Number.isFinite(parsedDuration) && parsedDuration > 0 ? parsedDuration : 60.0
|
||||
|
||||
const existingEmbeddings = await prisma.$queryRaw<ExistingAssetEmbeddingInfo[]>`
|
||||
const parsedOverlap = parseFloat(process.env.EMBEDDING_CHUNK_OVERLAP || '')
|
||||
const chunkOverlap = Number.isFinite(parsedOverlap) && parsedOverlap >= 0 ? parsedOverlap : 5.0
|
||||
const embeddingProvider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
|
||||
const existingEmbeddings = await prisma.$queryRaw<ExistingAssetEmbeddingInfo[]>`
|
||||
SELECT
|
||||
id,
|
||||
start_time as "startTime",
|
||||
@@ -261,15 +270,16 @@ export async function getEmbeddingContextActivity(params: { teamId: string; asse
|
||||
WHERE asset_id = ${params.assetId}
|
||||
`
|
||||
|
||||
return {
|
||||
agent,
|
||||
asset,
|
||||
chunkDuration,
|
||||
chunkOverlap,
|
||||
embeddingProvider,
|
||||
existingEmbeddings,
|
||||
}
|
||||
}
|
||||
return {
|
||||
agent,
|
||||
asset,
|
||||
chunkDuration,
|
||||
chunkOverlap,
|
||||
embeddingProvider,
|
||||
existingEmbeddings,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export interface ExistingAssetEmbeddingInfo {
|
||||
id: string
|
||||
@@ -279,62 +289,66 @@ export interface ExistingAssetEmbeddingInfo {
|
||||
has768: boolean
|
||||
}
|
||||
|
||||
export async function deleteAssetEmbeddingsActivity(params: { assetId: string; ids?: string[] }) {
|
||||
if (params.ids && params.ids.length > 0) {
|
||||
await prisma.assetEmbedding.deleteMany({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
id: { in: params.ids },
|
||||
},
|
||||
})
|
||||
} else {
|
||||
await prisma.assetEmbedding.deleteMany({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveAssetEmbeddingsActivity(params: {
|
||||
assetId: string
|
||||
embeddings: Array<{
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
}>
|
||||
}) {
|
||||
for (const item of params.embeddings) {
|
||||
const embVec = JSON.stringify(item.embedding)
|
||||
const is768 = item.embedding.length === 768
|
||||
|
||||
if (item.startTime !== undefined && item.endTime !== undefined) {
|
||||
if (is768) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
`
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
`
|
||||
}
|
||||
export const deleteAssetEmbeddingsActivity = defineStep(
|
||||
async function deleteAssetEmbeddingsActivity(params: { assetId: string; ids?: string[] }) {
|
||||
if (params.ids && params.ids.length > 0) {
|
||||
await prisma.assetEmbedding.deleteMany({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
id: { in: params.ids },
|
||||
},
|
||||
})
|
||||
} else {
|
||||
if (is768) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
|
||||
`
|
||||
await prisma.assetEmbedding.deleteMany({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
},
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export const saveAssetEmbeddingsActivity = defineStep(
|
||||
async function saveAssetEmbeddingsActivity(params: {
|
||||
assetId: string
|
||||
embeddings: Array<{
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
}>
|
||||
}) {
|
||||
for (const item of params.embeddings) {
|
||||
const embVec = JSON.stringify(item.embedding)
|
||||
const is768 = item.embedding.length === 768
|
||||
|
||||
if (item.startTime !== undefined && item.endTime !== undefined) {
|
||||
if (is768) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
`
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
`
|
||||
}
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
|
||||
`
|
||||
if (is768) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
|
||||
`
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
|
||||
`
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export interface GenerateImageEmbeddingParams {
|
||||
teamId: string
|
||||
@@ -342,60 +356,60 @@ export interface GenerateImageEmbeddingParams {
|
||||
mediaType: string
|
||||
}
|
||||
|
||||
export async function generateImageEmbeddingActivity(
|
||||
params: GenerateImageEmbeddingParams,
|
||||
): Promise<{
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.assetKey,
|
||||
)
|
||||
export const generateImageEmbeddingActivity = defineStep(
|
||||
async function generateImageEmbeddingActivity(params: GenerateImageEmbeddingParams): Promise<{
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.assetKey,
|
||||
)
|
||||
|
||||
if (provider === 'gemma-embedding-2-openai') {
|
||||
let imgData = data
|
||||
let mimeType = params.mediaType || 'image/jpeg'
|
||||
if (mimeType !== 'image/jpeg' && mimeType !== 'image/png') {
|
||||
imgData = await sharp(data).jpeg().toBuffer()
|
||||
mimeType = 'image/jpeg'
|
||||
}
|
||||
return callGemmaEmbeddingServer([
|
||||
{
|
||||
type: 'image_url',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
image_url: {
|
||||
url: `data:${mimeType};base64,${imgData.toString('base64')}`,
|
||||
if (provider === 'gemma-embedding-2-openai') {
|
||||
let imgData = data
|
||||
let mimeType = params.mediaType || 'image/jpeg'
|
||||
if (mimeType !== 'image/jpeg' && mimeType !== 'image/png') {
|
||||
imgData = await sharp(data).jpeg().toBuffer()
|
||||
mimeType = 'image/jpeg'
|
||||
}
|
||||
return callGemmaEmbeddingServer([
|
||||
{
|
||||
type: 'image_url',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
image_url: {
|
||||
url: `data:${mimeType};base64,${imgData.toString('base64')}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
])
|
||||
}
|
||||
])
|
||||
}
|
||||
|
||||
const apiKey = process.env.GEMINI_API_KEY
|
||||
if (!apiKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const apiKey = process.env.GEMINI_API_KEY
|
||||
if (!apiKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedApiKey = process.env[apiKey] || apiKey
|
||||
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
|
||||
const resolvedApiKey = process.env[apiKey] || apiKey
|
||||
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
|
||||
|
||||
const usage: Usage = {
|
||||
model: 'gemini-embedding-2',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
const usage: Usage = {
|
||||
model: 'gemini-embedding-2',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
const embVec = await generateMultimodalEmbedding(ai, data, params.mediaType)
|
||||
const embVec = await generateMultimodalEmbedding(ai, data, params.mediaType)
|
||||
|
||||
return {
|
||||
embedding: embVec,
|
||||
usage,
|
||||
}
|
||||
}
|
||||
return {
|
||||
embedding: embVec,
|
||||
usage,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Standard aspect ratios for video embedding:
|
||||
@@ -434,121 +448,296 @@ export interface GenerateVideoChunkEmbeddingParams {
|
||||
chunkKey: string
|
||||
}
|
||||
|
||||
export async function generateVideoChunkEmbeddingActivity(
|
||||
params: GenerateVideoChunkEmbeddingParams,
|
||||
): Promise<{
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
const isGemma = provider === 'gemma-embedding-2-openai' || params.chunkKey.endsWith('.tar')
|
||||
export const generateVideoChunkEmbeddingActivity = defineStep(
|
||||
async function generateVideoChunkEmbeddingActivity(
|
||||
params: GenerateVideoChunkEmbeddingParams,
|
||||
): Promise<{
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
const isGemma = provider === 'gemma-embedding-2-openai' || params.chunkKey.endsWith('.tar')
|
||||
|
||||
if (isGemma) {
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.chunkKey,
|
||||
)
|
||||
if (isGemma) {
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.chunkKey,
|
||||
)
|
||||
|
||||
let filesMap: Map<string, File>
|
||||
try {
|
||||
const archive = new Bun.Archive(data)
|
||||
filesMap = await archive.files()
|
||||
} catch (err) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to read chunk archive ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const frameFiles = Array.from(filesMap.keys())
|
||||
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
|
||||
.sort()
|
||||
|
||||
if (frameFiles.length === 0) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `No extracted frames found in chunk archive ${params.chunkKey}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
let targetFrameCount = 14
|
||||
try {
|
||||
const firstFile = filesMap.get(frameFiles[0])
|
||||
if (firstFile) {
|
||||
const firstFileBytes = await firstFile.bytes()
|
||||
if (firstFileBytes.byteLength > 0) {
|
||||
const meta = await sharp(Buffer.from(firstFileBytes)).metadata()
|
||||
targetFrameCount = getGemmaEmbeddingTargetFrameCount(meta.width, meta.height)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
targetFrameCount = 14
|
||||
}
|
||||
|
||||
let selectedFrames = frameFiles
|
||||
if (selectedFrames.length > targetFrameCount) {
|
||||
const step = (selectedFrames.length - 1) / (targetFrameCount - 1)
|
||||
selectedFrames = Array.from(
|
||||
{ length: targetFrameCount },
|
||||
(_, i) => selectedFrames[Math.round(i * step)],
|
||||
)
|
||||
}
|
||||
|
||||
const input: OpenAiEmbeddingItem[] = await Promise.all(
|
||||
selectedFrames.map(async (f) => {
|
||||
const file = filesMap.get(f)!
|
||||
const fileBytes = await file.bytes()
|
||||
if (fileBytes.byteLength === 0) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Extracted frame ${f} in chunk archive ${params.chunkKey} is empty (0 bytes)`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
return {
|
||||
type: 'image_url',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
image_url: {
|
||||
url: `data:image/jpeg;base64,${Buffer.from(fileBytes).toString('base64')}`,
|
||||
},
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return await callGemmaEmbeddingServer(input)
|
||||
}
|
||||
|
||||
const apiKey = process.env.GEMINI_API_KEY
|
||||
if (!apiKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedApiKey = process.env[apiKey] || apiKey
|
||||
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
|
||||
|
||||
const usage: Usage = {
|
||||
model: 'gemini-embedding-2',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
let filesMap: Map<string, File>
|
||||
try {
|
||||
const archive = new Bun.Archive(data)
|
||||
filesMap = await archive.files()
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.chunkKey,
|
||||
)
|
||||
|
||||
const embVec = await generateMultimodalEmbedding(ai, data, 'video/mp4')
|
||||
return {
|
||||
embedding: embVec,
|
||||
usage,
|
||||
}
|
||||
} catch (err) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to read chunk archive ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: true,
|
||||
message: `Failed to generate video chunk embedding for key ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const frameFiles = Array.from(filesMap.keys())
|
||||
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
|
||||
.sort()
|
||||
export interface TranscodeVideoChunkParams {
|
||||
assetId: string
|
||||
assetKey?: string
|
||||
filePath?: string
|
||||
startTime: number
|
||||
endTime: number
|
||||
format?: 'video' | 'frames'
|
||||
}
|
||||
|
||||
if (frameFiles.length === 0) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `No extracted frames found in chunk archive ${params.chunkKey}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
let targetFrameCount = 14
|
||||
try {
|
||||
const firstFile = filesMap.get(frameFiles[0])
|
||||
if (firstFile) {
|
||||
const firstFileBytes = await firstFile.bytes()
|
||||
if (firstFileBytes.byteLength > 0) {
|
||||
const meta = await sharp(Buffer.from(firstFileBytes)).metadata()
|
||||
targetFrameCount = getGemmaEmbeddingTargetFrameCount(meta.width, meta.height)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
targetFrameCount = 14
|
||||
}
|
||||
|
||||
let selectedFrames = frameFiles
|
||||
if (selectedFrames.length > targetFrameCount) {
|
||||
const step = (selectedFrames.length - 1) / (targetFrameCount - 1)
|
||||
selectedFrames = Array.from(
|
||||
{ length: targetFrameCount },
|
||||
(_, i) => selectedFrames[Math.round(i * step)],
|
||||
)
|
||||
}
|
||||
|
||||
const input: OpenAiEmbeddingItem[] = await Promise.all(
|
||||
selectedFrames.map(async (f) => {
|
||||
const file = filesMap.get(f)!
|
||||
const fileBytes = await file.bytes()
|
||||
if (fileBytes.byteLength === 0) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Extracted frame ${f} in chunk archive ${params.chunkKey} is empty (0 bytes)`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
return {
|
||||
type: 'image_url',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
image_url: {
|
||||
url: `data:image/jpeg;base64,${Buffer.from(fileBytes).toString('base64')}`,
|
||||
},
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return await callGemmaEmbeddingServer(input)
|
||||
}
|
||||
|
||||
const apiKey = process.env.GEMINI_API_KEY
|
||||
if (!apiKey) {
|
||||
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
|
||||
params: TranscodeVideoChunkParams,
|
||||
): Promise<{ chunkKey: string }> {
|
||||
if (!params.filePath && !params.assetKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedApiKey = process.env[apiKey] || apiKey
|
||||
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
|
||||
if (params.format === 'frames') {
|
||||
const tmpDir = transcodeService.createTempDir('video-chunk-frames-')
|
||||
try {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const inputSource =
|
||||
params.filePath ||
|
||||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
|
||||
if (!inputSource) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
|
||||
|
||||
const usage: Usage = {
|
||||
model: 'gemini-embedding-2',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
const duration = Math.max(0.1, params.endTime - params.startTime)
|
||||
const fpsFilter = duration > 16 ? `fps=${16 / duration}` : 'fps=1'
|
||||
const vframesArgs = duration > 16 ? ['-vframes', '16'] : []
|
||||
|
||||
await execFileAsync('ffmpeg', [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
...(isRemote
|
||||
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
|
||||
: []),
|
||||
'-ss',
|
||||
params.startTime.toString(),
|
||||
'-i',
|
||||
inputSource,
|
||||
'-map',
|
||||
'0:V:0',
|
||||
'-t',
|
||||
duration.toString(),
|
||||
'-vf',
|
||||
fpsFilter,
|
||||
...vframesArgs,
|
||||
'-q:v',
|
||||
'2',
|
||||
path.join(tmpDir, 'frame_%04d.jpg'),
|
||||
])
|
||||
|
||||
const frameFiles = fs
|
||||
.readdirSync(tmpDir)
|
||||
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
|
||||
.sort()
|
||||
|
||||
const archiveEntries: Record<string, Buffer> = {}
|
||||
for (const file of frameFiles) {
|
||||
archiveEntries[file] = fs.readFileSync(path.join(tmpDir, file))
|
||||
}
|
||||
|
||||
const archive = new Bun.Archive(archiveEntries)
|
||||
const archiveBytes = await archive.bytes()
|
||||
const archiveData = Buffer.from(
|
||||
archiveBytes.buffer,
|
||||
archiveBytes.byteOffset,
|
||||
archiveBytes.byteLength,
|
||||
)
|
||||
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
|
||||
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
|
||||
|
||||
return { chunkKey: key }
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to extract video chunk frames for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
} finally {
|
||||
transcodeService.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}-${ulid()}.mp4`)
|
||||
try {
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.chunkKey,
|
||||
)
|
||||
|
||||
const embVec = await generateMultimodalEmbedding(ai, data, 'video/mp4')
|
||||
return {
|
||||
embedding: embVec,
|
||||
usage,
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const inputSource =
|
||||
params.filePath ||
|
||||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
|
||||
if (!inputSource) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
|
||||
|
||||
// Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization
|
||||
// Note: -ss placed before -i for fast input seeking via demuxer Range requests
|
||||
await execFileAsync('ffmpeg', [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
...(isRemote
|
||||
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
|
||||
: []),
|
||||
'-ss',
|
||||
params.startTime.toString(),
|
||||
'-i',
|
||||
inputSource,
|
||||
'-map',
|
||||
'0:V:0',
|
||||
'-t',
|
||||
(params.endTime - params.startTime).toString(),
|
||||
'-vf',
|
||||
'fps=1',
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'ultrafast',
|
||||
'-crf',
|
||||
'28',
|
||||
'-an',
|
||||
chunkTmp,
|
||||
])
|
||||
|
||||
const chunkData = fs.readFileSync(chunkTmp)
|
||||
|
||||
// Upload to S3
|
||||
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
|
||||
|
||||
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
|
||||
|
||||
return { chunkKey: key }
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate video chunk embedding for key ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
} finally {
|
||||
if (fs.existsSync(chunkTmp)) {
|
||||
try {
|
||||
fs.unlinkSync(chunkTmp)
|
||||
} catch (e) {
|
||||
console.error('Failed to cleanup local chunk file:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const deleteS3ObjectActivity = defineStep(
|
||||
async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
@@ -604,9 +604,7 @@ export function formatSkillsForPrompt(
|
||||
}
|
||||
|
||||
import { WorkflowTaskType } from '@shumai/db'
|
||||
import { registerActivities, registerWorkflow } from '@shumai/workflow-core'
|
||||
import * as agentActivities from './activities/agent'
|
||||
import * as aiActivities from './activities/ai'
|
||||
import { registerWorkflow } from '@shumai/workflow-core'
|
||||
import { agentAutofillMedia } from './workflows/agent-autofill'
|
||||
import { agentChat } from './workflows/agent-chat'
|
||||
import { agentEmbeddingMedia } from './workflows/agent-embedding'
|
||||
@@ -615,9 +613,6 @@ export function initAgentWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia)
|
||||
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia)
|
||||
registerWorkflow(WorkflowTaskType.chat, agentChat)
|
||||
|
||||
registerActivities(agentActivities)
|
||||
registerActivities(aiActivities)
|
||||
}
|
||||
|
||||
export * from './activities/agent'
|
||||
|
||||
@@ -2,14 +2,29 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentAutofillMedia } from './agent-autofill'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import * as workflowCore from '@shumai/workflow-core'
|
||||
import * as agentActivities from '../activities/agent'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateTaskUsageActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/agent', async () => {
|
||||
const actual = await vi.importActual('../activities/agent')
|
||||
return {
|
||||
...actual,
|
||||
getAssetActivity: vi.fn(),
|
||||
getProjectAutofillFieldsActivity: vi.fn(),
|
||||
getAgentAutofillContextActivity: vi.fn(),
|
||||
autofillAiActivity: vi.fn(),
|
||||
updateAssetMetadataActivity: vi.fn(),
|
||||
createCommentActivity: vi.fn(),
|
||||
updateCommentActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -23,26 +38,15 @@ describe('Agent Autofill Workflow', () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getProjectAutofillFieldsActivity',
|
||||
}),
|
||||
getAgentAutofillContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentAutofillContextActivity',
|
||||
}),
|
||||
getAssetAutofillContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAssetAutofillContextActivity',
|
||||
}),
|
||||
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
updateAssetMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMetadataActivity',
|
||||
}),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskStatusActivity: vi.mocked(workflowCore.updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(agentActivities.getAssetActivity),
|
||||
getProjectAutofillFieldsActivity: vi.mocked(agentActivities.getProjectAutofillFieldsActivity),
|
||||
getAgentAutofillContextActivity: vi.mocked(agentActivities.getAgentAutofillContextActivity),
|
||||
autofillAiActivity: vi.mocked(agentActivities.autofillAiActivity),
|
||||
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
|
||||
updateAssetMetadataActivity: vi.mocked(agentActivities.updateAssetMetadataActivity),
|
||||
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
|
||||
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
|
||||
}
|
||||
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
@@ -65,13 +69,6 @@ describe('Agent Autofill Workflow', () => {
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 10, outputTokens: 15, model: 'gemini-model' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent autofill workflow successfully', async () => {
|
||||
|
||||
@@ -1,38 +1,33 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
executeActivity,
|
||||
getActivities,
|
||||
TaskQueueAgent,
|
||||
updateTaskStatusActivity,
|
||||
updateTaskUsageActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import { getProxyType } from '@shumai/core/src/utils/mime'
|
||||
import {
|
||||
autofillAiActivity,
|
||||
createCommentActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
getAssetActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
updateAssetMetadataActivity,
|
||||
updateCommentActivity,
|
||||
} from '../activities/agent'
|
||||
|
||||
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
autofillAiActivity,
|
||||
updateTaskUsageActivity,
|
||||
updateAssetMetadataActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
const agentWorkerQueue = TaskQueueAgent
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// 0. Create Placeholder Comment
|
||||
const payload = task.payload
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
const placeholder = await createCommentActivity({
|
||||
assetId: task.assetId,
|
||||
message: '__AUTOFILL__',
|
||||
sessionId: payload?.agent?.sessionId || task.id,
|
||||
@@ -41,7 +36,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 1. Get Asset
|
||||
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
||||
const asset = await getAssetActivity(task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||
}
|
||||
@@ -49,19 +44,15 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const projectId = asset.project.id
|
||||
|
||||
// 2. Get Project Autofill Fields
|
||||
const fields = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getProjectAutofillFieldsActivity,
|
||||
projectId,
|
||||
)
|
||||
const fields = await getProjectAutofillFieldsActivity(projectId)
|
||||
if (fields.length === 0) {
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed: No autofill fields defined in project.',
|
||||
})
|
||||
}
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -69,7 +60,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 3. Fetch Agent Context
|
||||
const context = await executeActivity(agentWorkerQueue, getAgentAutofillContextActivity, {
|
||||
const context = await getAgentAutofillContextActivity({
|
||||
teamId,
|
||||
})
|
||||
|
||||
@@ -91,7 +82,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
: undefined
|
||||
: undefined
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||
const aiResult = await autofillAiActivity({
|
||||
teamId,
|
||||
assetId: asset.id,
|
||||
assetName: asset.name,
|
||||
@@ -99,19 +90,17 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
duration,
|
||||
pageCount,
|
||||
projectId: asset.projectId ?? undefined,
|
||||
fields: fields.map(
|
||||
(f: { key: string; config: Record<string, unknown>; description?: string | null }) => ({
|
||||
id: f.key,
|
||||
config: f.config as unknown as PrismaJson.FieldConfig,
|
||||
description: f.description,
|
||||
}),
|
||||
),
|
||||
fields: fields.map((f) => ({
|
||||
id: f.key,
|
||||
config: (f.config as unknown as PrismaJson.FieldConfig) ?? {},
|
||||
description: f.description,
|
||||
})),
|
||||
context,
|
||||
})
|
||||
|
||||
if (aiResult.usage) {
|
||||
// Update Usage
|
||||
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||
await updateTaskUsageActivity({
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
@@ -129,7 +118,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}))
|
||||
|
||||
if (metadataUpdates.length > 0) {
|
||||
await executeActivity(agentWorkerQueue, updateAssetMetadataActivity, {
|
||||
await updateAssetMetadataActivity({
|
||||
assetId: asset.id,
|
||||
metadata: metadataUpdates,
|
||||
})
|
||||
@@ -137,7 +126,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed successfully.',
|
||||
sessionId: aiResult.sessionId,
|
||||
@@ -145,7 +134,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -153,9 +142,9 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId && agentWorkerQueue) {
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
})
|
||||
@@ -165,13 +154,11 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
if (agentWorkerQueue) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
}
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,34 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentChat } from './agent-chat'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import * as workflowCore from '@shumai/workflow-core'
|
||||
import * as agentActivities from '../activities/agent'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateTaskUsageActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/agent', async () => {
|
||||
const actual = await vi.importActual('../activities/agent')
|
||||
return {
|
||||
...actual,
|
||||
getCommentActivity: vi.fn(),
|
||||
createCommentActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
initializeAgentSessionActivity: vi.fn(),
|
||||
getAgentChatContextActivity: vi.fn(),
|
||||
agentChatActivity: vi.fn(),
|
||||
updateCommentActivity: vi.fn(),
|
||||
deleteCommentActivity: vi.fn(),
|
||||
getAssetPathHierarchyActivity: vi.fn(),
|
||||
getAssetPathContextActivity: vi.fn(),
|
||||
generateSessionNameActivity: vi.fn(),
|
||||
getUserTeamInfoActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -23,34 +43,20 @@ describe('Agent Chat Workflow', () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
initializeAgentSessionActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'initializeAgentSessionActivity',
|
||||
}),
|
||||
getAgentChatContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentChatContextActivity',
|
||||
}),
|
||||
agentChatActivity: Object.assign(vi.fn(), { _activityName: 'agentChatActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
|
||||
getAssetPathHierarchyActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAssetPathHierarchyActivity',
|
||||
}),
|
||||
getAssetPathContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAssetPathContextActivity',
|
||||
}),
|
||||
generateSessionNameActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateSessionNameActivity',
|
||||
}),
|
||||
getUserTeamInfoActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getUserTeamInfoActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(workflowCore.updateTaskStatusActivity),
|
||||
getCommentActivity: vi.mocked(agentActivities.getCommentActivity),
|
||||
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
|
||||
getAssetActivity: vi.mocked(agentActivities.getAssetActivity),
|
||||
initializeAgentSessionActivity: vi.mocked(agentActivities.initializeAgentSessionActivity),
|
||||
getAgentChatContextActivity: vi.mocked(agentActivities.getAgentChatContextActivity),
|
||||
agentChatActivity: vi.mocked(agentActivities.agentChatActivity),
|
||||
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
|
||||
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
|
||||
deleteCommentActivity: vi.mocked(agentActivities.deleteCommentActivity),
|
||||
getAssetPathHierarchyActivity: vi.mocked(agentActivities.getAssetPathHierarchyActivity),
|
||||
getAssetPathContextActivity: vi.mocked(agentActivities.getAssetPathContextActivity),
|
||||
generateSessionNameActivity: vi.mocked(agentActivities.generateSessionNameActivity),
|
||||
getUserTeamInfoActivity: vi.mocked(agentActivities.getUserTeamInfoActivity),
|
||||
}
|
||||
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
@@ -88,13 +94,6 @@ describe('Agent Chat Workflow', () => {
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 10, outputTokens: 20, model: 'gemini-model' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent chat workflow successfully with default configurations', async () => {
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
executeActivity,
|
||||
getActivities,
|
||||
TaskQueueAgent,
|
||||
updateTaskStatusActivity,
|
||||
updateTaskUsageActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
agentChatActivity,
|
||||
createCommentActivity,
|
||||
generateSessionNameActivity,
|
||||
getAgentChatContextActivity,
|
||||
getAssetActivity,
|
||||
getAssetPathContextActivity,
|
||||
getAssetPathHierarchyActivity,
|
||||
getCommentActivity,
|
||||
getUserTeamInfoActivity,
|
||||
initializeAgentSessionActivity,
|
||||
updateCommentActivity,
|
||||
} from '../activities/agent'
|
||||
import type {
|
||||
ShumaiMessageContext,
|
||||
ShumaiAssetContext,
|
||||
@@ -15,28 +27,11 @@ import { getProxyType } from '@shumai/core/src/utils/mime'
|
||||
import { secondToDegree } from '@shumai/core/src/utils/model3d'
|
||||
|
||||
export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
getAgentChatContextActivity,
|
||||
agentChatActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
updateTaskUsageActivity,
|
||||
initializeAgentSessionActivity,
|
||||
getAssetPathHierarchyActivity,
|
||||
getAssetPathContextActivity,
|
||||
generateSessionNameActivity,
|
||||
getUserTeamInfoActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
const agentWorkerQueue = TaskQueueAgent
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
@@ -65,7 +60,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
let commentAnnotations: unknown[] | undefined
|
||||
|
||||
if (userCommentId) {
|
||||
userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
|
||||
userComment = await getCommentActivity(userCommentId)
|
||||
if (!userComment) {
|
||||
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
||||
}
|
||||
@@ -84,7 +79,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
const placeholder = await createCommentActivity({
|
||||
assetId: task.assetId,
|
||||
message: '__CHAT__',
|
||||
sessionId: sessionId || 'pending',
|
||||
@@ -119,7 +114,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 3. Get Asset
|
||||
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
||||
const asset = await getAssetActivity(task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||
}
|
||||
@@ -134,7 +129,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
sessionId = await executeActivity(agentWorkerQueue, initializeAgentSessionActivity, {
|
||||
sessionId = await initializeAgentSessionActivity({
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
userCommentId,
|
||||
@@ -144,18 +139,14 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 4b. Fetch Agent Context
|
||||
const context = await executeActivity(agentWorkerQueue, getAgentChatContextActivity, {
|
||||
const context = await getAgentChatContextActivity({
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
userId: payload.agent?.userId,
|
||||
projectId: payload.projectId,
|
||||
})
|
||||
|
||||
const pathHierarchy = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathHierarchyActivity,
|
||||
task.assetId,
|
||||
)
|
||||
const pathHierarchy = await getAssetPathHierarchyActivity(task.assetId)
|
||||
const assetPath = pathHierarchy?.path || ''
|
||||
const ancestors = pathHierarchy?.ancestors || []
|
||||
|
||||
@@ -180,11 +171,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
if (userCommentId && userComment?.attachments) {
|
||||
for (const att of userComment.attachments) {
|
||||
if (att.asset) {
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
att.asset.id,
|
||||
)
|
||||
const filePath = await getAssetPathContextActivity(att.asset.id)
|
||||
const attProxyType =
|
||||
(att.asset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(att.asset.mediaType, att.asset.name) ||
|
||||
@@ -203,13 +190,9 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
} else if (payload.agent?.attachedFiles) {
|
||||
for (const fileId of payload.agent.attachedFiles) {
|
||||
const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId)
|
||||
const file = await getAssetActivity(fileId)
|
||||
if (file) {
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
fileId,
|
||||
)
|
||||
const filePath = await getAssetPathContextActivity(fileId)
|
||||
const fileProxyType =
|
||||
(file.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(file.mediaType, file.name) ||
|
||||
@@ -232,13 +215,9 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const referencedAssets: ShumaiAttachedFileContext[] = []
|
||||
if (payload.agent?.assetIds) {
|
||||
for (const assetId of payload.agent.assetIds) {
|
||||
const referencedAsset = await executeActivity(agentWorkerQueue, getAssetActivity, assetId)
|
||||
const referencedAsset = await getAssetActivity(assetId)
|
||||
if (referencedAsset) {
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
assetId,
|
||||
)
|
||||
const filePath = await getAssetPathContextActivity(assetId)
|
||||
const refProxyType =
|
||||
(referencedAsset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(referencedAsset.mediaType, referencedAsset.name) ||
|
||||
@@ -265,7 +244,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const targetUserId = userCommentId ? commentCreatorId : payload.agent?.userId
|
||||
let userInfo: { name: string; role: string } | null = null
|
||||
if (targetUserId) {
|
||||
userInfo = await executeActivity(agentWorkerQueue, getUserTeamInfoActivity, {
|
||||
userInfo = await getUserTeamInfoActivity({
|
||||
userId: targetUserId,
|
||||
teamId,
|
||||
})
|
||||
@@ -325,7 +304,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
folderId = asset.parentId
|
||||
}
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
||||
const aiResult = await agentChatActivity({
|
||||
taskId: task.id,
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
@@ -344,7 +323,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: aiResult.text,
|
||||
sessionId: aiResult.sessionId,
|
||||
@@ -353,7 +332,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 8. Update Usage
|
||||
if (aiResult.usage) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||
await updateTaskUsageActivity({
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
@@ -363,7 +342,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 9. Generate Session Name for new chats
|
||||
if (isNewChat) {
|
||||
await executeActivity(agentWorkerQueue, generateSessionNameActivity, {
|
||||
await generateSessionNameActivity({
|
||||
teamId,
|
||||
agentId,
|
||||
prompt,
|
||||
@@ -375,7 +354,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { sessionId: aiResult.sessionId },
|
||||
@@ -384,7 +363,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
console.error(`AgentChat failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId && agentWorkerQueue) {
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
let errorMessage = 'Sorry, I encountered an error while processing your request.'
|
||||
if (err instanceof Error) {
|
||||
@@ -406,7 +385,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
errorMessage = 'Agent execution stopped.'
|
||||
}
|
||||
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: errorMessage,
|
||||
})
|
||||
@@ -416,13 +395,11 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
if (agentWorkerQueue) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
}
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,39 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentEmbeddingMedia } from './agent-embedding'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import * as workflowCore from '@shumai/workflow-core'
|
||||
import * as agentActivities from '../activities/agent'
|
||||
import * as aiActivities from '../activities/ai'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateTaskUsageActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/agent', async () => {
|
||||
const actual = await vi.importActual('../activities/agent')
|
||||
return {
|
||||
...actual,
|
||||
createCommentActivity: vi.fn(),
|
||||
updateCommentActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/ai', async () => {
|
||||
const actual = await vi.importActual('../activities/ai')
|
||||
return {
|
||||
...actual,
|
||||
getEmbeddingContextActivity: vi.fn(),
|
||||
generateImageEmbeddingActivity: vi.fn(),
|
||||
generateVideoChunkEmbeddingActivity: vi.fn(),
|
||||
saveAssetEmbeddingsActivity: vi.fn(),
|
||||
deleteAssetEmbeddingsActivity: vi.fn(),
|
||||
transcodeVideoChunkActivity: vi.fn(),
|
||||
deleteS3ObjectActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -23,39 +48,21 @@ describe('Agent Embedding Workflow', () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getEmbeddingContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getEmbeddingContextActivity',
|
||||
}),
|
||||
generateImageEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateImageEmbeddingActivity',
|
||||
}),
|
||||
generateVideoChunkEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateVideoChunkEmbeddingActivity',
|
||||
}),
|
||||
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'saveAssetEmbeddingsActivity',
|
||||
}),
|
||||
deleteAssetEmbeddingsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'deleteAssetEmbeddingsActivity',
|
||||
}),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'cleanupTmpDirActivity',
|
||||
}),
|
||||
transcodeVideoChunkActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'transcodeVideoChunkActivity',
|
||||
}),
|
||||
deleteS3ObjectActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'deleteS3ObjectActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(workflowCore.updateTaskStatusActivity),
|
||||
getEmbeddingContextActivity: vi.mocked(aiActivities.getEmbeddingContextActivity),
|
||||
generateImageEmbeddingActivity: vi.mocked(aiActivities.generateImageEmbeddingActivity),
|
||||
generateVideoChunkEmbeddingActivity: vi.mocked(
|
||||
aiActivities.generateVideoChunkEmbeddingActivity,
|
||||
),
|
||||
saveAssetEmbeddingsActivity: vi.mocked(aiActivities.saveAssetEmbeddingsActivity),
|
||||
deleteAssetEmbeddingsActivity: vi.mocked(aiActivities.deleteAssetEmbeddingsActivity),
|
||||
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
|
||||
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
|
||||
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
transcodeVideoChunkActivity: vi.mocked(aiActivities.transcodeVideoChunkActivity),
|
||||
deleteS3ObjectActivity: vi.mocked(aiActivities.deleteS3ObjectActivity),
|
||||
}
|
||||
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
@@ -91,13 +98,6 @@ describe('Agent Embedding Workflow', () => {
|
||||
)
|
||||
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
|
||||
mockActivities.cleanupTmpDirActivity.mockResolvedValue(undefined)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully for image', async () => {
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
getActivities,
|
||||
executeActivity,
|
||||
TaskQueueAgent,
|
||||
TaskQueueTranscode,
|
||||
updateTaskStatusActivity,
|
||||
updateTaskUsageActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import { createCommentActivity, updateCommentActivity } from '../activities/agent'
|
||||
import {
|
||||
deleteAssetEmbeddingsActivity,
|
||||
deleteS3ObjectActivity,
|
||||
generateImageEmbeddingActivity,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
getEmbeddingContextActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
transcodeVideoChunkActivity,
|
||||
type ExistingAssetEmbeddingInfo,
|
||||
} from '../activities/ai'
|
||||
|
||||
export interface GeneratedEmbedding {
|
||||
embedding: number[]
|
||||
@@ -13,43 +22,21 @@ export interface GeneratedEmbedding {
|
||||
endTime?: number
|
||||
}
|
||||
|
||||
export interface ExistingAssetEmbeddingInfo {
|
||||
id: string
|
||||
startTime: number | null
|
||||
endTime: number | null
|
||||
has1536: boolean
|
||||
has768: boolean
|
||||
}
|
||||
export type { ExistingAssetEmbeddingInfo }
|
||||
|
||||
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getEmbeddingContextActivity,
|
||||
generateImageEmbeddingActivity,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
deleteAssetEmbeddingsActivity,
|
||||
updateTaskUsageActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
transcodeVideoChunkActivity,
|
||||
deleteS3ObjectActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
const agentWorkerQueue = TaskQueueAgent
|
||||
const transcodeWorkerQueue = TaskQueueTranscode
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// 0. Create Placeholder Comment
|
||||
const payload = task.payload
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
const placeholder = await createCommentActivity({
|
||||
assetId: task.assetId,
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: payload?.agent?.sessionId || task.id,
|
||||
@@ -62,7 +49,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 1. Fetch Agent Context
|
||||
const context = (await executeActivity(agentWorkerQueue, getEmbeddingContextActivity, {
|
||||
const context = (await getEmbeddingContextActivity({
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
})) as unknown as {
|
||||
@@ -89,7 +76,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
.map((e) => e.id)
|
||||
|
||||
if (incompatibleIds.length > 0) {
|
||||
await executeActivity(agentWorkerQueue, deleteAssetEmbeddingsActivity, {
|
||||
await deleteAssetEmbeddingsActivity({
|
||||
assetId: task.assetId,
|
||||
ids: incompatibleIds,
|
||||
})
|
||||
@@ -151,12 +138,12 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
(e) => e.startTime === null && e.endTime === null,
|
||||
)
|
||||
if (!alreadyEmbedded) {
|
||||
const result = await executeActivity(agentWorkerQueue, generateImageEmbeddingActivity, {
|
||||
const result = await generateImageEmbeddingActivity({
|
||||
teamId: task.teamId,
|
||||
assetKey: embeddingKey,
|
||||
mediaType: embeddingMediaType,
|
||||
mediaType: embeddingMediaType || 'image/jpeg',
|
||||
})
|
||||
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
|
||||
await saveAssetEmbeddingsActivity({
|
||||
assetId: task.assetId,
|
||||
embeddings: [{ embedding: result.embedding }],
|
||||
})
|
||||
@@ -197,7 +184,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Step A: Slice chunk on transcode worker and upload to S3
|
||||
const chunkRes = await executeActivity(transcodeWorkerQueue, transcodeVideoChunkActivity, {
|
||||
const chunkRes = await transcodeVideoChunkActivity({
|
||||
assetId: asset.id,
|
||||
assetKey: embeddingKey,
|
||||
startTime: start,
|
||||
@@ -208,17 +195,13 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
try {
|
||||
// Step B: Generate embedding on agent worker
|
||||
const chunkResult = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
{
|
||||
teamId: task.teamId,
|
||||
chunkKey,
|
||||
},
|
||||
)
|
||||
const chunkResult = await generateVideoChunkEmbeddingActivity({
|
||||
teamId: task.teamId,
|
||||
chunkKey,
|
||||
})
|
||||
|
||||
// Step C: Save chunk embedding to database immediately
|
||||
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
|
||||
await saveAssetEmbeddingsActivity({
|
||||
assetId: task.assetId,
|
||||
embeddings: [
|
||||
{
|
||||
@@ -235,7 +218,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
} finally {
|
||||
// Step D: Delete temporary chunk from S3
|
||||
await executeActivity(transcodeWorkerQueue, deleteS3ObjectActivity, {
|
||||
await deleteS3ObjectActivity({
|
||||
key: chunkKey,
|
||||
})
|
||||
}
|
||||
@@ -248,7 +231,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update Usage
|
||||
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||
await updateTaskUsageActivity({
|
||||
taskId: task.id,
|
||||
inputTokens: usage.inputTokens,
|
||||
outputTokens: usage.outputTokens,
|
||||
@@ -257,14 +240,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Embedding completed successfully.',
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -272,9 +255,9 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
console.error(`AgentEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId && agentWorkerQueue) {
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: `Embedding failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
})
|
||||
@@ -284,13 +267,11 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
if (agentWorkerQueue) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
}
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -351,7 +351,35 @@ describe('S3Service implementations', () => {
|
||||
|
||||
const input = await s3.resolveInput('test-bucket', 'video.mp4')
|
||||
expect(input).toBe('https://presigned.s3.url')
|
||||
expect(presignSpy).toHaveBeenCalledWith('test-bucket', 'video.mp4', 'GET')
|
||||
expect(presignSpy).toHaveBeenCalledWith(
|
||||
'test-bucket',
|
||||
'video.mp4',
|
||||
'GET',
|
||||
false,
|
||||
undefined,
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
it('should support separate publicEndpoint for presigning while resolveInput uses internal client', async () => {
|
||||
const s3 = new S3StorageService(
|
||||
'http://internal-s3:9000',
|
||||
'key',
|
||||
'secret',
|
||||
'test-bucket',
|
||||
'us-east-1',
|
||||
'https://public.example.com',
|
||||
)
|
||||
|
||||
getSignedUrlSpy.mockClear()
|
||||
await s3.presign('test-bucket', 'asset.mp4', 'GET')
|
||||
const presignClientCall = getSignedUrlSpy.mock.calls[0][0]
|
||||
|
||||
getSignedUrlSpy.mockClear()
|
||||
await s3.resolveInput('test-bucket', 'asset.mp4')
|
||||
const resolveClientCall = getSignedUrlSpy.mock.calls[0][0]
|
||||
|
||||
expect(presignClientCall).not.toBe(resolveClientCall)
|
||||
})
|
||||
|
||||
it('should stream in uploadFileToKey', async () => {
|
||||
@@ -642,6 +670,16 @@ describe('S3Service implementations', () => {
|
||||
expect(url).toContain('http://123.456.7.8:12345')
|
||||
expect(url).not.toContain('4567')
|
||||
})
|
||||
|
||||
it('should initialize S3StorageService with AWS_PUBLIC_ENDPOINT_URL_S3 when set', async () => {
|
||||
process.env.STORAGE_BACKEND = 's3'
|
||||
process.env.AWS_ENDPOINT_URL_S3 = 'http://garage.shumai.svc.cluster.local:3900'
|
||||
process.env.AWS_PUBLIC_ENDPOINT_URL_S3 = 'http://localhost:3900'
|
||||
|
||||
vi.resetModules()
|
||||
const { s3Service } = await import('./s3')
|
||||
expect(s3Service).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildContentDisposition', () => {
|
||||
|
||||
+33
-11
@@ -111,6 +111,7 @@ export interface S3Service {
|
||||
method: string,
|
||||
download?: boolean,
|
||||
filename?: string,
|
||||
internal?: boolean,
|
||||
) => Promise<string>
|
||||
presignMultipart: (
|
||||
bucket: string,
|
||||
@@ -123,6 +124,7 @@ export interface S3Service {
|
||||
|
||||
export class S3StorageService implements S3Service {
|
||||
private client: S3Client
|
||||
private presignClient: S3Client
|
||||
private bucket: string
|
||||
private presignCache = new LruTtlCache<string, string>(50000)
|
||||
|
||||
@@ -132,6 +134,7 @@ export class S3StorageService implements S3Service {
|
||||
secretAccessKey: string,
|
||||
bucket: string,
|
||||
region: string = 'auto',
|
||||
publicEndpoint?: string,
|
||||
) {
|
||||
this.client = new S3Client({
|
||||
region,
|
||||
@@ -144,6 +147,20 @@ export class S3StorageService implements S3Service {
|
||||
requestChecksumCalculation: 'WHEN_REQUIRED',
|
||||
responseChecksumValidation: 'WHEN_REQUIRED',
|
||||
})
|
||||
this.presignClient =
|
||||
publicEndpoint && publicEndpoint !== endpoint
|
||||
? new S3Client({
|
||||
region,
|
||||
endpoint: publicEndpoint,
|
||||
credentials: {
|
||||
accessKeyId,
|
||||
secretAccessKey,
|
||||
},
|
||||
forcePathStyle: true,
|
||||
requestChecksumCalculation: 'WHEN_REQUIRED',
|
||||
responseChecksumValidation: 'WHEN_REQUIRED',
|
||||
})
|
||||
: this.client
|
||||
this.bucket = bucket
|
||||
}
|
||||
|
||||
@@ -342,12 +359,13 @@ export class S3StorageService implements S3Service {
|
||||
method: string,
|
||||
download?: boolean,
|
||||
filename?: string,
|
||||
internal?: boolean,
|
||||
): Promise<string> {
|
||||
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
|
||||
const expiresInSeconds = expireHours * 3600
|
||||
const cacheTtlMs = expiresInSeconds * 1000
|
||||
|
||||
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}`
|
||||
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&internal=${internal || false}`
|
||||
if (method === 'GET' && !download) {
|
||||
const cached = this.presignCache.get(cacheKey)
|
||||
if (cached) {
|
||||
@@ -355,6 +373,7 @@ export class S3StorageService implements S3Service {
|
||||
}
|
||||
}
|
||||
|
||||
const signingClient = internal ? this.client : this.presignClient
|
||||
let url: string
|
||||
|
||||
if (method === 'GET') {
|
||||
@@ -363,19 +382,19 @@ export class S3StorageService implements S3Service {
|
||||
Key: key,
|
||||
ResponseContentDisposition: download ? buildContentDisposition(filename) : undefined,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
|
||||
} else if (method === 'PUT') {
|
||||
const command = new PutObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
|
||||
} else if (method === 'DELETE') {
|
||||
const command = new DeleteObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
|
||||
} else {
|
||||
throw new Error(`Unsupported method for presign: ${method}`)
|
||||
}
|
||||
@@ -405,13 +424,13 @@ export class S3StorageService implements S3Service {
|
||||
UploadId: request.uploadId,
|
||||
PartNumber: request.partNumber,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
|
||||
} else {
|
||||
const command = new PutObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
|
||||
}
|
||||
} else if (request.method === 'POST') {
|
||||
if (request.uploadId) {
|
||||
@@ -420,13 +439,13 @@ export class S3StorageService implements S3Service {
|
||||
Key: key,
|
||||
UploadId: request.uploadId,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
|
||||
} else {
|
||||
const command = new CreateMultipartUploadCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
|
||||
}
|
||||
} else if (request.method === 'GET') {
|
||||
if (!request.uploadId) {
|
||||
@@ -437,7 +456,7 @@ export class S3StorageService implements S3Service {
|
||||
Key: key,
|
||||
UploadId: request.uploadId,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
|
||||
} else if (request.method === 'DELETE') {
|
||||
if (!request.uploadId) {
|
||||
throw new Error('Abort multipart upload requires uploadId')
|
||||
@@ -447,7 +466,7 @@ export class S3StorageService implements S3Service {
|
||||
Key: key,
|
||||
UploadId: request.uploadId,
|
||||
})
|
||||
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
|
||||
} else {
|
||||
throw new Error(`Unsupported method for presignMultipart: ${request.method}`)
|
||||
}
|
||||
@@ -466,7 +485,7 @@ export class S3StorageService implements S3Service {
|
||||
}
|
||||
|
||||
async resolveInput(bucket: string, key: string): Promise<string> {
|
||||
return this.presign(bucket, key, 'GET')
|
||||
return this.presign(bucket, key, 'GET', false, undefined, true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -743,6 +762,8 @@ export function getStorageBackend(): 's3' | 'local' {
|
||||
const storageBackend = getStorageBackend()
|
||||
const port = process.env.SHUMAI_SERVER_PORT || '3000'
|
||||
const s3Endpoint = process.env.AWS_ENDPOINT_URL_S3 || `http://localhost:${port}`
|
||||
const s3PublicEndpoint =
|
||||
process.env.AWS_PUBLIC_ENDPOINT_URL_S3 || process.env.S3_PUBLIC_ENDPOINT || undefined
|
||||
|
||||
export const s3Service: S3Service =
|
||||
storageBackend === 's3'
|
||||
@@ -752,5 +773,6 @@ export const s3Service: S3Service =
|
||||
process.env.S3_SECRET_ACCESS_KEY || 'minioadmin',
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
process.env.S3_REGION || 'auto',
|
||||
s3PublicEndpoint,
|
||||
)
|
||||
: new LocalStorageService(s3Endpoint)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/db",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -360,6 +360,13 @@ declare global {
|
||||
imageAnnotation?: ImageAnnotationSpec
|
||||
pdfPages?: PdfPagesSpec
|
||||
watermark?: WatermarkTaskPayload
|
||||
recoveryAttempts?: number
|
||||
}
|
||||
|
||||
export interface WorkflowTaskOutput {
|
||||
error?: string
|
||||
recoveryAttempts?: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
||||
import { fileURLToPath } from 'url'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
@@ -289,4 +290,137 @@ describe('Workflow E2E - transcodePdfWorkflow', () => {
|
||||
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
|
||||
expect(mediaInfo.frames).toBeGreaterThan(0)
|
||||
}, 50000)
|
||||
|
||||
it('should recover and complete workflow when intermediate local proxy is deleted before downstream steps', async () => {
|
||||
// 1. Create Team, Project, Asset & StorageKey
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E Recovery Transcode Team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E Recovery Transcode Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'projects/e2e/recovery-doc.md',
|
||||
status: 'active',
|
||||
},
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'recovery-doc.md',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'text/markdown',
|
||||
projectId: project.id,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Seed S3 Storage with Markdown text
|
||||
const mdText = '# Recovery Test\n\nVerifying that intermediate proxy.pdf recovers from S3.'
|
||||
const mdBuffer = Buffer.from(mdText, 'utf-8')
|
||||
await s3Service.putObject(
|
||||
'shumai-e2e-test-bucket-transcode',
|
||||
'projects/e2e/recovery-doc.md',
|
||||
mdBuffer,
|
||||
mdBuffer.length,
|
||||
'text/markdown',
|
||||
)
|
||||
|
||||
// 3. Spy on createTempDir and s3Service to intercept proxy.pdf upload and delete it locally
|
||||
let capturedTmpDir: string | undefined
|
||||
const origCreateTempDir = transcodeService.createTempDir.bind(transcodeService)
|
||||
const createTempDirSpy = vi
|
||||
.spyOn(transcodeService, 'createTempDir')
|
||||
.mockImplementation((prefix: string) => {
|
||||
const dir = origCreateTempDir(prefix)
|
||||
if (prefix.startsWith('transcode-')) {
|
||||
capturedTmpDir = dir
|
||||
}
|
||||
return dir
|
||||
})
|
||||
|
||||
const origPutObject = s3Service.putObject.bind(s3Service)
|
||||
const origDownloadToFile = s3Service.downloadToFile.bind(s3Service)
|
||||
const downloadedKeys: string[] = []
|
||||
|
||||
const downloadSpy = vi
|
||||
.spyOn(s3Service, 'downloadToFile')
|
||||
.mockImplementation(async (bucket, key, localPath) => {
|
||||
downloadedKeys.push(key)
|
||||
return origDownloadToFile(bucket, key, localPath)
|
||||
})
|
||||
|
||||
const putSpy = vi.spyOn(s3Service, 'putObject').mockImplementation(async (...args) => {
|
||||
const result = await origPutObject(...args)
|
||||
const key = String(args[1] || '')
|
||||
if (key.endsWith('proxy.pdf') && capturedTmpDir) {
|
||||
// Once proxy.pdf has been uploaded to S3 by generatePdfProxyActivity,
|
||||
// delete the local file to simulate empty filesystem on a recovery/worker node.
|
||||
const localProxyPath = path.join(capturedTmpDir, 'proxy.pdf')
|
||||
if (fs.existsSync(localProxyPath)) {
|
||||
fs.unlinkSync(localProxyPath)
|
||||
}
|
||||
}
|
||||
return result
|
||||
})
|
||||
|
||||
// 4. Create Workflow Task
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'transcode_pdf',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
transcode: {
|
||||
poster: true,
|
||||
sprite: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
console.log(
|
||||
`Submitted E2E Recovery Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||
)
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
|
||||
// 5. Verification
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
const updatedAsset = await prisma.asset.findUnique({
|
||||
where: { id: asset.id },
|
||||
})
|
||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||
|
||||
const mediaInfo = updatedAsset?.media as unknown as {
|
||||
proxyType?: string
|
||||
pdfTranscode?: { key: string }
|
||||
poster?: { key: string }
|
||||
sprite?: { key: string }
|
||||
frames?: number
|
||||
}
|
||||
expect(mediaInfo).toBeDefined()
|
||||
expect(mediaInfo.proxyType).toBe('pdf')
|
||||
expect(mediaInfo.pdfTranscode?.key).toBe('projects/e2e/proxy.pdf')
|
||||
expect(mediaInfo.poster?.key).toContain('poster.webp')
|
||||
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
|
||||
expect(mediaInfo.frames).toBeGreaterThan(0)
|
||||
|
||||
// Verify that proxy.pdf was re-downloaded from S3 via ensureLocalMediaFile
|
||||
const proxyDownloadCall = downloadedKeys.find((k) => k.endsWith('proxy.pdf'))
|
||||
expect(proxyDownloadCall).toBeDefined()
|
||||
} finally {
|
||||
createTempDirSpy.mockRestore()
|
||||
downloadSpy.mockRestore()
|
||||
putSpy.mockRestore()
|
||||
}
|
||||
}, 50000)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -25,6 +25,7 @@ vi.mock('@shumai/core/src/turntable/turntable', () => ({
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
putObject: vi.fn(),
|
||||
downloadToFile: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -120,6 +121,46 @@ describe('3D Transcode Activities', () => {
|
||||
expect(res.modelMetadata).toEqual({ format: 'glb', vertices: 120 })
|
||||
})
|
||||
|
||||
it('recovers 3D model from S3 assetKey when local file is missing', async () => {
|
||||
vi.mocked(turntableService.uploadFile).mockResolvedValue({
|
||||
id: 'f_input',
|
||||
name: 'model.glb',
|
||||
size: 1024,
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.startRender).mockResolvedValue({
|
||||
taskId: 'task_render_1',
|
||||
status: 'queued',
|
||||
poster: {
|
||||
fileId: 'f_poster',
|
||||
contentType: 'image/png',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 5000,
|
||||
},
|
||||
metadata: { format: 'glb', vertices: 120 },
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.downloadFile).mockResolvedValue(Buffer.from('poster-raw-bytes'))
|
||||
|
||||
const targetPath = `/tmp/test-3d-model-${Date.now()}.glb`
|
||||
await start3dRenderActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
filePath: targetPath,
|
||||
filename: 'model.glb',
|
||||
targetPosterKey: 'files/asset-1/poster.webp',
|
||||
})
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/model.glb',
|
||||
targetPath,
|
||||
)
|
||||
})
|
||||
|
||||
it('throws ApplicationFailure when poster file ID is missing', async () => {
|
||||
vi.mocked(turntableService.uploadFile).mockResolvedValue({
|
||||
id: 'f_input',
|
||||
@@ -326,6 +367,24 @@ describe('3D Transcode Activities', () => {
|
||||
)
|
||||
expect(res.spriteKey).toBe('files/asset-1/sprite.webp')
|
||||
})
|
||||
|
||||
it('recovers turntable video from S3 videoKey when local file is missing', async () => {
|
||||
const targetPath = `/tmp/test-turntable-${Date.now()}.mp4`
|
||||
const res = await generate3dSpriteActivity({
|
||||
taskId: 'wf-task-3',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
videoKey: 'files/asset-1/turntable.mp4',
|
||||
videoFilePath: targetPath,
|
||||
spriteKey: 'files/asset-1/sprite.webp',
|
||||
})
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/turntable.mp4',
|
||||
targetPath,
|
||||
)
|
||||
expect(res.spriteKey).toBe('files/asset-1/sprite.webp')
|
||||
})
|
||||
})
|
||||
|
||||
describe('generate3dViewsActivity', () => {
|
||||
@@ -351,5 +410,23 @@ describe('3D Transcode Activities', () => {
|
||||
)
|
||||
expect(res.viewsKey).toBe('files/asset-1/views.webp')
|
||||
})
|
||||
|
||||
it('recovers turntable video from S3 videoKey when local file is missing', async () => {
|
||||
const targetPath = `/tmp/test-turntable-views-${Date.now()}.mp4`
|
||||
const res = await generate3dViewsActivity({
|
||||
taskId: 'wf-task-4',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
videoKey: 'files/asset-1/turntable.mp4',
|
||||
videoFilePath: targetPath,
|
||||
viewsKey: 'files/asset-1/views.webp',
|
||||
})
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/turntable.mp4',
|
||||
targetPath,
|
||||
)
|
||||
expect(res.viewsKey).toBe('files/asset-1/views.webp')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,6 +12,7 @@ vi.mock('child_process', () => ({
|
||||
execFile: vi.fn(),
|
||||
}))
|
||||
import {
|
||||
ensureLocalMediaFile,
|
||||
getMediaInfoActivity,
|
||||
overlayAnnotationsActivity,
|
||||
renderPdfPagesActivity,
|
||||
@@ -107,6 +108,7 @@ describe('Transcode Activities', () => {
|
||||
vi.clearAllMocks()
|
||||
const fs = await import('fs')
|
||||
vi.mocked(fs.readFileSync).mockImplementation(() => Buffer.from('fake data') as never)
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true)
|
||||
})
|
||||
|
||||
it('should convert CSV via Gotenberg in landscape mode when maxCols > 5', async () => {
|
||||
@@ -218,6 +220,40 @@ describe('Transcode Activities', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('should resolve presigned URL when assetKey is provided without filePath for video', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: { name: 'remote-video.mp4', type: 'file', status: 'uploaded' },
|
||||
})
|
||||
|
||||
vi.spyOn(s3Service, 'resolveInput').mockResolvedValueOnce(
|
||||
'http://s3.local/shumai/remote-video.mp4?presigned=true',
|
||||
)
|
||||
vi.mocked(transcodeService.getVideoInfo).mockResolvedValueOnce({
|
||||
originalWidth: 1920,
|
||||
originalHeight: 1080,
|
||||
duration: 15,
|
||||
bitRate: 1000000,
|
||||
videoBitRate: 800000,
|
||||
frameRate: 30,
|
||||
totalFrames: 450,
|
||||
hasAudio: false,
|
||||
mimeType: 'video/mp4',
|
||||
})
|
||||
|
||||
const result = await getMediaInfoActivity({
|
||||
assetId: asset.id,
|
||||
assetKey: 'remote-video.mp4',
|
||||
proxyType: 'video',
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
|
||||
expect(s3Service.resolveInput).toHaveBeenCalledWith(expect.any(String), 'remote-video.mp4')
|
||||
expect(transcodeService.getVideoInfo).toHaveBeenCalledWith(
|
||||
'http://s3.local/shumai/remote-video.mp4?presigned=true',
|
||||
)
|
||||
expect(result.duration).toBe(15)
|
||||
})
|
||||
|
||||
it('should downgrade proxyType to audio when getVideoInfo throws No video stream found but audio exists', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: { name: 'audio-with-art.mp4', type: 'file', status: 'uploaded' },
|
||||
@@ -907,14 +943,43 @@ describe('Transcode Activities', () => {
|
||||
})
|
||||
|
||||
describe('Non-retryable Error Handling', () => {
|
||||
it('should throw non-retryable ApplicationFailure when downloadMediaToTmpActivity fails with ENOENT', async () => {
|
||||
it('should throw non-retryable ApplicationFailure when downloadMediaToTmpActivity fails with ENOENT or AWS SDK NoSuchKey', async () => {
|
||||
vi.mocked(s3Service.downloadToFile).mockRejectedValue({
|
||||
code: 'ENOENT',
|
||||
message: 'ENOENT: no such file or directory',
|
||||
name: 'NoSuchKey',
|
||||
message: 'The specified key does not exist.',
|
||||
})
|
||||
|
||||
await expect(downloadMediaToTmpActivity({ assetKey: 'missing.mp4' })).rejects.toThrowError(
|
||||
/Failed to download media to tmp/,
|
||||
await expect(downloadMediaToTmpActivity({ assetKey: 'missing.mp4' })).rejects.toMatchObject({
|
||||
message: expect.stringMatching(/Failed to download media to tmp/),
|
||||
nonRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when ensureLocalMediaFile fails with ENOENT or AWS SDK NoSuchKey', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false)
|
||||
vi.mocked(s3Service.downloadToFile).mockRejectedValue({
|
||||
name: 'NoSuchKey',
|
||||
message: 'The specified key does not exist.',
|
||||
})
|
||||
|
||||
const targetPath = `/tmp/test-recovery-${Date.now()}.mp4`
|
||||
await expect(ensureLocalMediaFile('missing.mp4', targetPath)).rejects.toMatchObject({
|
||||
message: expect.stringMatching(/Failed to download media to local file/),
|
||||
nonRetryable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('should recover missing local file from S3 via ensureLocalMediaFile', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false)
|
||||
vi.mocked(s3Service.downloadToFile).mockResolvedValue()
|
||||
const targetPath = `/tmp/test-recovery-${Date.now()}.mp4`
|
||||
|
||||
const result = await ensureLocalMediaFile('asset.mp4', targetPath)
|
||||
expect(result).toBe(targetPath)
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'asset.mp4',
|
||||
targetPath,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1108,6 +1173,37 @@ describe('Transcode Activities', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('generateSpriteActivity recovers local file from inputKey when provided and missing on disk', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false)
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
vi.mocked(s3Service.downloadToFile).mockResolvedValue()
|
||||
vi.mocked(transcodeService.generateSprite).mockImplementation(
|
||||
async (_in, spriteOut, posterOut) => {
|
||||
const fs = await import('fs')
|
||||
fs.writeFileSync(spriteOut, 'fake-sprite')
|
||||
fs.writeFileSync(posterOut, 'fake-poster')
|
||||
},
|
||||
)
|
||||
|
||||
const targetPath = `/tmp/test-sprite-${Date.now()}.pdf`
|
||||
await generateSpriteActivity({
|
||||
assetKey: 'files/asset-1/doc.docx',
|
||||
inputKey: 'files/asset-1/proxy.pdf',
|
||||
filePath: targetPath,
|
||||
mediaInfo: {
|
||||
duration: 10,
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
spriteSpec: { key: 'files/asset-1/sprite.webp', frames: 100, tileX: 10, tileY: 10 },
|
||||
posterSpec: { key: 'files/asset-1/poster.webp' },
|
||||
})
|
||||
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/asset-1/proxy.pdf',
|
||||
targetPath,
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when takeScreenshotsActivity fails with error', async () => {
|
||||
vi.mocked(transcodeService.takeScreenshots).mockRejectedValue(new Error('FFmpeg failed'))
|
||||
|
||||
|
||||
@@ -22,38 +22,19 @@ import {
|
||||
isMarkdownDocument,
|
||||
isOfficeDocument,
|
||||
} from '@shumai/core/src/utils/mime'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { ApplicationFailure, getLocalTaskAbortSignal } from '@shumai/workflow-core'
|
||||
|
||||
function getActivityCancellationSignal(taskId?: string): AbortSignal | undefined {
|
||||
return getLocalTaskAbortSignal(taskId)
|
||||
}
|
||||
|
||||
export async function ensureLocalMediaFile(assetKey: string, filePath: string): Promise<string> {
|
||||
if (fs.existsSync(filePath)) {
|
||||
return filePath
|
||||
}
|
||||
const dir = path.dirname(filePath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.downloadToFile(bucket, assetKey, filePath)
|
||||
return filePath
|
||||
}
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { ulid } from 'ulid'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { ApplicationFailure, defineStep, getLocalTaskAbortSignal } from '@shumai/workflow-core'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
export interface GetMediaInfoActivityParams {
|
||||
assetId: string
|
||||
assetKey: string
|
||||
mediaType: string
|
||||
function getActivityCancellationSignal(taskId?: string): AbortSignal | undefined {
|
||||
return getLocalTaskAbortSignal(taskId)
|
||||
}
|
||||
|
||||
function getErrorDetails(err: unknown): { code?: string; message: string; name?: string } {
|
||||
@@ -75,6 +56,46 @@ function getErrorDetails(err: unknown): { code?: string; message: string; name?:
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureLocalMediaFile(assetKey: string, filePath: string): Promise<string> {
|
||||
if (fs.existsSync(filePath)) {
|
||||
return filePath
|
||||
}
|
||||
const dir = path.dirname(filePath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
try {
|
||||
await s3Service.downloadToFile(bucket, assetKey, filePath)
|
||||
} catch (err) {
|
||||
const { code, message, name } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
const lowerCode = (code || '').toLowerCase()
|
||||
const lowerName = (name || '').toLowerCase()
|
||||
if (
|
||||
lowerCode === 'enoent' ||
|
||||
lowerCode === 'nosuchkey' ||
|
||||
lowerName === 'nosuchkey' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('nosuchkey')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to download media to local file: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
return filePath
|
||||
}
|
||||
|
||||
export interface GetMediaInfoActivityParams {
|
||||
assetId: string
|
||||
assetKey: string
|
||||
mediaType: string
|
||||
}
|
||||
|
||||
async function ensureAssetNotPurging(assetKey: string): Promise<void> {
|
||||
const sk = await prisma.storageKey.findUnique({
|
||||
where: { key: assetKey },
|
||||
@@ -93,20 +114,46 @@ async function ensureAssetNotPurging(assetKey: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMediaInfoActivity(params: {
|
||||
filePath: string
|
||||
export const getMediaInfoActivity = defineStep(async function getMediaInfoActivity(params: {
|
||||
filePath?: string
|
||||
assetKey?: string
|
||||
assetId: string
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
mediaType?: string
|
||||
}): Promise<PrismaJson.MediaInfo> {
|
||||
let tempLocalDir: string | undefined
|
||||
try {
|
||||
const proxyType =
|
||||
params.proxyType || getProxyType(params.mediaType, params.filePath) || undefined
|
||||
params.proxyType ||
|
||||
getProxyType(params.mediaType, params.filePath || params.assetKey) ||
|
||||
undefined
|
||||
const isVideo = proxyType === 'video'
|
||||
const isImage = proxyType === 'image'
|
||||
const isAudio = proxyType === 'audio'
|
||||
const isPdf = proxyType === 'pdf'
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
let mediaSource = params.filePath
|
||||
if (!mediaSource) {
|
||||
if (params.assetKey) {
|
||||
if (isVideo || isAudio) {
|
||||
mediaSource = await s3Service.resolveInput(bucket, params.assetKey)
|
||||
} else {
|
||||
tempLocalDir = transcodeService.createTempDir('mediainfo-')
|
||||
const ext = path.extname(params.assetKey) || (isImage ? '.jpg' : isPdf ? '.pdf' : '')
|
||||
const localTarget = path.join(tempLocalDir, `input${ext}`)
|
||||
mediaSource = await ensureLocalMediaFile(params.assetKey, localTarget)
|
||||
}
|
||||
} else {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Neither filePath nor assetKey provided to getMediaInfoActivity',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
} else if (params.assetKey) {
|
||||
mediaSource = await ensureLocalMediaFile(params.assetKey, mediaSource)
|
||||
}
|
||||
|
||||
const fileType = isVideo
|
||||
? 'video'
|
||||
: isAudio
|
||||
@@ -145,11 +192,11 @@ export async function getMediaInfoActivity(params: {
|
||||
let isDowngradedToAudio = false
|
||||
let videoInfo: Awaited<ReturnType<typeof transcodeService.getVideoInfo>> | null = null
|
||||
try {
|
||||
videoInfo = await transcodeService.getVideoInfo(params.filePath)
|
||||
videoInfo = await transcodeService.getVideoInfo(mediaSource)
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.message.includes('No video stream found')) {
|
||||
try {
|
||||
const audioInfo = await transcodeService.getAudioInfo(params.filePath)
|
||||
const audioInfo = await transcodeService.getAudioInfo(mediaSource)
|
||||
isDowngradedToAudio = true
|
||||
mediaInfo.proxyType = 'audio'
|
||||
mediaInfo.duration = audioInfo.duration
|
||||
@@ -247,7 +294,7 @@ export async function getMediaInfoActivity(params: {
|
||||
metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth })
|
||||
}
|
||||
} else if (isAudio) {
|
||||
const info = await transcodeService.getAudioInfo(params.filePath)
|
||||
const info = await transcodeService.getAudioInfo(mediaSource)
|
||||
mediaInfo.duration = info.duration
|
||||
mediaInfo.metadata = {
|
||||
originalWidth: 0,
|
||||
@@ -278,7 +325,7 @@ export async function getMediaInfoActivity(params: {
|
||||
if (info.audioBitDepth !== undefined)
|
||||
metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth })
|
||||
} else if (isImage) {
|
||||
const info = await transcodeService.getImageInfo(params.filePath)
|
||||
const info = await transcodeService.getImageInfo(mediaSource)
|
||||
mediaInfo.metadata = {
|
||||
originalWidth: info.originalWidth,
|
||||
originalHeight: info.originalHeight,
|
||||
@@ -295,7 +342,7 @@ export async function getMediaInfoActivity(params: {
|
||||
{ key: 'resolution_height', value: info.originalHeight },
|
||||
)
|
||||
} else if (isPdf) {
|
||||
const info = await transcodeService.getPdfInfo(params.filePath)
|
||||
const info = await transcodeService.getPdfInfo(mediaSource)
|
||||
mediaInfo.frames = info.totalFrames
|
||||
mediaInfo.metadata = {
|
||||
originalWidth: info.originalWidth,
|
||||
@@ -328,8 +375,16 @@ export async function getMediaInfoActivity(params: {
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
} finally {
|
||||
if (tempLocalDir) {
|
||||
try {
|
||||
fs.rmSync(tempLocalDir, { recursive: true, force: true })
|
||||
} catch {
|
||||
// ignore cleanup error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface VideoActivityParams {
|
||||
taskId?: string
|
||||
@@ -351,7 +406,7 @@ export interface VideoActivityParams {
|
||||
audioStreamIndex?: number
|
||||
}
|
||||
|
||||
export async function transcodeVideoActivity(
|
||||
export const transcodeVideoActivity = defineStep(async function transcodeVideoActivity(
|
||||
params: VideoActivityParams,
|
||||
): Promise<PrismaJson.VideoTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -460,7 +515,7 @@ export async function transcodeVideoActivity(
|
||||
} finally {
|
||||
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface HlsActivityParams {
|
||||
taskId: string
|
||||
@@ -484,7 +539,9 @@ export interface HlsActivityParams {
|
||||
audioStreamIndex?: number
|
||||
}
|
||||
|
||||
export async function transcodeHlsActivity(params: HlsActivityParams): Promise<PrismaJson.HlsInfo> {
|
||||
export const transcodeHlsActivity = defineStep(async function transcodeHlsActivity(
|
||||
params: HlsActivityParams,
|
||||
): Promise<PrismaJson.HlsInfo> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const assetDir = path.posix.dirname(params.assetKey)
|
||||
const hlsDirKey = path.posix.join(assetDir, 'hls')
|
||||
@@ -648,7 +705,7 @@ export async function transcodeHlsActivity(params: HlsActivityParams): Promise<P
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface AudioActivityParams {
|
||||
taskId?: string
|
||||
@@ -658,7 +715,7 @@ export interface AudioActivityParams {
|
||||
audioStreamIndex?: number
|
||||
}
|
||||
|
||||
export async function transcodeAudioActivity(
|
||||
export const transcodeAudioActivity = defineStep(async function transcodeAudioActivity(
|
||||
params: AudioActivityParams,
|
||||
): Promise<PrismaJson.VideoTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -736,7 +793,7 @@ export async function transcodeAudioActivity(
|
||||
} finally {
|
||||
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface ImageActivityParams {
|
||||
assetKey: string
|
||||
@@ -744,7 +801,7 @@ export interface ImageActivityParams {
|
||||
imageSpec: PrismaJson.ImageTranscode
|
||||
}
|
||||
|
||||
export async function transcodeImageActivity(
|
||||
export const transcodeImageActivity = defineStep(async function transcodeImageActivity(
|
||||
params: ImageActivityParams,
|
||||
): Promise<PrismaJson.ImageTranscode> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -807,18 +864,21 @@ export async function transcodeImageActivity(
|
||||
} finally {
|
||||
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface GenerateSpriteActivityParams {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
inputKey?: string
|
||||
filePath: string
|
||||
mediaInfo: PrismaJson.MediaInfo
|
||||
spriteSpec: PrismaJson.SpriteInfo
|
||||
posterSpec: PrismaJson.PosterInfo
|
||||
}
|
||||
|
||||
export async function generateSpriteActivity(params: GenerateSpriteActivityParams) {
|
||||
export const generateSpriteActivity = defineStep(async function generateSpriteActivity(
|
||||
params: GenerateSpriteActivityParams,
|
||||
) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
@@ -836,7 +896,7 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
|
||||
// Not found
|
||||
}
|
||||
|
||||
await ensureLocalMediaFile(params.assetKey, params.filePath)
|
||||
await ensureLocalMediaFile(params.inputKey || params.assetKey, params.filePath)
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const spriteFile = path.join(tmpDir, 'sprite.webp')
|
||||
const posterFile = path.join(tmpDir, 'poster.webp')
|
||||
@@ -929,7 +989,7 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
|
||||
if (fs.existsSync(spriteFile)) fs.unlinkSync(spriteFile)
|
||||
if (fs.existsSync(posterFile)) fs.unlinkSync(posterFile)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface GeneratePdfProxyActivityParams {
|
||||
teamId?: string | null
|
||||
@@ -940,9 +1000,11 @@ export interface GeneratePdfProxyActivityParams {
|
||||
filename: string
|
||||
}
|
||||
|
||||
export async function generatePdfProxyActivity(
|
||||
export const generatePdfProxyActivity = defineStep(async function generatePdfProxyActivity(
|
||||
params: GeneratePdfProxyActivityParams,
|
||||
): Promise<{ pdfProxyKey: string; pdfFilePath: string }> {
|
||||
await ensureLocalMediaFile(params.assetKey, params.filePath)
|
||||
|
||||
const isOffice = isOfficeDocument(params.mediaType, params.filename)
|
||||
const isHtml = isHtmlDocument(params.mediaType, params.filename)
|
||||
const isMd = isMarkdownDocument(params.mediaType, params.filename)
|
||||
@@ -1054,47 +1116,62 @@ export async function generatePdfProxyActivity(
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export async function downloadMediaToTmpActivity(params: {
|
||||
assetKey: string
|
||||
}): Promise<{ filePath: string; tmpDir: string }> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = transcodeService.createTempDir('transcode-')
|
||||
const filePath = path.join(tmpDir, path.basename(params.assetKey))
|
||||
export const downloadMediaToTmpActivity = defineStep(
|
||||
async function downloadMediaToTmpActivity(params: {
|
||||
assetKey: string
|
||||
}): Promise<{ filePath: string; tmpDir: string }> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = transcodeService.createTempDir('transcode-')
|
||||
const filePath = path.join(tmpDir, path.basename(params.assetKey))
|
||||
|
||||
if (!fs.existsSync(tmpDir)) {
|
||||
fs.mkdirSync(tmpDir, { recursive: true })
|
||||
}
|
||||
|
||||
try {
|
||||
await s3Service.downloadToFile(bucket, params.assetKey, filePath)
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
if (code === 'ENOENT' || lowerMsg.includes('enoent') || lowerMsg.includes('nosuchkey')) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to download media to tmp: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
if (!fs.existsSync(tmpDir)) {
|
||||
fs.mkdirSync(tmpDir, { recursive: true })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
return { filePath, tmpDir }
|
||||
}
|
||||
try {
|
||||
await s3Service.downloadToFile(bucket, params.assetKey, filePath)
|
||||
} catch (err) {
|
||||
const { code, message, name } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
const lowerCode = (code || '').toLowerCase()
|
||||
const lowerName = (name || '').toLowerCase()
|
||||
if (
|
||||
lowerCode === 'enoent' ||
|
||||
lowerCode === 'nosuchkey' ||
|
||||
lowerName === 'nosuchkey' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('nosuchkey')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to download media to tmp: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
export async function cleanupTmpDirActivity(params: { tmpDir: string }): Promise<void> {
|
||||
transcodeService.removeDir(params.tmpDir)
|
||||
}
|
||||
return { filePath, tmpDir }
|
||||
},
|
||||
)
|
||||
|
||||
export const cleanupTmpDirActivity = defineStep(
|
||||
async function cleanupTmpDirActivity(params: { tmpDir: string }): Promise<void> {
|
||||
transcodeService.removeDir(params.tmpDir)
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface UpdateAssetMediaActivityParams {
|
||||
assetId: string
|
||||
mediaInfo: PrismaJson.MediaInfo
|
||||
}
|
||||
|
||||
export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityParams) {
|
||||
export const updateAssetMediaActivity = defineStep(async function updateAssetMediaActivity(
|
||||
params: UpdateAssetMediaActivityParams,
|
||||
) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
@@ -1126,9 +1203,9 @@ export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityP
|
||||
'[updateAssetMediaActivity] Asset was deleted or pending purge before media update completed',
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export async function takeScreenshotsActivity(params: {
|
||||
export const takeScreenshotsActivity = defineStep(async function takeScreenshotsActivity(params: {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
assetId: string
|
||||
@@ -1180,7 +1257,7 @@ export async function takeScreenshotsActivity(params: {
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface ExtractPosterActivityParams {
|
||||
assetKey: string
|
||||
@@ -1193,7 +1270,7 @@ export interface ExtractPosterActivityParams {
|
||||
streamIndex?: number
|
||||
}
|
||||
|
||||
export async function extractPosterActivity(
|
||||
export const extractPosterActivity = defineStep(async function extractPosterActivity(
|
||||
params: ExtractPosterActivityParams,
|
||||
): Promise<{ poster: PrismaJson.PosterInfo }> {
|
||||
const signal = params.signal || getActivityCancellationSignal(params.taskId)
|
||||
@@ -1272,36 +1349,38 @@ export async function extractPosterActivity(
|
||||
} finally {
|
||||
transcodeService.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export async function overlayAnnotationsActivity(params: {
|
||||
assetKey: string
|
||||
assetId: string
|
||||
annotations: PrismaJson.AnnotationList
|
||||
}): Promise<string> {
|
||||
try {
|
||||
return await transcodeService.overlayAnnotations(params)
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('nosuchkey') ||
|
||||
lowerMsg.includes('ffmpeg') ||
|
||||
lowerMsg.includes('sharp')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Overlay annotations failed: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
export const overlayAnnotationsActivity = defineStep(
|
||||
async function overlayAnnotationsActivity(params: {
|
||||
assetKey: string
|
||||
assetId: string
|
||||
annotations: PrismaJson.AnnotationList
|
||||
}): Promise<string> {
|
||||
try {
|
||||
return await transcodeService.overlayAnnotations(params)
|
||||
} catch (err) {
|
||||
const { code, message } = getErrorDetails(err)
|
||||
const lowerMsg = message.toLowerCase()
|
||||
if (
|
||||
code === 'ENOENT' ||
|
||||
lowerMsg.includes('enoent') ||
|
||||
lowerMsg.includes('nosuchkey') ||
|
||||
lowerMsg.includes('ffmpeg') ||
|
||||
lowerMsg.includes('sharp')
|
||||
) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Overlay annotations failed: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export async function renderPdfPagesActivity(params: {
|
||||
export const renderPdfPagesActivity = defineStep(async function renderPdfPagesActivity(params: {
|
||||
taskId?: string
|
||||
assetKey: string
|
||||
assetId: string
|
||||
@@ -1352,7 +1431,7 @@ export async function renderPdfPagesActivity(params: {
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface CreateEmbeddingTaskIfEnabledParams {
|
||||
assetId: string
|
||||
@@ -1360,75 +1439,77 @@ export interface CreateEmbeddingTaskIfEnabledParams {
|
||||
projectId: string | null
|
||||
}
|
||||
|
||||
export async function createEmbeddingTaskIfEnabledActivity(
|
||||
params: CreateEmbeddingTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
})
|
||||
if (!asset) {
|
||||
return
|
||||
}
|
||||
|
||||
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
|
||||
const isVideo = asset.mediaType?.startsWith('video/')
|
||||
const isImage =
|
||||
asset.mediaType?.startsWith('image/') ||
|
||||
(mediaInfo?.proxyType === '3d' && (mediaInfo.imageTranscodes?.length ?? 0) > 0)
|
||||
if (!isVideo && !isImage) {
|
||||
return
|
||||
}
|
||||
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active embedding agent for the team
|
||||
const embeddingAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!embeddingAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing embedding task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create embedding task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: embeddingAgent.id },
|
||||
export const createEmbeddingTaskIfEnabledActivity = defineStep(
|
||||
async function createEmbeddingTaskIfEnabledActivity(
|
||||
params: CreateEmbeddingTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
if (!asset) {
|
||||
return
|
||||
}
|
||||
|
||||
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
|
||||
const isVideo = asset.mediaType?.startsWith('video/')
|
||||
const isImage =
|
||||
asset.mediaType?.startsWith('image/') ||
|
||||
(mediaInfo?.proxyType === '3d' && (mediaInfo.imageTranscodes?.length ?? 0) > 0)
|
||||
if (!isVideo && !isImage) {
|
||||
return
|
||||
}
|
||||
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active embedding agent for the team
|
||||
const embeddingAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!embeddingAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing embedding task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create embedding task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: embeddingAgent.id },
|
||||
},
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export interface CreateAutofillTaskIfEnabledParams {
|
||||
assetId: string
|
||||
@@ -1436,66 +1517,68 @@ export interface CreateAutofillTaskIfEnabledParams {
|
||||
projectId: string | null
|
||||
}
|
||||
|
||||
export async function createAutofillTaskIfEnabledActivity(
|
||||
params: CreateAutofillTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
})
|
||||
if (!asset || (asset.type !== 'file' && asset.type !== 'version_stack')) {
|
||||
return
|
||||
}
|
||||
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active autofill agent for the team
|
||||
const autofillAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!autofillAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing autofill task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create autofill task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: autofillAgent.id },
|
||||
export const createAutofillTaskIfEnabledActivity = defineStep(
|
||||
async function createAutofillTaskIfEnabledActivity(
|
||||
params: CreateAutofillTaskIfEnabledParams,
|
||||
): Promise<void> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
if (!asset || (asset.type !== 'file' && asset.type !== 'version_stack')) {
|
||||
return
|
||||
}
|
||||
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if there is an active autofill agent for the team
|
||||
const autofillAgent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!autofillAgent) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if a pending/processing autofill task already exists for this asset to avoid duplicates
|
||||
const existing = await prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create autofill task
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId,
|
||||
payload: {
|
||||
projectId: projectId ?? '',
|
||||
agent: { agentId: autofillAgent.id },
|
||||
},
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export interface TranscodeVideoChunkParams {
|
||||
assetId: string
|
||||
@@ -1506,7 +1589,7 @@ export interface TranscodeVideoChunkParams {
|
||||
format?: 'video' | 'frames'
|
||||
}
|
||||
|
||||
export async function transcodeVideoChunkActivity(
|
||||
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
|
||||
params: TranscodeVideoChunkParams,
|
||||
): Promise<{ chunkKey: string }> {
|
||||
if (!params.filePath && !params.assetKey) {
|
||||
@@ -1660,12 +1743,15 @@ export async function transcodeVideoChunkActivity(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
}
|
||||
export const deleteS3ObjectActivity = defineStep(
|
||||
async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface Render3dModelActivityParams {
|
||||
taskId: string
|
||||
@@ -1702,7 +1788,7 @@ export interface Start3dRenderActivityResult {
|
||||
modelMetadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export async function start3dRenderActivity(
|
||||
export const start3dRenderActivity = defineStep(async function start3dRenderActivity(
|
||||
params: Start3dRenderActivityParams,
|
||||
): Promise<Start3dRenderActivityResult> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
@@ -1713,6 +1799,8 @@ export async function start3dRenderActivity(
|
||||
})
|
||||
}
|
||||
|
||||
await ensureLocalMediaFile(params.assetKey, params.filePath)
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const posterFilePath = path.join(tmpDir, 'poster.webp')
|
||||
@@ -1783,7 +1871,7 @@ export async function start3dRenderActivity(
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface WaitFor3dVideoRenderActivityParams {
|
||||
taskId: string
|
||||
@@ -1798,7 +1886,7 @@ export interface WaitFor3dVideoRenderActivityResult {
|
||||
videoFilePath: string
|
||||
}
|
||||
|
||||
export async function waitFor3dVideoRenderActivity(
|
||||
export const waitFor3dVideoRenderActivity = defineStep(async function waitFor3dVideoRenderActivity(
|
||||
params: WaitFor3dVideoRenderActivityParams,
|
||||
): Promise<WaitFor3dVideoRenderActivityResult> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
@@ -1897,12 +1985,12 @@ export async function waitFor3dVideoRenderActivity(
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* @deprecated Legacy monolithic 3D render activity. Prefer using `start3dRenderActivity` and `waitFor3dVideoRenderActivity`.
|
||||
*/
|
||||
export async function render3dModelActivity(
|
||||
export const render3dModelActivity = defineStep(async function render3dModelActivity(
|
||||
params: Render3dModelActivityParams,
|
||||
): Promise<Render3dModelActivityResult> {
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
@@ -1930,16 +2018,17 @@ export async function render3dModelActivity(
|
||||
posterFilePath: startResult.posterFilePath,
|
||||
modelMetadata: startResult.modelMetadata,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface Generate3dSpriteActivityParams {
|
||||
taskId: string
|
||||
assetKey: string
|
||||
videoKey?: string
|
||||
videoFilePath: string
|
||||
spriteKey: string
|
||||
}
|
||||
|
||||
export async function generate3dSpriteActivity(
|
||||
export const generate3dSpriteActivity = defineStep(async function generate3dSpriteActivity(
|
||||
params: Generate3dSpriteActivityParams,
|
||||
): Promise<{ spriteKey: string }> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
@@ -1950,6 +2039,9 @@ export async function generate3dSpriteActivity(
|
||||
})
|
||||
}
|
||||
|
||||
const downloadKey = params.videoKey || params.assetKey
|
||||
await ensureLocalMediaFile(downloadKey, params.videoFilePath)
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = path.dirname(params.videoFilePath)
|
||||
const spriteFilePath = path.join(tmpDir, 'sprite.webp')
|
||||
@@ -1978,16 +2070,17 @@ export async function generate3dSpriteActivity(
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface Generate3dViewsActivityParams {
|
||||
taskId: string
|
||||
assetKey: string
|
||||
videoKey?: string
|
||||
videoFilePath: string
|
||||
viewsKey: string
|
||||
}
|
||||
|
||||
export async function generate3dViewsActivity(
|
||||
export const generate3dViewsActivity = defineStep(async function generate3dViewsActivity(
|
||||
params: Generate3dViewsActivityParams,
|
||||
): Promise<{ viewsKey: string }> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
@@ -1998,6 +2091,9 @@ export async function generate3dViewsActivity(
|
||||
})
|
||||
}
|
||||
|
||||
const downloadKey = params.videoKey || params.assetKey
|
||||
await ensureLocalMediaFile(downloadKey, params.videoFilePath)
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = path.dirname(params.videoFilePath)
|
||||
const viewsFilePath = path.join(tmpDir, 'views.webp')
|
||||
@@ -2026,4 +2122,4 @@ export async function generate3dViewsActivity(
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure, defineStep } from '@shumai/workflow-core'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
import { ulid } from 'ulid'
|
||||
@@ -35,7 +35,7 @@ export interface InitWatermarkFileResult {
|
||||
media?: PrismaJson.MediaInfo | null
|
||||
}
|
||||
|
||||
export async function initWatermarkFileActivity(
|
||||
export const initWatermarkFileActivity = defineStep(async function initWatermarkFileActivity(
|
||||
params: InitWatermarkFileParams,
|
||||
): Promise<InitWatermarkFileResult> {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
@@ -46,12 +46,12 @@ export async function initWatermarkFileActivity(
|
||||
media: PrismaJson.MediaInfo | null
|
||||
}>
|
||||
>`
|
||||
SELECT id, status, media
|
||||
FROM watermark_files
|
||||
WHERE asset_id = ${params.assetId}
|
||||
AND watermark_config_id = ${params.watermarkConfigId}
|
||||
FOR UPDATE
|
||||
`
|
||||
SELECT id, status, media
|
||||
FROM watermark_files
|
||||
WHERE asset_id = ${params.assetId}
|
||||
AND watermark_config_id = ${params.watermarkConfigId}
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
if (rows.length > 0) {
|
||||
const existing = rows[0]
|
||||
@@ -74,7 +74,7 @@ export async function initWatermarkFileActivity(
|
||||
|
||||
return { action: 'created' }
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export interface WaitForWatermarkFileParams {
|
||||
assetId: string
|
||||
@@ -86,7 +86,7 @@ export interface WaitForWatermarkFileResult {
|
||||
media?: PrismaJson.MediaInfo | null
|
||||
}
|
||||
|
||||
export async function waitForWatermarkFileActivity(
|
||||
export const waitForWatermarkFileActivity = defineStep(async function waitForWatermarkFileActivity(
|
||||
params: WaitForWatermarkFileParams,
|
||||
): Promise<WaitForWatermarkFileResult> {
|
||||
const pollIntervalMs = 1000
|
||||
@@ -113,358 +113,278 @@ export async function waitForWatermarkFileActivity(
|
||||
}
|
||||
|
||||
return { status: WatermarkFileStatus.failed }
|
||||
}
|
||||
})
|
||||
|
||||
export interface TranscodeWatermarkMediaParams {
|
||||
assetId: string
|
||||
watermarkConfigId: string
|
||||
}
|
||||
|
||||
export async function transcodeWatermarkMediaActivity(
|
||||
params: TranscodeWatermarkMediaParams,
|
||||
): Promise<PrismaJson.MediaInfo> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
export const transcodeWatermarkMediaActivity = defineStep(
|
||||
async function transcodeWatermarkMediaActivity(
|
||||
params: TranscodeWatermarkMediaParams,
|
||||
): Promise<PrismaJson.MediaInfo> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
const watermarkConfigRecord = await prisma.watermarkConfig.findUnique({
|
||||
where: { id: params.watermarkConfigId },
|
||||
})
|
||||
if (!watermarkConfigRecord) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Watermark config not found: ${params.watermarkConfigId}`,
|
||||
nonRetryable: true,
|
||||
const watermarkConfigRecord = await prisma.watermarkConfig.findUnique({
|
||||
where: { id: params.watermarkConfigId },
|
||||
})
|
||||
}
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: { team: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!asset || !asset.storageKey?.key) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset or storage key not found: ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const teamSettings = asset.project?.team?.settings as PrismaJson.Settings | null
|
||||
const hardwareAcceleration = teamSettings?.transcode?.hardwareAcceleration ?? 'off'
|
||||
const threads = teamSettings?.transcode?.threads ?? 0
|
||||
|
||||
// The config column is declared as PrismaJson.WatermarkConfigSpec, which is
|
||||
// structurally identical to the DTO type, so no cast is required.
|
||||
const config: WatermarkConfigSpec = watermarkConfigRecord.config
|
||||
const assetKey = asset.storageKey.key
|
||||
const stem = stemFromKey(assetKey)
|
||||
|
||||
const tmpDir = transcodeService.createTempDir('watermark-')
|
||||
|
||||
try {
|
||||
const is3d = (asset.media as PrismaJson.MediaInfo | null)?.proxyType === '3d'
|
||||
const isVideo =
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('video/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video')
|
||||
const isImage =
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('image/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image')
|
||||
|
||||
if (!isVideo && !isImage && !is3d) {
|
||||
if (!watermarkConfigRecord) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset ${params.assetId} is neither video nor image`,
|
||||
message: `Watermark config not found: ${params.watermarkConfigId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const inputKey = is3d
|
||||
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
|
||||
: assetKey
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: { team: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (is3d && !inputKey) {
|
||||
if (!asset || !asset.storageKey?.key) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
|
||||
message: `Asset or storage key not found: ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
|
||||
await s3Service.downloadToFile(bucket, inputKey!, rawFilePath)
|
||||
const teamSettings = asset.project?.team?.settings as PrismaJson.Settings | null
|
||||
const hardwareAcceleration = teamSettings?.transcode?.hardwareAcceleration ?? 'off'
|
||||
const threads = teamSettings?.transcode?.threads ?? 0
|
||||
|
||||
let originalWidth = 1920
|
||||
let originalHeight = 1080
|
||||
let duration = 0
|
||||
let bitRate = 0
|
||||
let videoBitRate: number | undefined
|
||||
let frameRate = 30
|
||||
let totalFrames = 0
|
||||
let startTimecode = '00:00:00:00'
|
||||
let hasAudio = false
|
||||
let sourceVideoBitrate: number | undefined
|
||||
let colorTransfer: string | undefined
|
||||
let colorPrimaries: string | undefined
|
||||
let colorSpace: string | undefined
|
||||
let isHdr: boolean | undefined
|
||||
let hdrType: PrismaJson.HdrType | undefined
|
||||
let dvProfile: number | undefined
|
||||
// The config column is declared as PrismaJson.WatermarkConfigSpec, which is
|
||||
// structurally identical to the DTO type, so no cast is required.
|
||||
const config: WatermarkConfigSpec = watermarkConfigRecord.config
|
||||
const assetKey = asset.storageKey.key
|
||||
const stem = stemFromKey(assetKey)
|
||||
|
||||
if (isVideo || is3d) {
|
||||
const info = await transcodeService.getVideoInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
duration = info.duration
|
||||
bitRate = info.bitRate
|
||||
videoBitRate = info.videoBitRate
|
||||
frameRate = info.frameRate
|
||||
totalFrames = info.totalFrames
|
||||
startTimecode = info.startTimecode || '00:00:00:00'
|
||||
hasAudio = info.hasAudio
|
||||
sourceVideoBitrate = info.videoBitRate || info.bitRate
|
||||
colorTransfer = info.colorTransfer
|
||||
colorPrimaries = info.colorPrimaries
|
||||
colorSpace = info.colorSpace
|
||||
isHdr = info.isHdr
|
||||
hdrType = info.hdrType
|
||||
dvProfile = info.dvProfile
|
||||
} else if (isImage) {
|
||||
const info = await transcodeService.getImageInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
}
|
||||
const tmpDir = transcodeService.createTempDir('watermark-')
|
||||
|
||||
// Process image blocks if any
|
||||
const blockImagesMap = new Map<string, RenderBlockImageData>()
|
||||
const imageBlocks = (config.blocks || []).filter(
|
||||
(b) => b.type === 'image',
|
||||
) as WatermarkBlockImage[]
|
||||
try {
|
||||
const is3d = (asset.media as PrismaJson.MediaInfo | null)?.proxyType === '3d'
|
||||
const isVideo =
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('video/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video')
|
||||
const isImage =
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('image/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image')
|
||||
|
||||
for (const imgBlock of imageBlocks) {
|
||||
if (!imgBlock.imageAssetKey) continue
|
||||
try {
|
||||
const imgTmpPath = path.join(tmpDir, `block-${ulid()}`)
|
||||
await s3Service.downloadToFile(bucket, imgBlock.imageAssetKey, imgTmpPath)
|
||||
const buffer = fs.readFileSync(imgTmpPath)
|
||||
// Downscale to a bounded size and normalize to PNG so large logo assets
|
||||
// don't balloon the SVG/base64 payload.
|
||||
const processed = await transcodeService.downscaleImageToPng(
|
||||
buffer,
|
||||
MAX_BLOCK_IMAGE_DIMENSION,
|
||||
)
|
||||
blockImagesMap.set(imgBlock.imageAssetKey, {
|
||||
imageAssetKey: imgBlock.imageAssetKey,
|
||||
base64Data: processed.buffer.toString('base64'),
|
||||
mimeType: 'image/png',
|
||||
width: processed.width,
|
||||
height: processed.height,
|
||||
})
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ imageAssetKey: imgBlock.imageAssetKey, err },
|
||||
'Failed to load watermark block image',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const originalMedia = asset.media as PrismaJson.MediaInfo | null
|
||||
|
||||
const mediaInfo: PrismaJson.MediaInfo = {
|
||||
duration,
|
||||
filesize: 0,
|
||||
frames: totalFrames,
|
||||
proxyType: is3d ? '3d' : isVideo ? 'video' : 'image',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
poster: originalMedia?.poster,
|
||||
sprite: originalMedia?.sprite,
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth,
|
||||
originalHeight,
|
||||
duration,
|
||||
bitRate,
|
||||
videoBitRate,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
startTimecode,
|
||||
hasAudio,
|
||||
colorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
colorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
colorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
isHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
hdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
dvProfile: dvProfile ?? originalMedia?.metadata?.dvProfile,
|
||||
format: originalMedia?.metadata?.format ?? {},
|
||||
},
|
||||
original: {
|
||||
key: assetKey,
|
||||
filesizeInBytes: 0,
|
||||
codec: '',
|
||||
},
|
||||
}
|
||||
|
||||
if (isImage) {
|
||||
const originalTranscodes = originalMedia?.imageTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
for (let i = 0; i < originalTranscodes.length; i++) {
|
||||
const it = originalTranscodes[i]
|
||||
const targetWidth = it.width || originalWidth
|
||||
const targetHeight = it.height || originalHeight
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${targetWidth}x${targetHeight}.webp`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.compositeOverlayToWebpFile(
|
||||
rawFilePath,
|
||||
overlayPngBuffer,
|
||||
outFilePath,
|
||||
targetWidth,
|
||||
targetHeight,
|
||||
)
|
||||
|
||||
const stat = fs.statSync(outFilePath)
|
||||
totalSize += stat.size
|
||||
const outputKey = path.posix.join(path.posix.dirname(assetKey), outFileName)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
outputKey,
|
||||
Bun.file(outFilePath).stream(),
|
||||
stat.size,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
mediaInfo.imageTranscodes.push({
|
||||
key: outputKey,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
quality: it.quality ?? 90,
|
||||
format: it.format ?? 'webp',
|
||||
})
|
||||
}
|
||||
mediaInfo.filesize = totalSize
|
||||
} else if (isVideo || is3d) {
|
||||
const originalTranscodes = originalMedia?.videoTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
for (let i = 0; i < originalTranscodes.length; i++) {
|
||||
const vt = originalTranscodes[i]
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const resolution = vt.resolution || `${targetHeight}p`
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
const suffix = isVtHdr ? `${resolution}-hdr` : resolution
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-${i}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${suffix}.mp4`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: rawFilePath,
|
||||
outputFile: outFilePath,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
disableAudio: !hasAudio,
|
||||
overlayFile: overlayPngPath,
|
||||
hardwareAcceleration,
|
||||
sourceVideoBitrate,
|
||||
threads,
|
||||
hdr: isVtHdr,
|
||||
sourceIsHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
sourceHdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
sourceColorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
sourceColorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
streamIndex: originalMedia?.metadata?.videoStreamIndex,
|
||||
audioStreamIndex: originalMedia?.metadata?.audioStreamIndex,
|
||||
})
|
||||
|
||||
const stat = fs.statSync(outFilePath)
|
||||
totalSize += stat.size
|
||||
const outputKey = path.posix.join(path.posix.dirname(assetKey), outFileName)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
outputKey,
|
||||
Bun.file(outFilePath).stream(),
|
||||
stat.size,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
mediaInfo.videoTranscodes.push({
|
||||
key: outputKey,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
resolution,
|
||||
hdr: isVtHdr,
|
||||
if (!isVideo && !isImage && !is3d) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset ${params.assetId} is neither video nor image`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (is3d && mediaInfo.videoTranscodes.length > 0) {
|
||||
mediaInfo.videoPreview = {
|
||||
key: mediaInfo.videoTranscodes[0].key,
|
||||
width: mediaInfo.videoTranscodes[0].width,
|
||||
height: mediaInfo.videoTranscodes[0].height,
|
||||
resolution: mediaInfo.videoTranscodes[0].resolution,
|
||||
const inputKey = is3d
|
||||
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
|
||||
: assetKey
|
||||
|
||||
if (is3d && !inputKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
|
||||
await s3Service.downloadToFile(bucket, inputKey!, rawFilePath)
|
||||
|
||||
let originalWidth = 1920
|
||||
let originalHeight = 1080
|
||||
let duration = 0
|
||||
let bitRate = 0
|
||||
let videoBitRate: number | undefined
|
||||
let frameRate = 30
|
||||
let totalFrames = 0
|
||||
let startTimecode = '00:00:00:00'
|
||||
let hasAudio = false
|
||||
let sourceVideoBitrate: number | undefined
|
||||
let colorTransfer: string | undefined
|
||||
let colorPrimaries: string | undefined
|
||||
let colorSpace: string | undefined
|
||||
let isHdr: boolean | undefined
|
||||
let hdrType: PrismaJson.HdrType | undefined
|
||||
let dvProfile: number | undefined
|
||||
|
||||
if (isVideo || is3d) {
|
||||
const info = await transcodeService.getVideoInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
duration = info.duration
|
||||
bitRate = info.bitRate
|
||||
videoBitRate = info.videoBitRate
|
||||
frameRate = info.frameRate
|
||||
totalFrames = info.totalFrames
|
||||
startTimecode = info.startTimecode || '00:00:00:00'
|
||||
hasAudio = info.hasAudio
|
||||
sourceVideoBitrate = info.videoBitRate || info.bitRate
|
||||
colorTransfer = info.colorTransfer
|
||||
colorPrimaries = info.colorPrimaries
|
||||
colorSpace = info.colorSpace
|
||||
isHdr = info.isHdr
|
||||
hdrType = info.hdrType
|
||||
dvProfile = info.dvProfile
|
||||
} else if (isImage) {
|
||||
const info = await transcodeService.getImageInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
}
|
||||
|
||||
// Process image blocks if any
|
||||
const blockImagesMap = new Map<string, RenderBlockImageData>()
|
||||
const imageBlocks = (config.blocks || []).filter(
|
||||
(b) => b.type === 'image',
|
||||
) as WatermarkBlockImage[]
|
||||
|
||||
for (const imgBlock of imageBlocks) {
|
||||
if (!imgBlock.imageAssetKey) continue
|
||||
try {
|
||||
const imgTmpPath = path.join(tmpDir, `block-${ulid()}`)
|
||||
await s3Service.downloadToFile(bucket, imgBlock.imageAssetKey, imgTmpPath)
|
||||
const buffer = fs.readFileSync(imgTmpPath)
|
||||
// Downscale to a bounded size and normalize to PNG so large logo assets
|
||||
// don't balloon the SVG/base64 payload.
|
||||
const processed = await transcodeService.downscaleImageToPng(
|
||||
buffer,
|
||||
MAX_BLOCK_IMAGE_DIMENSION,
|
||||
)
|
||||
blockImagesMap.set(imgBlock.imageAssetKey, {
|
||||
imageAssetKey: imgBlock.imageAssetKey,
|
||||
base64Data: processed.buffer.toString('base64'),
|
||||
mimeType: 'image/png',
|
||||
width: processed.width,
|
||||
height: processed.height,
|
||||
})
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ imageAssetKey: imgBlock.imageAssetKey, err },
|
||||
'Failed to load watermark block image',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (originalMedia?.isHls && originalMedia?.hls?.resolutions?.length) {
|
||||
const hlsWatermarkDirKey = path.posix.join(
|
||||
path.posix.dirname(assetKey),
|
||||
`hls-watermark-${params.watermarkConfigId}`,
|
||||
)
|
||||
const masterKey = path.posix.join(hlsWatermarkDirKey, 'master.m3u8')
|
||||
const hlsTmpDir = path.join(tmpDir, `hls-watermark-${params.watermarkConfigId}`)
|
||||
fs.mkdirSync(hlsTmpDir, { recursive: true })
|
||||
const originalMedia = asset.media as PrismaJson.MediaInfo | null
|
||||
|
||||
const renditionSpecs: Array<{
|
||||
resolution: string
|
||||
width: number
|
||||
height: number
|
||||
bitrateBps: number
|
||||
isHdr?: boolean
|
||||
}> = []
|
||||
const hlsResolutions: PrismaJson.VideoTranscode[] = []
|
||||
const mediaInfo: PrismaJson.MediaInfo = {
|
||||
duration,
|
||||
filesize: 0,
|
||||
frames: totalFrames,
|
||||
proxyType: is3d ? '3d' : isVideo ? 'video' : 'image',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
poster: originalMedia?.poster,
|
||||
sprite: originalMedia?.sprite,
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth,
|
||||
originalHeight,
|
||||
duration,
|
||||
bitRate,
|
||||
videoBitRate,
|
||||
frameRate,
|
||||
totalFrames,
|
||||
startTimecode,
|
||||
hasAudio,
|
||||
colorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
colorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
colorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
isHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
hdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
dvProfile: dvProfile ?? originalMedia?.metadata?.dvProfile,
|
||||
format: originalMedia?.metadata?.format ?? {},
|
||||
},
|
||||
original: {
|
||||
key: assetKey,
|
||||
filesizeInBytes: 0,
|
||||
codec: '',
|
||||
},
|
||||
}
|
||||
|
||||
for (const vt of originalMedia.hls.resolutions) {
|
||||
const ladder = vt.resolution || `${vt.height}p`
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
if (isImage) {
|
||||
const originalTranscodes = originalMedia?.imageTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
for (let i = 0; i < originalTranscodes.length; i++) {
|
||||
const it = originalTranscodes[i]
|
||||
const targetWidth = it.width || originalWidth
|
||||
const targetHeight = it.height || originalHeight
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-hls-${ladder}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const ladderDir = path.join(hlsTmpDir, ladder)
|
||||
await transcodeService.transcodeHlsRendition({
|
||||
inputFile: rawFilePath,
|
||||
outputDir: ladderDir,
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${targetWidth}x${targetHeight}.webp`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.compositeOverlayToWebpFile(
|
||||
rawFilePath,
|
||||
overlayPngBuffer,
|
||||
outFilePath,
|
||||
targetWidth,
|
||||
targetHeight,
|
||||
)
|
||||
|
||||
const stat = fs.statSync(outFilePath)
|
||||
totalSize += stat.size
|
||||
const outputKey = path.posix.join(path.posix.dirname(assetKey), outFileName)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
outputKey,
|
||||
Bun.file(outFilePath).stream(),
|
||||
stat.size,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
mediaInfo.imageTranscodes.push({
|
||||
key: outputKey,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
quality: it.quality ?? 90,
|
||||
format: it.format ?? 'webp',
|
||||
})
|
||||
}
|
||||
mediaInfo.filesize = totalSize
|
||||
} else if (isVideo || is3d) {
|
||||
const originalTranscodes = originalMedia?.videoTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
for (let i = 0; i < originalTranscodes.length; i++) {
|
||||
const vt = originalTranscodes[i]
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const resolution = vt.resolution || `${targetHeight}p`
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
const suffix = isVtHdr ? `${resolution}-hdr` : resolution
|
||||
|
||||
const svgString = generateWatermarkSvg(config, targetWidth, targetHeight, blockImagesMap)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-${i}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${suffix}.mp4`
|
||||
const outFilePath = path.join(tmpDir, outFileName)
|
||||
|
||||
await transcodeService.transcodeVideo({
|
||||
inputFile: rawFilePath,
|
||||
outputFile: outFilePath,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
disableAudio: !hasAudio,
|
||||
overlayFile: overlayPngPath,
|
||||
frameRate,
|
||||
hardwareAcceleration,
|
||||
sourceVideoBitrate,
|
||||
threads,
|
||||
hdr: isVtHdr,
|
||||
disableAudio: !hasAudio,
|
||||
sourceIsHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
sourceHdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
@@ -474,82 +394,169 @@ export async function transcodeWatermarkMediaActivity(
|
||||
audioStreamIndex: originalMedia?.metadata?.audioStreamIndex,
|
||||
})
|
||||
|
||||
const targetBps = calculateEffectiveBitrateBps(
|
||||
targetHeight,
|
||||
targetWidth,
|
||||
sourceVideoBitrate,
|
||||
frameRate,
|
||||
const stat = fs.statSync(outFilePath)
|
||||
totalSize += stat.size
|
||||
const outputKey = path.posix.join(path.posix.dirname(assetKey), outFileName)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
outputKey,
|
||||
Bun.file(outFilePath).stream(),
|
||||
stat.size,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
renditionSpecs.push({
|
||||
resolution: ladder,
|
||||
mediaInfo.videoTranscodes.push({
|
||||
key: outputKey,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
bitrateBps: targetBps,
|
||||
isHdr: isVtHdr,
|
||||
})
|
||||
|
||||
const ladderFiles = fs.readdirSync(ladderDir)
|
||||
for (const file of ladderFiles) {
|
||||
const filePath = path.join(ladderDir, file)
|
||||
const stat = fs.statSync(filePath)
|
||||
totalSize += stat.size
|
||||
const contentType = file.endsWith('.m3u8')
|
||||
? 'application/vnd.apple.mpegurl'
|
||||
: file.endsWith('.m4s')
|
||||
? 'video/iso.segment'
|
||||
: 'video/mp4'
|
||||
const s3Key = path.posix.join(hlsWatermarkDirKey, ladder, file)
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
s3Key,
|
||||
Bun.file(filePath).stream(),
|
||||
stat.size,
|
||||
contentType,
|
||||
)
|
||||
}
|
||||
|
||||
hlsResolutions.push({
|
||||
key: path.posix.join(hlsWatermarkDirKey, ladder, 'index.m3u8'),
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
resolution: ladder,
|
||||
resolution,
|
||||
hdr: isVtHdr,
|
||||
})
|
||||
}
|
||||
|
||||
const masterM3u8Content = buildHlsMasterPlaylist(renditionSpecs)
|
||||
const masterM3u8Buffer = Buffer.from(masterM3u8Content, 'utf-8')
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
masterKey,
|
||||
masterM3u8Buffer,
|
||||
masterM3u8Buffer.length,
|
||||
'application/vnd.apple.mpegurl',
|
||||
)
|
||||
|
||||
mediaInfo.isHls = true
|
||||
mediaInfo.hls = {
|
||||
key: masterKey,
|
||||
resolutions: hlsResolutions,
|
||||
if (is3d && mediaInfo.videoTranscodes.length > 0) {
|
||||
mediaInfo.videoPreview = {
|
||||
key: mediaInfo.videoTranscodes[0].key,
|
||||
width: mediaInfo.videoTranscodes[0].width,
|
||||
height: mediaInfo.videoTranscodes[0].height,
|
||||
resolution: mediaInfo.videoTranscodes[0].resolution,
|
||||
}
|
||||
}
|
||||
|
||||
if (originalMedia?.isHls && originalMedia?.hls?.resolutions?.length) {
|
||||
const hlsWatermarkDirKey = path.posix.join(
|
||||
path.posix.dirname(assetKey),
|
||||
`hls-watermark-${params.watermarkConfigId}`,
|
||||
)
|
||||
const masterKey = path.posix.join(hlsWatermarkDirKey, 'master.m3u8')
|
||||
const hlsTmpDir = path.join(tmpDir, `hls-watermark-${params.watermarkConfigId}`)
|
||||
fs.mkdirSync(hlsTmpDir, { recursive: true })
|
||||
|
||||
const renditionSpecs: Array<{
|
||||
resolution: string
|
||||
width: number
|
||||
height: number
|
||||
bitrateBps: number
|
||||
isHdr?: boolean
|
||||
}> = []
|
||||
const hlsResolutions: PrismaJson.VideoTranscode[] = []
|
||||
|
||||
for (const vt of originalMedia.hls.resolutions) {
|
||||
const ladder = vt.resolution || `${vt.height}p`
|
||||
const targetWidth = vt.width || originalWidth
|
||||
const targetHeight = vt.height || originalHeight
|
||||
const isVtHdr = Boolean(vt.hdr)
|
||||
|
||||
const svgString = generateWatermarkSvg(
|
||||
config,
|
||||
targetWidth,
|
||||
targetHeight,
|
||||
blockImagesMap,
|
||||
)
|
||||
const overlayPngBuffer = await transcodeService.renderSvgToPng(svgString)
|
||||
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-hls-${ladder}.png`)
|
||||
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
|
||||
|
||||
const ladderDir = path.join(hlsTmpDir, ladder)
|
||||
await transcodeService.transcodeHlsRendition({
|
||||
inputFile: rawFilePath,
|
||||
outputDir: ladderDir,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
overlayFile: overlayPngPath,
|
||||
frameRate,
|
||||
hardwareAcceleration,
|
||||
sourceVideoBitrate,
|
||||
threads,
|
||||
hdr: isVtHdr,
|
||||
disableAudio: !hasAudio,
|
||||
sourceIsHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
sourceHdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
sourceColorTransfer: colorTransfer ?? originalMedia?.metadata?.colorTransfer,
|
||||
sourceColorPrimaries: colorPrimaries ?? originalMedia?.metadata?.colorPrimaries,
|
||||
sourceColorSpace: colorSpace ?? originalMedia?.metadata?.colorSpace,
|
||||
streamIndex: originalMedia?.metadata?.videoStreamIndex,
|
||||
audioStreamIndex: originalMedia?.metadata?.audioStreamIndex,
|
||||
})
|
||||
|
||||
const targetBps = calculateEffectiveBitrateBps(
|
||||
targetHeight,
|
||||
targetWidth,
|
||||
sourceVideoBitrate,
|
||||
frameRate,
|
||||
)
|
||||
|
||||
renditionSpecs.push({
|
||||
resolution: ladder,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
bitrateBps: targetBps,
|
||||
isHdr: isVtHdr,
|
||||
})
|
||||
|
||||
const ladderFiles = fs.readdirSync(ladderDir)
|
||||
for (const file of ladderFiles) {
|
||||
const filePath = path.join(ladderDir, file)
|
||||
const stat = fs.statSync(filePath)
|
||||
totalSize += stat.size
|
||||
const contentType = file.endsWith('.m3u8')
|
||||
? 'application/vnd.apple.mpegurl'
|
||||
: file.endsWith('.m4s')
|
||||
? 'video/iso.segment'
|
||||
: 'video/mp4'
|
||||
const s3Key = path.posix.join(hlsWatermarkDirKey, ladder, file)
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
s3Key,
|
||||
Bun.file(filePath).stream(),
|
||||
stat.size,
|
||||
contentType,
|
||||
)
|
||||
}
|
||||
|
||||
hlsResolutions.push({
|
||||
key: path.posix.join(hlsWatermarkDirKey, ladder, 'index.m3u8'),
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
resolution: ladder,
|
||||
hdr: isVtHdr,
|
||||
})
|
||||
}
|
||||
|
||||
const masterM3u8Content = buildHlsMasterPlaylist(renditionSpecs)
|
||||
const masterM3u8Buffer = Buffer.from(masterM3u8Content, 'utf-8')
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
masterKey,
|
||||
masterM3u8Buffer,
|
||||
masterM3u8Buffer.length,
|
||||
'application/vnd.apple.mpegurl',
|
||||
)
|
||||
|
||||
mediaInfo.isHls = true
|
||||
mediaInfo.hls = {
|
||||
key: masterKey,
|
||||
resolutions: hlsResolutions,
|
||||
}
|
||||
}
|
||||
|
||||
mediaInfo.filesize = totalSize
|
||||
}
|
||||
|
||||
mediaInfo.filesize = totalSize
|
||||
return mediaInfo
|
||||
} catch (err) {
|
||||
logger.error({ assetId: params.assetId, err }, 'Failed to generate watermark proxy')
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate watermark proxy: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
} finally {
|
||||
transcodeService.removeDir(tmpDir)
|
||||
}
|
||||
|
||||
return mediaInfo
|
||||
} catch (err) {
|
||||
logger.error({ assetId: params.assetId, err }, 'Failed to generate watermark proxy')
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate watermark proxy: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
} finally {
|
||||
transcodeService.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export interface CompleteWatermarkFileParams {
|
||||
assetId: string
|
||||
@@ -559,30 +566,31 @@ export interface CompleteWatermarkFileParams {
|
||||
shareLinkId?: string | null
|
||||
}
|
||||
|
||||
export async function completeWatermarkFileActivity(
|
||||
params: CompleteWatermarkFileParams,
|
||||
): Promise<void> {
|
||||
await prisma.watermarkFile.upsert({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_watermarkConfigId: {
|
||||
export const completeWatermarkFileActivity = defineStep(
|
||||
async function completeWatermarkFileActivity(params: CompleteWatermarkFileParams): Promise<void> {
|
||||
await prisma.watermarkFile.upsert({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_watermarkConfigId: {
|
||||
assetId: params.assetId,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
assetId: params.assetId,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
media: params.mediaInfo ?? undefined,
|
||||
status: params.status,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
assetId: params.assetId,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
media: params.mediaInfo ?? undefined,
|
||||
status: params.status,
|
||||
},
|
||||
update: {
|
||||
media: params.mediaInfo ?? undefined,
|
||||
status: params.status,
|
||||
},
|
||||
})
|
||||
update: {
|
||||
media: params.mediaInfo ?? undefined,
|
||||
status: params.status,
|
||||
},
|
||||
})
|
||||
|
||||
if (params.shareLinkId) {
|
||||
await watermarkService.checkAndUpdateShareLinkStatus(params.shareLinkId)
|
||||
}
|
||||
}
|
||||
if (params.shareLinkId) {
|
||||
await watermarkService.checkAndUpdateShareLinkStatus(params.shareLinkId)
|
||||
}
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { WorkflowTaskType } from '@shumai/db'
|
||||
import { registerActivities, registerWorkflow } from '@shumai/workflow-core'
|
||||
import * as transcodeActivities from './activities/transcode'
|
||||
import * as watermarkActivities from './activities/watermark'
|
||||
import { registerWorkflow } from '@shumai/workflow-core'
|
||||
import { transcodeVideoWorkflow } from './workflows/transcode-video'
|
||||
import { transcodeImageWorkflow } from './workflows/transcode-image'
|
||||
import { transcodePdfWorkflow } from './workflows/transcode-pdf'
|
||||
@@ -22,8 +20,6 @@ export function initTranscodeWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_watermark, transcodeWatermarkWorkflow)
|
||||
registerActivities(transcodeActivities)
|
||||
registerActivities(watermarkActivities)
|
||||
}
|
||||
|
||||
export * from './transcoder'
|
||||
|
||||
@@ -1,23 +1,31 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
executeActivity,
|
||||
getActivities,
|
||||
TaskQueueTranscode,
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import { cleanupTmpDirActivity } from '../activities/transcode'
|
||||
|
||||
export async function getWorkerQueueAndStartTask(task: WorkflowTask): Promise<string> {
|
||||
const { updateTaskStatusActivity } = getActivities()
|
||||
await executeActivity(TaskQueueTranscode, updateTaskStatusActivity, {
|
||||
export async function startTask(task: WorkflowTask): Promise<void> {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
return TaskQueueTranscode
|
||||
}
|
||||
|
||||
export async function fetchAssetWithKey(workerQueue: string, assetId: string) {
|
||||
const { getAssetActivity } = getActivities()
|
||||
const asset = await executeActivity(workerQueue, getAssetActivity, assetId)
|
||||
/**
|
||||
* @deprecated Use `startTask(task)` instead.
|
||||
*/
|
||||
export async function getWorkerQueueAndStartTask(task: WorkflowTask): Promise<string> {
|
||||
await startTask(task)
|
||||
return ''
|
||||
}
|
||||
|
||||
export async function fetchAssetWithKey(
|
||||
assetId: string,
|
||||
): Promise<{ asset: NonNullable<Awaited<ReturnType<typeof getAssetActivity>>>; key: string }> {
|
||||
const asset = await getAssetActivity(assetId)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key || asset.status === 'pending_purge') {
|
||||
throw ApplicationFailure.create({
|
||||
@@ -28,52 +36,38 @@ export async function fetchAssetWithKey(workerQueue: string, assetId: string) {
|
||||
return { asset, key }
|
||||
}
|
||||
|
||||
export async function completeTask(
|
||||
workerQueue: string,
|
||||
taskId: string,
|
||||
output?: Record<string, unknown>,
|
||||
) {
|
||||
const { updateTaskStatusActivity } = getActivities()
|
||||
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||
export async function completeTask(taskId: string, output?: Record<string, unknown>) {
|
||||
await updateTaskStatusActivity({
|
||||
taskId,
|
||||
status: 'completed',
|
||||
...(output ? { output } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export async function failTask(
|
||||
workerQueue: string,
|
||||
taskId: string,
|
||||
err: unknown,
|
||||
assetId?: string,
|
||||
) {
|
||||
const { updateTaskStatusActivity, updateAssetStatusActivity } = getActivities()
|
||||
if (workerQueue) {
|
||||
const errorMsg = err instanceof Error ? err.message : String(err)
|
||||
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||
taskId,
|
||||
status: 'failed',
|
||||
output: { error: errorMsg },
|
||||
})
|
||||
if (assetId) {
|
||||
try {
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
assetId,
|
||||
status: 'failed',
|
||||
error: errorMsg,
|
||||
})
|
||||
} catch (assetErr) {
|
||||
console.error('Failed to update asset status to failed:', assetErr)
|
||||
}
|
||||
export async function failTask(taskId: string, err: unknown, assetId?: string) {
|
||||
const errorMsg = err instanceof Error ? err.message : String(err)
|
||||
await updateTaskStatusActivity({
|
||||
taskId,
|
||||
status: 'failed',
|
||||
output: { error: errorMsg },
|
||||
})
|
||||
if (assetId) {
|
||||
try {
|
||||
await updateAssetStatusActivity({
|
||||
assetId,
|
||||
status: 'failed',
|
||||
error: errorMsg,
|
||||
})
|
||||
} catch (assetErr) {
|
||||
console.error('Failed to update asset status to failed:', assetErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanupTmpDir(workerQueue: string, tmpDir: string | undefined) {
|
||||
if (tmpDir && workerQueue) {
|
||||
const { cleanupTmpDirActivity } = getActivities()
|
||||
export async function cleanupTmpDir(tmpDir: string | undefined) {
|
||||
if (tmpDir) {
|
||||
try {
|
||||
await executeActivity(workerQueue, cleanupTmpDirActivity, { tmpDir })
|
||||
await cleanupTmpDirActivity({ tmpDir })
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup tmp dir:', cleanupErr)
|
||||
}
|
||||
|
||||
@@ -1,49 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { overlayImageAnnotationWorkflow } from './overlay-image-annotation'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
|
||||
import { overlayAnnotationsActivity } from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
overlayAnnotationsActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('overlayImageAnnotationWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
overlayAnnotationsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'overlayAnnotationsActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
overlayAnnotationsActivity: vi.mocked(overlayAnnotationsActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
})
|
||||
|
||||
it('should run image annotation overlay workflow successfully', async () => {
|
||||
@@ -78,7 +60,8 @@ describe('overlayImageAnnotationWorkflow', () => {
|
||||
media: {
|
||||
imageTranscodes: [{ key: 'image-transcoded.webp' }],
|
||||
},
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.overlayAnnotationsActivity.mockResolvedValue(
|
||||
'files/asset-image/annotations/ann1.webp',
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { getWorkerQueueAndStartTask, completeTask, failTask } from './common'
|
||||
import { ApplicationFailure, getAssetActivity } from '@shumai/workflow-core'
|
||||
import { overlayAnnotationsActivity } from '../activities/transcode'
|
||||
import { startTask, completeTask, failTask } from './common'
|
||||
|
||||
export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let workerQueue = ''
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload?.imageAnnotation) {
|
||||
@@ -16,8 +16,7 @@ export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promis
|
||||
})
|
||||
}
|
||||
|
||||
const { getAssetActivity, overlayAnnotationsActivity } = getActivities()
|
||||
const asset = await executeActivity(workerQueue, getAssetActivity, task.assetId)
|
||||
const asset = await getAssetActivity(task.assetId)
|
||||
let key = asset?.storageKey?.key
|
||||
if (asset?.media) {
|
||||
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
|
||||
@@ -33,16 +32,16 @@ export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promis
|
||||
})
|
||||
}
|
||||
|
||||
const keyWithOverlay = await executeActivity(workerQueue, overlayAnnotationsActivity, {
|
||||
const keyWithOverlay = await overlayAnnotationsActivity({
|
||||
assetKey: key,
|
||||
assetId: asset.id,
|
||||
annotations: payload.imageAnnotation.annotations,
|
||||
annotations: payload.imageAnnotation.annotations || [],
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id, { key: keyWithOverlay })
|
||||
await completeTask(task.id, { key: keyWithOverlay })
|
||||
} catch (err) {
|
||||
console.error(`overlayImageAnnotationWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err)
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderPdfPagesWorkflow } from './render-pdf-pages'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
|
||||
import { renderPdfPagesActivity } from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
renderPdfPagesActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('renderPdfPagesWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
renderPdfPagesActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'renderPdfPagesActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
renderPdfPagesActivity: vi.mocked(renderPdfPagesActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
})
|
||||
|
||||
it('should run renderPdfPagesWorkflow successfully', async () => {
|
||||
@@ -78,7 +60,8 @@ describe('renderPdfPagesWorkflow', () => {
|
||||
id: 'asset-pdf',
|
||||
storageKey: { key: 'doc.pdf' },
|
||||
mediaType: 'application/pdf',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.renderPdfPagesActivity.mockResolvedValue([
|
||||
{ key: 'pdf_pages/doc-page-1.webp', page: 1 },
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { getWorkerQueueAndStartTask, fetchAssetWithKey, completeTask, failTask } from './common'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { renderPdfPagesActivity } from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask } from './common'
|
||||
|
||||
export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let workerQueue = ''
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload?.pdfPages) {
|
||||
@@ -15,11 +15,10 @@ export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void>
|
||||
})
|
||||
}
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { renderPdfPagesActivity } = getActivities()
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
const pdfKey = (asset.media as PrismaJson.MediaInfo | null)?.pdfTranscode?.key || key
|
||||
|
||||
const pages = await executeActivity(workerQueue, renderPdfPagesActivity, {
|
||||
const pages = await renderPdfPagesActivity({
|
||||
taskId: task.id,
|
||||
assetKey: pdfKey,
|
||||
assetId: asset.id,
|
||||
@@ -29,10 +28,10 @@ export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void>
|
||||
annotations: payload.pdfPages.annotations,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id, { pages })
|
||||
await completeTask(task.id, { pages })
|
||||
} catch (err) {
|
||||
console.error(`renderPdfPagesWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err)
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { takeVideoScreenshotsWorkflow } from './take-video-screenshots'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
|
||||
import { takeScreenshotsActivity } from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
takeScreenshotsActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('takeVideoScreenshotsWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
takeScreenshotsActivity: Object.assign(vi.fn(), { _activityName: 'takeScreenshotsActivity' }),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
takeScreenshotsActivity: vi.mocked(takeScreenshotsActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
})
|
||||
|
||||
it('should run screenshot workflow successfully', async () => {
|
||||
@@ -77,7 +61,8 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
id: 'asset-video',
|
||||
storageKey: { key: 'video.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.takeScreenshotsActivity.mockResolvedValue([
|
||||
{ key: 'files/asset-video/screenshots/shot1.webp', timestamp: 0.0 },
|
||||
@@ -149,7 +134,8 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
{ key: 'proxy-360p.mp4', height: 360, width: 640 },
|
||||
],
|
||||
},
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.takeScreenshotsActivity.mockResolvedValue([
|
||||
{ key: 'files/asset-video-proxy/screenshots/shot1.webp', timestamp: 1.2345 },
|
||||
@@ -208,7 +194,8 @@ describe('takeVideoScreenshotsWorkflow', () => {
|
||||
{ key: 'proxy-720p.mp4', height: 720, width: 1280, hdr: false },
|
||||
],
|
||||
},
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.takeScreenshotsActivity.mockResolvedValue([
|
||||
{ key: 'files/asset-video-hdr/screenshots/shot1.webp', timestamp: 2.0 },
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { getWorkerQueueAndStartTask, fetchAssetWithKey, completeTask, failTask } from './common'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { takeScreenshotsActivity } from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask } from './common'
|
||||
|
||||
export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let workerQueue = ''
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload?.screenshot) {
|
||||
@@ -15,7 +15,7 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
})
|
||||
}
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
let targetKey = key
|
||||
if (asset?.media) {
|
||||
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
|
||||
@@ -34,9 +34,7 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
const { takeScreenshotsActivity } = getActivities()
|
||||
|
||||
const screenshots = await executeActivity(workerQueue, takeScreenshotsActivity, {
|
||||
const screenshots = await takeScreenshotsActivity({
|
||||
taskId: task.id,
|
||||
assetKey: targetKey,
|
||||
assetId: asset.id,
|
||||
@@ -47,10 +45,10 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
|
||||
annotations: payload.screenshot.annotations,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id, { screenshots })
|
||||
await completeTask(task.id, { screenshots })
|
||||
} catch (err) {
|
||||
console.error(`takeVideoScreenshotsWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err)
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,69 +1,63 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcode3dWorkflow } from './transcode-3d'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
downloadMediaToTmpActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
generate3dSpriteActivity,
|
||||
generate3dViewsActivity,
|
||||
updateAssetMediaActivity,
|
||||
cleanupTmpDirActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
start3dRenderActivity: vi.fn(),
|
||||
waitFor3dVideoRenderActivity: vi.fn(),
|
||||
generate3dSpriteActivity: vi.fn(),
|
||||
generate3dViewsActivity: vi.fn(),
|
||||
updateAssetMediaActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.fn(),
|
||||
createAutofillTaskIfEnabledActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcode3dWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
render3dModelActivity: Object.assign(vi.fn(), { _activityName: 'render3dModelActivity' }),
|
||||
start3dRenderActivity: Object.assign(vi.fn(), { _activityName: 'start3dRenderActivity' }),
|
||||
waitFor3dVideoRenderActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'waitFor3dVideoRenderActivity',
|
||||
}),
|
||||
generate3dSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generate3dSpriteActivity' }),
|
||||
generate3dViewsActivity: Object.assign(vi.fn(), { _activityName: 'generate3dViewsActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
start3dRenderActivity: vi.mocked(start3dRenderActivity),
|
||||
waitFor3dVideoRenderActivity: vi.mocked(waitFor3dVideoRenderActivity),
|
||||
generate3dSpriteActivity: vi.mocked(generate3dSpriteActivity),
|
||||
generate3dViewsActivity: vi.mocked(generate3dViewsActivity),
|
||||
updateAssetMediaActivity: vi.mocked(updateAssetMediaActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
cleanupTmpDirActivity: vi.mocked(cleanupTmpDirActivity),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.mocked(createEmbeddingTaskIfEnabledActivity),
|
||||
createAutofillTaskIfEnabledActivity: vi.mocked(createAutofillTaskIfEnabledActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/model.glb',
|
||||
tmpDir: '/tmp',
|
||||
@@ -102,7 +96,8 @@ describe('transcode3dWorkflow', () => {
|
||||
storageKey: { key: 'files/asset-3d/robot.glb' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
sizeByte: BigInt(1024),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.start3dRenderActivity.mockResolvedValue({
|
||||
renderTaskId: 'task_render_1',
|
||||
@@ -170,6 +165,7 @@ describe('transcode3dWorkflow', () => {
|
||||
expect(mockActivities.generate3dSpriteActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
videoKey: 'files/asset-3d/turntable.mp4',
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
spriteKey: 'files/asset-3d/sprite.webp',
|
||||
})
|
||||
@@ -177,6 +173,7 @@ describe('transcode3dWorkflow', () => {
|
||||
expect(mockActivities.generate3dViewsActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
videoKey: 'files/asset-3d/turntable.mp4',
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
viewsKey: 'files/asset-3d/views.webp',
|
||||
})
|
||||
@@ -248,7 +245,8 @@ describe('transcode3dWorkflow', () => {
|
||||
storageKey: { key: 'files/corrupt.glb' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
sizeByte: BigInt(512),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.start3dRenderActivity.mockRejectedValue(new Error('Renderer crashed'))
|
||||
|
||||
|
||||
@@ -1,42 +1,33 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import { updateAssetStatusActivity } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
downloadMediaToTmpActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
generate3dSpriteActivity,
|
||||
generate3dViewsActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
|
||||
|
||||
export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
generate3dSpriteActivity,
|
||||
generate3dViewsActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
const download = await downloadMediaToTmpActivity({
|
||||
assetKey: key,
|
||||
})
|
||||
const currentFilePath = download.filePath
|
||||
@@ -49,9 +40,9 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
const spriteKey = assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp'
|
||||
const viewsKey = assetDir ? `${assetDir}/views.webp` : 'views.webp'
|
||||
|
||||
const renderStart = await executeActivity(workerQueue, start3dRenderActivity, {
|
||||
const renderStart = await start3dRenderActivity({
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
teamId: task.teamId || '',
|
||||
assetId: asset.id,
|
||||
assetKey: key,
|
||||
filePath: currentFilePath,
|
||||
@@ -91,23 +82,24 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
},
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
const renderVideo = await executeActivity(workerQueue, waitFor3dVideoRenderActivity, {
|
||||
const renderVideo = await waitFor3dVideoRenderActivity({
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
teamId: task.teamId || '',
|
||||
assetKey: key,
|
||||
renderTaskId: renderStart.renderTaskId,
|
||||
targetVideoKey: videoKey,
|
||||
tmpDir,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, generate3dSpriteActivity, {
|
||||
await generate3dSpriteActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
videoKey,
|
||||
videoFilePath: renderVideo.videoFilePath,
|
||||
spriteKey,
|
||||
})
|
||||
@@ -119,9 +111,10 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
tileY: 10,
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, generate3dViewsActivity, {
|
||||
await generate3dViewsActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
videoKey,
|
||||
videoFilePath: renderVideo.videoFilePath,
|
||||
viewsKey,
|
||||
})
|
||||
@@ -136,7 +129,7 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
},
|
||||
]
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
@@ -157,35 +150,35 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
mediaInfo.finishedAt = new Date().toISOString()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcode3dWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
await cleanupTmpDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,64 +1,57 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodeImageWorkflow } from './transcode-image'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
downloadMediaToTmpActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeImageActivity,
|
||||
updateAssetMediaActivity,
|
||||
cleanupTmpDirActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
getMediaInfoActivity: vi.fn(),
|
||||
transcodeImageActivity: vi.fn(),
|
||||
updateAssetMediaActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.fn(),
|
||||
createAutofillTaskIfEnabledActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcodeImageWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }),
|
||||
transcodeImageActivity: Object.assign(vi.fn(), { _activityName: 'transcodeImageActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
getMediaInfoActivity: vi.mocked(getMediaInfoActivity),
|
||||
transcodeImageActivity: vi.mocked(transcodeImageActivity),
|
||||
updateAssetMediaActivity: vi.mocked(updateAssetMediaActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
cleanupTmpDirActivity: vi.mocked(cleanupTmpDirActivity),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.mocked(createEmbeddingTaskIfEnabledActivity),
|
||||
createAutofillTaskIfEnabledActivity: vi.mocked(createAutofillTaskIfEnabledActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/image.jpg',
|
||||
tmpDir: '/tmp',
|
||||
@@ -94,7 +87,8 @@ describe('transcodeImageWorkflow', () => {
|
||||
id: 'asset-image',
|
||||
storageKey: { key: 'image.jpg' },
|
||||
mediaType: 'image/jpeg',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
proxyType: 'image',
|
||||
@@ -111,17 +105,26 @@ describe('transcodeImageWorkflow', () => {
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.transcodeImageActivity.mockResolvedValue({
|
||||
key: 't.webp',
|
||||
width: 300,
|
||||
height: 300,
|
||||
quality: 80,
|
||||
format: 'webp',
|
||||
})
|
||||
|
||||
await transcodeImageWorkflow(task)
|
||||
|
||||
expect(mockActivities.getMediaInfoActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetKey: 'image.jpg',
|
||||
filePath: '/tmp/image.jpg',
|
||||
}),
|
||||
)
|
||||
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-image',
|
||||
status: AssetStatus.processing,
|
||||
@@ -185,7 +188,8 @@ describe('transcodeImageWorkflow', () => {
|
||||
id: 'asset-raw',
|
||||
storageKey: { key: 'photo.cr2' },
|
||||
mediaType: 'image/x-canon-cr2',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
// RAW file without usable preview returns originalWidth: 0, originalHeight: 0
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
@@ -203,7 +207,8 @@ describe('transcodeImageWorkflow', () => {
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
await transcodeImageWorkflow(task)
|
||||
|
||||
|
||||
@@ -1,47 +1,39 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import { updateAssetStatusActivity } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
downloadMediaToTmpActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeImageActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
|
||||
|
||||
export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeImageActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
const download = await downloadMediaToTmpActivity({
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const spec = task.payload?.transcode || {}
|
||||
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
|
||||
const mediaInfo = await getMediaInfoActivity({
|
||||
assetKey: key,
|
||||
filePath,
|
||||
assetId: asset.id,
|
||||
proxyType: 'image',
|
||||
@@ -65,7 +57,7 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
|
||||
quality: 90,
|
||||
format: 'webp',
|
||||
}
|
||||
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
const imageTranscode = await transcodeImageActivity({
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec,
|
||||
@@ -74,7 +66,7 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
|
||||
}
|
||||
|
||||
if (spec.thumbnail && hasUsablePreview) {
|
||||
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
const thumbTranscode = await transcodeImageActivity({
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec: { width: 300, height: 300, quality: 80, format: 'webp', isPreview: true },
|
||||
@@ -82,35 +74,35 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
|
||||
mediaInfo.thumbnail = thumbTranscode
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcodeImageWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
await cleanupTmpDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,67 +1,60 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodePdfWorkflow } from './transcode-pdf'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
downloadMediaToTmpActivity,
|
||||
generatePdfProxyActivity,
|
||||
getMediaInfoActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
cleanupTmpDirActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
generatePdfProxyActivity: vi.fn(),
|
||||
getMediaInfoActivity: vi.fn(),
|
||||
generateSpriteActivity: vi.fn(),
|
||||
updateAssetMediaActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.fn(),
|
||||
createAutofillTaskIfEnabledActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcodePdfWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }),
|
||||
generateSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generateSpriteActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
generatePdfProxyActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generatePdfProxyActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
getMediaInfoActivity: vi.mocked(getMediaInfoActivity),
|
||||
generateSpriteActivity: vi.mocked(generateSpriteActivity),
|
||||
updateAssetMediaActivity: vi.mocked(updateAssetMediaActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
generatePdfProxyActivity: vi.mocked(generatePdfProxyActivity),
|
||||
cleanupTmpDirActivity: vi.mocked(cleanupTmpDirActivity),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.mocked(createEmbeddingTaskIfEnabledActivity),
|
||||
createAutofillTaskIfEnabledActivity: vi.mocked(createAutofillTaskIfEnabledActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/doc.pdf',
|
||||
tmpDir: '/tmp',
|
||||
@@ -102,7 +95,8 @@ describe('transcodePdfWorkflow', () => {
|
||||
id: 'asset-pdf',
|
||||
storageKey: { key: 'document.pdf' },
|
||||
mediaType: 'application/pdf',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
proxyType: 'pdf',
|
||||
@@ -119,7 +113,8 @@ describe('transcodePdfWorkflow', () => {
|
||||
},
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.generateSpriteActivity.mockResolvedValue({
|
||||
sprite: { key: 'sprite.webp', frames: 100, tileX: 10, tileY: 10 },
|
||||
@@ -133,8 +128,17 @@ describe('transcodePdfWorkflow', () => {
|
||||
status: AssetStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.getMediaInfoActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'document.pdf',
|
||||
filePath: '/tmp/doc.pdf',
|
||||
assetId: 'asset-pdf',
|
||||
proxyType: 'pdf',
|
||||
mediaType: 'application/pdf',
|
||||
})
|
||||
|
||||
expect(mockActivities.generateSpriteActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'document.pdf',
|
||||
inputKey: 'document.pdf',
|
||||
filePath: '/tmp/doc.pdf',
|
||||
spriteSpec: expect.objectContaining({ key: 'sprite.webp' }),
|
||||
posterSpec: expect.objectContaining({ key: 'poster.webp' }),
|
||||
|
||||
@@ -1,47 +1,38 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import { updateAssetStatusActivity } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
downloadMediaToTmpActivity,
|
||||
generatePdfProxyActivity,
|
||||
getMediaInfoActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
|
||||
|
||||
export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
getMediaInfoActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
generatePdfProxyActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
const download = await downloadMediaToTmpActivity({
|
||||
assetKey: key,
|
||||
})
|
||||
let currentFilePath = download.filePath
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const pdfProxy = await executeActivity(workerQueue, generatePdfProxyActivity, {
|
||||
const pdfProxy = await generatePdfProxyActivity({
|
||||
teamId: task.teamId,
|
||||
assetId: asset.id,
|
||||
assetKey: key,
|
||||
@@ -53,7 +44,8 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
currentFilePath = pdfProxy.pdfFilePath
|
||||
|
||||
const spec = task.payload?.transcode || {}
|
||||
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
|
||||
const mediaInfo = await getMediaInfoActivity({
|
||||
assetKey: pdfProxy.pdfProxyKey,
|
||||
filePath: currentFilePath,
|
||||
assetId: asset.id,
|
||||
proxyType: 'pdf',
|
||||
@@ -83,8 +75,9 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
|
||||
}
|
||||
|
||||
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
|
||||
const spriteResult = await generateSpriteActivity({
|
||||
assetKey: key,
|
||||
inputKey: pdfProxy.pdfProxyKey,
|
||||
filePath: currentFilePath,
|
||||
spriteSpec,
|
||||
posterSpec,
|
||||
@@ -94,35 +87,35 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
mediaInfo.poster = spriteResult.poster
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcodePdfWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
await cleanupTmpDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,71 +1,77 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodeVideoWorkflow } from './transcode-video'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
getMediaInfoActivity,
|
||||
transcodeVideoActivity,
|
||||
transcodeHlsActivity,
|
||||
transcodeAudioActivity,
|
||||
transcodeImageActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
cleanupTmpDirActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
extractPosterActivity,
|
||||
type VideoActivityParams,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
getMediaInfoActivity: vi.fn(),
|
||||
transcodeVideoActivity: vi.fn(),
|
||||
transcodeHlsActivity: vi.fn(),
|
||||
transcodeAudioActivity: vi.fn(),
|
||||
transcodeImageActivity: vi.fn(),
|
||||
generateSpriteActivity: vi.fn(),
|
||||
updateAssetMediaActivity: vi.fn(),
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.fn(),
|
||||
createAutofillTaskIfEnabledActivity: vi.fn(),
|
||||
extractPosterActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcodeVideoWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getMediaInfoActivity: Object.assign(vi.fn(), { _activityName: 'getMediaInfoActivity' }),
|
||||
transcodeVideoActivity: Object.assign(vi.fn(), { _activityName: 'transcodeVideoActivity' }),
|
||||
transcodeHlsActivity: Object.assign(vi.fn(), { _activityName: 'transcodeHlsActivity' }),
|
||||
transcodeAudioActivity: Object.assign(vi.fn(), { _activityName: 'transcodeAudioActivity' }),
|
||||
transcodeImageActivity: Object.assign(vi.fn(), { _activityName: 'transcodeImageActivity' }),
|
||||
generateSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generateSpriteActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
extractPosterActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractPosterActivity',
|
||||
}),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to allow partial mock payloads in unit tests
|
||||
let mockActivities: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
getMediaInfoActivity: vi.mocked(getMediaInfoActivity),
|
||||
transcodeVideoActivity: vi.mocked(transcodeVideoActivity),
|
||||
transcodeHlsActivity: vi.mocked(transcodeHlsActivity),
|
||||
transcodeAudioActivity: vi.mocked(transcodeAudioActivity),
|
||||
transcodeImageActivity: vi.mocked(transcodeImageActivity),
|
||||
generateSpriteActivity: vi.mocked(generateSpriteActivity),
|
||||
updateAssetMediaActivity: vi.mocked(updateAssetMediaActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
cleanupTmpDirActivity: vi.mocked(cleanupTmpDirActivity),
|
||||
createEmbeddingTaskIfEnabledActivity: vi.mocked(createEmbeddingTaskIfEnabledActivity),
|
||||
createAutofillTaskIfEnabledActivity: vi.mocked(createAutofillTaskIfEnabledActivity),
|
||||
extractPosterActivity: vi.mocked(extractPosterActivity),
|
||||
}
|
||||
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/video.mp4',
|
||||
tmpDir: '/tmp',
|
||||
@@ -150,6 +156,16 @@ describe('transcodeVideoWorkflow', () => {
|
||||
}),
|
||||
}),
|
||||
})
|
||||
expect(mockActivities.getMediaInfoActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'video.mp4',
|
||||
assetId: 'asset-1',
|
||||
proxyType: 'video',
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
const getMediaInfoOrder = mockActivities.getMediaInfoActivity.mock.invocationCallOrder[0]
|
||||
const downloadOrder = mockActivities.downloadMediaToTmpActivity.mock.invocationCallOrder[0]
|
||||
expect(getMediaInfoOrder).toBeLessThan(downloadOrder)
|
||||
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
status: AssetStatus.processed,
|
||||
@@ -554,15 +570,17 @@ describe('transcodeVideoWorkflow', () => {
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(async (params) => {
|
||||
return {
|
||||
key: `files/asset-hdr/video-${params.videoSpec.resolution}${params.videoSpec.hdr ? '-hdr' : ''}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
})
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(
|
||||
async (params: VideoActivityParams) => {
|
||||
return {
|
||||
key: `files/asset-hdr/video-${params.videoSpec.resolution}${params.videoSpec.hdr ? '-hdr' : ''}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
@@ -659,15 +677,17 @@ describe('transcodeVideoWorkflow', () => {
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(async (params) => {
|
||||
return {
|
||||
key: `files/asset-sdr-source/video-${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
})
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(
|
||||
async (params: VideoActivityParams) => {
|
||||
return {
|
||||
key: `files/asset-sdr-source/video-${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
hdr: params.videoSpec.hdr,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
await transcodeVideoWorkflow(task)
|
||||
|
||||
@@ -846,12 +866,14 @@ describe('transcodeVideoWorkflow', () => {
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(async (params) => ({
|
||||
key: `files/asset-multi/${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
}))
|
||||
mockActivities.transcodeVideoActivity.mockImplementation(
|
||||
async (params: VideoActivityParams) => ({
|
||||
key: `files/asset-multi/${params.videoSpec.resolution}.mp4`,
|
||||
width: params.videoSpec.width,
|
||||
height: params.videoSpec.height,
|
||||
resolution: params.videoSpec.resolution,
|
||||
}),
|
||||
)
|
||||
|
||||
return transcodeVideoWorkflow(task).then(() => {
|
||||
// 180p preview + 1080p + 720p (2160p is skipped since > 1920)
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import { updateAssetStatusActivity } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
downloadMediaToTmpActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeVideoActivity,
|
||||
transcodeHlsActivity,
|
||||
transcodeAudioActivity,
|
||||
transcodeImageActivity,
|
||||
extractPosterActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} from '../activities/transcode'
|
||||
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
|
||||
import {
|
||||
getTargetVideoResolutions,
|
||||
getTargetHlsResolutions,
|
||||
@@ -16,44 +23,22 @@ import {
|
||||
|
||||
export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
getMediaInfoActivity,
|
||||
transcodeVideoActivity,
|
||||
transcodeHlsActivity,
|
||||
transcodeAudioActivity,
|
||||
transcodeImageActivity,
|
||||
extractPosterActivity,
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
const { asset, key } = await fetchAssetWithKey(task.assetId)
|
||||
|
||||
const spec = task.payload?.transcode || {}
|
||||
const proxyType = asset.mediaType?.startsWith('audio/') ? 'audio' : 'video'
|
||||
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
|
||||
filePath,
|
||||
const mediaInfo = await getMediaInfoActivity({
|
||||
assetKey: key,
|
||||
assetId: asset.id,
|
||||
proxyType,
|
||||
mediaType: asset.mediaType || '',
|
||||
@@ -73,7 +58,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
const posterSpec: PrismaJson.PosterInfo = {
|
||||
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
|
||||
}
|
||||
const posterResult = await executeActivity(workerQueue, extractPosterActivity, {
|
||||
const posterResult = await extractPosterActivity({
|
||||
assetKey: key,
|
||||
posterSpec,
|
||||
taskId: task.id,
|
||||
@@ -83,12 +68,18 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
streamIndex: mediaInfo.metadata?.videoStreamIndex,
|
||||
})
|
||||
mediaInfo.poster = posterResult.poster
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
}
|
||||
|
||||
const download = await downloadMediaToTmpActivity({
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
// Generate the sprite (and its poster fallback) before the expensive proxy transcodes so the
|
||||
// file list can show a poster/sprite preview while the asset is still processing.
|
||||
if ((spec.sprite || (spec.poster && !mediaInfo.poster)) && isVideo) {
|
||||
@@ -105,7 +96,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
|
||||
}
|
||||
|
||||
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
|
||||
const spriteResult = await generateSpriteActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -120,7 +111,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
mediaInfo.poster = spriteResult.poster
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
@@ -152,7 +143,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
hdr: isHdr,
|
||||
}
|
||||
|
||||
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
|
||||
const videoTranscode = await transcodeVideoActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -183,7 +174,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
hdr: isHdr,
|
||||
}
|
||||
|
||||
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
|
||||
const videoTranscode = await transcodeVideoActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -214,7 +205,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
metadata.originalHeight,
|
||||
)
|
||||
if (hlsLadders.length > 0) {
|
||||
const hlsResult = await executeActivity(workerQueue, transcodeHlsActivity, {
|
||||
const hlsResult = await transcodeHlsActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -222,6 +213,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
originalWidth: metadata.originalWidth,
|
||||
originalHeight: metadata.originalHeight,
|
||||
originalFps: metadata.frameRate,
|
||||
duration: metadata.duration,
|
||||
sourceVideoBitrate: metadata.videoBitRate || metadata.bitRate,
|
||||
hardwareAcceleration: spec.hardwareAcceleration,
|
||||
threads: spec.threads,
|
||||
@@ -242,7 +234,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
|
||||
const isAudio = mediaInfo.proxyType === 'audio'
|
||||
if (isAudio && metadata) {
|
||||
const audioTranscode = await executeActivity(workerQueue, transcodeAudioActivity, {
|
||||
const audioTranscode = await transcodeAudioActivity({
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
@@ -253,7 +245,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
}
|
||||
|
||||
if (spec.thumbnail && isVideo) {
|
||||
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
const thumbTranscode = await transcodeImageActivity({
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec: { width: 300, height: 300, quality: 80, format: 'webp', isPreview: true },
|
||||
@@ -261,35 +253,35 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
mediaInfo.thumbnail = thumbTranscode
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
await updateAssetMediaActivity({
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
await updateAssetStatusActivity({
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
await createAutofillTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcodeVideoWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
await cleanupTmpDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { getWorkerQueueAndStartTask, completeTask, failTask } from './common'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import {
|
||||
initWatermarkFileActivity,
|
||||
waitForWatermarkFileActivity,
|
||||
transcodeWatermarkMediaActivity,
|
||||
completeWatermarkFileActivity,
|
||||
} from '../activities/watermark'
|
||||
import { startTask, completeTask, failTask } from './common'
|
||||
|
||||
export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let workerQueue = ''
|
||||
const watermarkConfigId = task.payload?.watermark?.watermarkConfigId
|
||||
const shareLinkId = task.payload?.watermark?.shareLinkId
|
||||
|
||||
@@ -16,30 +21,23 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
}
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
await startTask(task)
|
||||
|
||||
const {
|
||||
initWatermarkFileActivity,
|
||||
waitForWatermarkFileActivity,
|
||||
transcodeWatermarkMediaActivity,
|
||||
completeWatermarkFileActivity,
|
||||
} = getActivities()
|
||||
|
||||
const initResult = await executeActivity(workerQueue, initWatermarkFileActivity, {
|
||||
const initResult = await initWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
})
|
||||
|
||||
if (initResult.action === 'completed') {
|
||||
if (shareLinkId) {
|
||||
await executeActivity(workerQueue, completeWatermarkFileActivity, {
|
||||
await completeWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
status: 'completed',
|
||||
shareLinkId,
|
||||
})
|
||||
}
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -51,21 +49,21 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
}
|
||||
|
||||
if (initResult.action === 'processing') {
|
||||
const waitResult = await executeActivity(workerQueue, waitForWatermarkFileActivity, {
|
||||
const waitResult = await waitForWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
})
|
||||
|
||||
if (waitResult.status === 'completed') {
|
||||
if (shareLinkId) {
|
||||
await executeActivity(workerQueue, completeWatermarkFileActivity, {
|
||||
await completeWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
status: 'completed',
|
||||
shareLinkId,
|
||||
})
|
||||
}
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -75,12 +73,12 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
})
|
||||
}
|
||||
|
||||
const mediaInfo = await executeActivity(workerQueue, transcodeWatermarkMediaActivity, {
|
||||
const mediaInfo = await transcodeWatermarkMediaActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, completeWatermarkFileActivity, {
|
||||
await completeWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
mediaInfo,
|
||||
@@ -88,12 +86,11 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
shareLinkId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
await completeTask(task.id)
|
||||
} catch (err) {
|
||||
if (workerQueue && watermarkConfigId) {
|
||||
const { completeWatermarkFileActivity } = getActivities()
|
||||
if (watermarkConfigId) {
|
||||
try {
|
||||
await executeActivity(workerQueue, completeWatermarkFileActivity, {
|
||||
await completeWatermarkFileActivity({
|
||||
assetId: task.assetId,
|
||||
watermarkConfigId,
|
||||
status: 'failed',
|
||||
@@ -103,7 +100,7 @@ export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<vo
|
||||
console.error('Failed to update watermark file status to failed:', e)
|
||||
}
|
||||
}
|
||||
await failTask(workerQueue, task.id, err)
|
||||
await failTask(task.id, err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,52 +1,45 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcodeMedia } from './transcode'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import {
|
||||
getAssetActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskStatusActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
downloadMediaToTmpActivity,
|
||||
getMediaInfoActivity,
|
||||
renderPdfPagesActivity,
|
||||
} from '../activities/transcode'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateAssetStatusActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/transcode', () => ({
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
getMediaInfoActivity: vi.fn(),
|
||||
renderPdfPagesActivity: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('transcodeMedia Fallback Dispatcher', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
renderPdfPagesActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'renderPdfPagesActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
|
||||
updateAssetStatusActivity: vi.mocked(updateAssetStatusActivity),
|
||||
getAssetActivity: vi.mocked(getAssetActivity),
|
||||
renderPdfPagesActivity: vi.mocked(renderPdfPagesActivity),
|
||||
downloadMediaToTmpActivity: vi.mocked(downloadMediaToTmpActivity),
|
||||
getMediaInfoActivity: vi.mocked(getMediaInfoActivity),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
})
|
||||
|
||||
it('should dispatch to pdfPages workflow when payload.pdfPages is present', async () => {
|
||||
@@ -79,7 +72,8 @@ describe('transcodeMedia Fallback Dispatcher', () => {
|
||||
id: 'asset-pdf',
|
||||
storageKey: { key: 'doc.pdf' },
|
||||
mediaType: 'application/pdf',
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
mockActivities.renderPdfPagesActivity.mockResolvedValue([])
|
||||
|
||||
|
||||
@@ -227,4 +227,38 @@ describe('FileViewerLeftSidebar', () => {
|
||||
expect(agentBadge?.getAttribute('title')).toBe('DrawBot')
|
||||
expect(agentBadge?.textContent).toBe('AI')
|
||||
})
|
||||
|
||||
it('renders thumbnail skeletons when isLoading is true and initialFiles is empty', () => {
|
||||
const { container } = render(
|
||||
<FileViewerLeftSidebar
|
||||
projectId="proj-1"
|
||||
currentAssetId="file-1"
|
||||
parentFolderId="folder-1"
|
||||
initialFiles={[]}
|
||||
initialNextCursor={undefined}
|
||||
isLoading={true}
|
||||
/>,
|
||||
)
|
||||
|
||||
const skeletons = container.querySelectorAll('[data-testid="carousel-skeleton-item"]')
|
||||
expect(skeletons.length).toBe(6)
|
||||
})
|
||||
|
||||
it('renders files instead of skeletons when isLoading is false', () => {
|
||||
const { container } = render(
|
||||
<FileViewerLeftSidebar
|
||||
projectId="proj-1"
|
||||
currentAssetId="file-1"
|
||||
parentFolderId="folder-1"
|
||||
initialFiles={mockFiles}
|
||||
initialNextCursor={undefined}
|
||||
isLoading={false}
|
||||
/>,
|
||||
)
|
||||
|
||||
const skeletons = container.querySelectorAll('[data-testid="carousel-skeleton-item"]')
|
||||
expect(skeletons.length).toBe(0)
|
||||
const links = container.querySelectorAll('[data-testid="carousel-link"]')
|
||||
expect(links.length).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,6 +6,7 @@ import { File, Loader2, AudioLines } from 'lucide-react'
|
||||
import type { FC } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { Skeleton } from '@/ui/components/ui/skeleton'
|
||||
|
||||
interface FileViewerLeftSidebarProps {
|
||||
projectId: string
|
||||
@@ -13,6 +14,7 @@ interface FileViewerLeftSidebarProps {
|
||||
parentFolderId: string
|
||||
initialFiles: AssetInfo[]
|
||||
initialNextCursor: string | undefined
|
||||
isLoading?: boolean
|
||||
}
|
||||
|
||||
export const CarouselFilePreview = ({ item }: { item: AssetInfo }) => {
|
||||
@@ -44,6 +46,7 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
|
||||
parentFolderId,
|
||||
initialFiles,
|
||||
initialNextCursor,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0,
|
||||
@@ -122,43 +125,51 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
|
||||
return (
|
||||
<div className="h-24 md:h-full w-full md:w-24 bg-gray-100 dark:bg-gray-950 flex flex-row md:flex-col flex-shrink-0 select-none">
|
||||
<div className="flex-1 overflow-x-auto overflow-y-hidden md:overflow-y-auto md:overflow-x-hidden px-4 md:px-0 py-2 md:py-4 flex flex-row md:flex-col items-center gap-3 no-scrollbar">
|
||||
{files.map((file) => {
|
||||
if (!file) return null
|
||||
const isActive = file.id === currentAssetId
|
||||
return (
|
||||
<div
|
||||
key={file.id}
|
||||
ref={file.id === currentAssetId ? activeItemRef : null}
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
<Link
|
||||
to="/projects/$projectId/files/$fileId"
|
||||
params={{ projectId, fileId: file.id }}
|
||||
search={{ version: undefined }}
|
||||
className={cn(
|
||||
'rounded-lg border overflow-hidden flex items-center justify-center transition-all bg-muted/30 block relative',
|
||||
isActive
|
||||
? 'w-[62px] h-[62px] opacity-100'
|
||||
: 'w-[52px] h-[52px] opacity-60 hover:opacity-100',
|
||||
)}
|
||||
>
|
||||
<CarouselFilePreview item={file} />
|
||||
{file.agent && (
|
||||
<span
|
||||
className="absolute top-1 right-1 z-10 pointer-events-none select-none rounded bg-black/60 px-1 py-0.5 text-[10px] font-medium leading-none text-white"
|
||||
title={file.agent.name}
|
||||
data-testid="carousel-agent-badge"
|
||||
{isLoading && files.length === 0
|
||||
? Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton
|
||||
key={i}
|
||||
className="w-[52px] h-[52px] rounded-lg shrink-0"
|
||||
data-testid="carousel-skeleton-item"
|
||||
/>
|
||||
))
|
||||
: files.map((file) => {
|
||||
if (!file) return null
|
||||
const isActive = file.id === currentAssetId
|
||||
return (
|
||||
<div
|
||||
key={file.id}
|
||||
ref={file.id === currentAssetId ? activeItemRef : null}
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
<Link
|
||||
to="/projects/$projectId/files/$fileId"
|
||||
params={{ projectId, fileId: file.id }}
|
||||
search={{ version: undefined }}
|
||||
className={cn(
|
||||
'rounded-lg border overflow-hidden flex items-center justify-center transition-all bg-muted/30 block relative',
|
||||
isActive
|
||||
? 'w-[62px] h-[62px] opacity-100'
|
||||
: 'w-[52px] h-[52px] opacity-60 hover:opacity-100',
|
||||
)}
|
||||
>
|
||||
AI
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<CarouselFilePreview item={file} />
|
||||
{file.agent && (
|
||||
<span
|
||||
className="absolute top-1 right-1 z-10 pointer-events-none select-none rounded bg-black/60 px-1 py-0.5 text-[10px] font-medium leading-none text-white"
|
||||
title={file.agent.name}
|
||||
data-testid="carousel-agent-badge"
|
||||
>
|
||||
AI
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Infinite Scroll Trigger */}
|
||||
{hasMore && (
|
||||
{!isLoading && hasMore && (
|
||||
<div
|
||||
ref={ref}
|
||||
className="px-2 md:px-0 py-2 md:py-4 flex justify-center items-center h-full md:w-full flex-shrink-0"
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React from 'react'
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
FileDetailSkeleton,
|
||||
MobileFileBrowserContentSkeleton,
|
||||
ProjectFolderSkeleton,
|
||||
} from './loading-skeletons'
|
||||
|
||||
describe('loading-skeletons', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('renders MobileFileBrowserContentSkeleton with card layout', () => {
|
||||
render(<MobileFileBrowserContentSkeleton />)
|
||||
const skeleton = screen.getByTestId('mobile-file-browser-loading-skeleton')
|
||||
expect(skeleton).toBeDefined()
|
||||
|
||||
// Assert cards with aspect-square are rendered
|
||||
const aspectSquareElements = skeleton.querySelectorAll('.aspect-square')
|
||||
expect(aspectSquareElements.length).toBe(3)
|
||||
})
|
||||
|
||||
it('renders ProjectFolderSkeleton containing desktop and mobile layouts', () => {
|
||||
const { container } = render(<ProjectFolderSkeleton />)
|
||||
expect(screen.getByTestId('mobile-file-browser-loading-skeleton')).toBeDefined()
|
||||
expect(container.querySelector('[data-testid="file-browser-loading-skeleton"]')).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders FileDetailSkeleton without top nav duplicate', () => {
|
||||
const { container } = render(<FileDetailSkeleton />)
|
||||
// Left sidebar carousel skeleton should exist on desktop
|
||||
const carouselCards = container.querySelectorAll('.w-24 .rounded-lg')
|
||||
expect(carouselCards.length).toBe(6)
|
||||
})
|
||||
})
|
||||
@@ -2,46 +2,38 @@ import { Skeleton } from '@/ui/components/ui/skeleton'
|
||||
|
||||
export function ProjectFolderSkeleton() {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background min-h-0">
|
||||
{/* Top navigation/breadcrumbs placeholder */}
|
||||
<div className="flex h-14 items-center justify-between border-b px-6 shrink-0">
|
||||
<div className="flex flex-1 overflow-hidden bg-background min-h-0">
|
||||
{/* Sidebar (Folder tree placeholder) */}
|
||||
<div className="w-[240px] border-r p-4 space-y-4 hidden md:block shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-4 rounded" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-8 w-8 rounded-md" />
|
||||
<Skeleton className="h-8 w-20 rounded-md" />
|
||||
<div className="pl-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 rounded" />
|
||||
<Skeleton className="h-3 w-28" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 rounded" />
|
||||
<Skeleton className="h-3 w-20" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 rounded" />
|
||||
<Skeleton className="h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* Sidebar (Folder tree placeholder) */}
|
||||
<div className="w-[240px] border-r p-4 space-y-4 hidden md:block shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-4 rounded" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
<div className="pl-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 rounded" />
|
||||
<Skeleton className="h-3 w-28" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 rounded" />
|
||||
<Skeleton className="h-3 w-20" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 rounded" />
|
||||
<Skeleton className="h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
{/* Main content area */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{/* Mobile: matches MobileFileBrowserContentSkeleton */}
|
||||
<div className="block md:hidden">
|
||||
<MobileFileBrowserContentSkeleton />
|
||||
</div>
|
||||
|
||||
{/* File Browser area */}
|
||||
<div className="flex-1 p-6 space-y-6 overflow-y-auto">
|
||||
{/* File browser toolbar */}
|
||||
{/* Desktop: file browser toolbar + card grid */}
|
||||
<div className="hidden md:block p-6 space-y-6">
|
||||
<div className="flex items-center justify-between border-b pb-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
@@ -53,27 +45,7 @@ export function ProjectFolderSkeleton() {
|
||||
<Skeleton className="h-8 w-32 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Cards Grid */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
|
||||
{Array.from({ length: 10 }).map((_, i) => (
|
||||
<div key={i} className="flex flex-col rounded-lg border bg-card p-3 space-y-3">
|
||||
<Skeleton className="aspect-square w-full rounded-md" />
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<div className="flex justify-between items-center">
|
||||
<Skeleton className="h-3 w-1/4" />
|
||||
<Skeleton className="h-3 w-1/3" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<FileBrowserContentSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -82,54 +54,69 @@ export function ProjectFolderSkeleton() {
|
||||
|
||||
export function FileDetailSkeleton() {
|
||||
return (
|
||||
<div className="h-screen flex flex-col bg-background">
|
||||
{/* Top navigation */}
|
||||
<div className="flex h-14 items-center justify-between border-b px-6 shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-16" />
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<Skeleton className="h-4 w-28" />
|
||||
<span className="text-muted-foreground">/</span>
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<div className="h-full flex-1 flex flex-col bg-background overflow-hidden">
|
||||
{/* Mobile-only view: matches MobileFileDetail */}
|
||||
<div className="flex md:hidden flex-col h-full w-full overflow-hidden">
|
||||
{/* Mobile File Header placeholder */}
|
||||
<div className="h-14 flex items-center justify-between border-b px-4 shrink-0 bg-card">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-8 w-8 rounded-full" />
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-7 w-7 rounded" />
|
||||
<Skeleton className="h-7 w-7 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-8 w-20 rounded" />
|
||||
{/* Media area placeholder */}
|
||||
<div className="flex-1 min-h-0 bg-muted/20 flex items-center justify-center relative p-4">
|
||||
<Skeleton className="w-full max-w-sm aspect-video rounded-lg" />
|
||||
</div>
|
||||
{/* Bottom sheet placeholder */}
|
||||
<div className="h-[45%] border-t bg-card rounded-t-xl p-4 flex flex-col gap-3 shrink-0">
|
||||
<div className="flex items-center justify-between border-b pb-2">
|
||||
<div className="flex gap-4">
|
||||
<Skeleton className="h-4 w-16" />
|
||||
<Skeleton className="h-4 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3 flex-1">
|
||||
<Skeleton className="h-12 w-full rounded" />
|
||||
<Skeleton className="h-12 w-full rounded" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* Left Pane (Version stack) */}
|
||||
<div className="w-[280px] border-r p-4 flex flex-col gap-4 shrink-0 hidden md:flex">
|
||||
<Skeleton className="h-5 w-24" />
|
||||
<div className="space-y-3 flex-1 overflow-y-auto">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div key={i} className="flex gap-3 p-2 rounded border">
|
||||
<Skeleton className="h-12 w-12 rounded bg-muted shrink-0" />
|
||||
<div className="space-y-2 flex-1">
|
||||
<Skeleton className="h-3 w-2/3" />
|
||||
<Skeleton className="h-2 w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{/* Desktop view: Left Carousel (96px) + Center Full-Bleed Viewer + Right Sidebar (360px) */}
|
||||
<div className="hidden md:flex h-full flex-1 overflow-hidden">
|
||||
{/* Left Carousel Skeleton (96px / w-24) */}
|
||||
<div className="w-24 bg-gray-100 dark:bg-gray-950 flex flex-col items-center py-4 gap-3 shrink-0 border-r">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="w-[52px] h-[52px] rounded-lg shrink-0" />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Center Pane (Viewer area) */}
|
||||
<div className="flex-1 bg-muted/20 p-6 flex flex-col justify-between relative min-w-0">
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<Skeleton className="w-full max-w-4xl aspect-video rounded-lg shadow-lg" />
|
||||
{/* Center Viewer Area */}
|
||||
<div className="flex-1 bg-muted/10 relative flex flex-col min-w-0 justify-between">
|
||||
<div className="flex-1 flex items-center justify-center p-8">
|
||||
<Skeleton className="w-full max-w-4xl aspect-video rounded-lg shadow-sm" />
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-between shrink-0">
|
||||
<div className="flex items-center gap-4">
|
||||
<Skeleton className="h-8 w-8 rounded-full" />
|
||||
<Skeleton className="h-4 w-32" />
|
||||
{/* Bottom video control bar placeholder */}
|
||||
<div className="h-12 border-t px-4 flex items-center justify-between bg-card shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="h-6 w-6 rounded" />
|
||||
<Skeleton className="h-4 w-20" />
|
||||
</div>
|
||||
<Skeleton className="h-3 flex-1 mx-6" />
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-6 w-6 rounded" />
|
||||
<Skeleton className="h-6 w-6 rounded" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Pane (Metadata and Comments) */}
|
||||
<div className="w-[360px] border-l p-4 flex flex-col gap-6 shrink-0 hidden lg:flex bg-card">
|
||||
{/* Right Sidebar Skeleton (360px) */}
|
||||
<div className="w-[360px] border-l p-4 hidden lg:flex flex-col gap-6 shrink-0 bg-card">
|
||||
{/* Metadata Section */}
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
@@ -214,18 +201,30 @@ export function FileBrowserContentSkeleton({
|
||||
export function MobileFileBrowserContentSkeleton() {
|
||||
return (
|
||||
<div
|
||||
className="p-3 space-y-3 max-w-lg mx-auto w-full"
|
||||
className="p-3 pb-24 max-w-lg mx-auto w-full"
|
||||
data-testid="mobile-file-browser-loading-skeleton"
|
||||
>
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div key={i} className="flex items-center gap-3 p-3 rounded-lg border bg-card">
|
||||
<Skeleton className="h-10 w-10 rounded-md shrink-0" />
|
||||
<div className="space-y-2 flex-1">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-3 w-1/3" />
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Skeleton className="h-4 w-4 rounded" />
|
||||
<Skeleton className="h-4 w-28 rounded" />
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 w-full">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex flex-col overflow-hidden rounded-xl border border-border bg-card m-1"
|
||||
>
|
||||
<Skeleton className="aspect-square w-full rounded-none" />
|
||||
<div className="p-3 space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<div className="flex justify-between items-center pt-1">
|
||||
<Skeleton className="h-3 w-1/3" />
|
||||
<Skeleton className="h-3 w-1/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React from 'react'
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { TopNav } from './top-nav'
|
||||
import { useTopNavStore } from '@/ui/stores/top-nav'
|
||||
|
||||
let mockPathname = '/projects/proj-1'
|
||||
let mockIsMobile = false
|
||||
|
||||
vi.mock('@tanstack/react-router', () => ({
|
||||
Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
useNavigate: () => vi.fn(),
|
||||
useRouterState: ({ select }: { select: (s: { location: { pathname: string } }) => string }) =>
|
||||
select({ location: { pathname: mockPathname } }),
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/hooks/use-mobile', () => ({
|
||||
useIsMobile: () => mockIsMobile,
|
||||
}))
|
||||
|
||||
describe('TopNav component', () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
useTopNavStore.getState().clearProjectState()
|
||||
mockPathname = '/projects/proj-1'
|
||||
mockIsMobile = false
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders TopNavBreadcrumbSkeleton on project routes when projectState is not loaded', () => {
|
||||
mockPathname = '/projects/proj-1'
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TopNav />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('top-nav-breadcrumb-skeleton')).toBeDefined()
|
||||
// Ensure center ShumaiLogo is NOT rendered
|
||||
expect(container.querySelector('.text-orange-600')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders TeamHeader with logo on non-project routes when projectState is not loaded', () => {
|
||||
mockPathname = '/teams/team-1'
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TopNav />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.queryByTestId('top-nav-breadcrumb-skeleton')).toBeNull()
|
||||
// TeamHeader contains ShumaiLogo with text-orange-600
|
||||
expect(container.querySelector('.text-orange-600')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('returns null on mobile when navigating file routes', () => {
|
||||
mockPathname = '/projects/proj-1/files/file-1'
|
||||
mockIsMobile = true
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TopNav />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,28 @@ import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useChatbotStore } from '@/ui/stores/chatbot'
|
||||
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
|
||||
import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||
import { Skeleton } from '@/ui/components/ui/skeleton'
|
||||
import { useRouterState } from '@tanstack/react-router'
|
||||
|
||||
export function TopNavBreadcrumbSkeleton() {
|
||||
return (
|
||||
<div
|
||||
className="flex h-14 flex-nowrap items-center justify-between gap-2 border-b border-border bg-card px-4 py-2 flex-shrink-0"
|
||||
data-testid="top-nav-breadcrumb-skeleton"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
|
||||
<Skeleton className="h-5 w-5 rounded md:hidden shrink-0 -ml-1 mr-1" />
|
||||
<Skeleton className="h-4 w-20 md:w-28 shrink-0" />
|
||||
<span className="text-muted-foreground text-xs">/</span>
|
||||
<Skeleton className="h-4 w-24 md:w-36 shrink-0" />
|
||||
</div>
|
||||
<div className="hidden md:flex items-center gap-2 shrink-0">
|
||||
<Skeleton className="h-8 w-20 rounded-md" />
|
||||
<Skeleton className="h-8 w-8 rounded-md" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function TopNav() {
|
||||
const { projectState } = useTopNavStore()
|
||||
@@ -12,12 +34,16 @@ export function TopNav() {
|
||||
const { isChatbotOpen, setIsChatbotOpen } = useChatbotStore()
|
||||
const hideAgent = useUserMetadataStore((s) => Boolean(s.metadata['appearance.hideAgent']))
|
||||
const isMobile = useIsMobile()
|
||||
const pathname = useRouterState({ select: (s) => s.location.pathname })
|
||||
|
||||
if (isMobile && projectState?.fileId) {
|
||||
if (isMobile && (projectState?.fileId || pathname.includes('/files/'))) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!projectState) {
|
||||
if (pathname.startsWith('/projects/')) {
|
||||
return <TopNavBreadcrumbSkeleton />
|
||||
}
|
||||
return <TeamHeader />
|
||||
}
|
||||
|
||||
|
||||
@@ -346,6 +346,15 @@ describe('CompareVideoPane', () => {
|
||||
'[data-testid="compare-video-area"] video',
|
||||
) as HTMLVideoElement
|
||||
expect(video.getAttribute('poster')).toBe('https://cdn.example.com/compare-poster.jpg')
|
||||
expect(video.className).toContain('blur-md')
|
||||
expect(video.className).toContain('scale-105')
|
||||
|
||||
act(() => {
|
||||
video.dispatchEvent(new Event('play'))
|
||||
})
|
||||
|
||||
expect(video.className).not.toContain('blur-md')
|
||||
expect(video.className).not.toContain('scale-105')
|
||||
})
|
||||
|
||||
it('shows loading spinner initially, transitions on loadeddata, and blocks play while loading', () => {
|
||||
|
||||
@@ -718,7 +718,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
|
||||
{/* Native Video Layer (Hardware-accelerated, full HDR EDR) */}
|
||||
{!isAudio && (
|
||||
<div
|
||||
className="absolute pointer-events-none"
|
||||
className="absolute pointer-events-none overflow-hidden"
|
||||
style={{
|
||||
left: 0,
|
||||
top: 0,
|
||||
@@ -730,7 +730,10 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
|
||||
>
|
||||
<video
|
||||
ref={videoRef}
|
||||
className="w-full h-full block object-contain pointer-events-none"
|
||||
className={cn(
|
||||
'w-full h-full block object-contain pointer-events-none',
|
||||
!hasStartedPlaying && file.preview?.thumbnailUrl && 'blur-md scale-105',
|
||||
)}
|
||||
playsInline
|
||||
preload="auto"
|
||||
poster={file.preview?.thumbnailUrl || undefined}
|
||||
|
||||
@@ -567,7 +567,7 @@ describe('VideoViewer', () => {
|
||||
expect(settingsButton?.textContent).not.toContain('1920p')
|
||||
})
|
||||
|
||||
it('sets poster on video element from file.preview.thumbnailUrl', () => {
|
||||
it('sets poster on video element from file.preview.thumbnailUrl and blurs until playback starts', () => {
|
||||
const videoWithThumb: AssetInfo = {
|
||||
id: 'video-thumb',
|
||||
name: 'thumb.mp4',
|
||||
@@ -597,6 +597,15 @@ describe('VideoViewer', () => {
|
||||
const { container } = render(<VideoViewer file={videoWithThumb} />)
|
||||
const video = container.querySelector('[data-testid="video-area"] video') as HTMLVideoElement
|
||||
expect(video.getAttribute('poster')).toBe('https://cdn.example.com/poster.jpg')
|
||||
expect(video.className).toContain('blur-md')
|
||||
expect(video.className).toContain('scale-105')
|
||||
|
||||
act(() => {
|
||||
video.dispatchEvent(new Event('play'))
|
||||
})
|
||||
|
||||
expect(video.className).not.toContain('blur-md')
|
||||
expect(video.className).not.toContain('scale-105')
|
||||
})
|
||||
|
||||
it('shows loading spinner initially and transitions to play overlay on loadeddata', () => {
|
||||
|
||||
@@ -1018,7 +1018,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
{/* Native Video Layer (Hardware-accelerated, full HDR EDR) */}
|
||||
{!isAudio && (
|
||||
<div
|
||||
className="absolute pointer-events-none"
|
||||
className="absolute pointer-events-none overflow-hidden"
|
||||
style={{
|
||||
left: 0,
|
||||
top: 0,
|
||||
@@ -1030,7 +1030,10 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
>
|
||||
<video
|
||||
ref={videoRef}
|
||||
className="w-full h-full block object-contain pointer-events-none"
|
||||
className={cn(
|
||||
'w-full h-full block object-contain pointer-events-none',
|
||||
!hasStartedPlaying && data.preview?.thumbnailUrl && 'blur-md scale-105',
|
||||
)}
|
||||
playsInline
|
||||
preload="auto"
|
||||
poster={data.preview?.thumbnailUrl || undefined}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./index.html",
|
||||
|
||||
@@ -85,7 +85,8 @@ function FileViewPage() {
|
||||
files: AssetInfo[]
|
||||
nextCursor?: string
|
||||
folderId?: string
|
||||
}>({ show: false, files: [], nextCursor: undefined, folderId: undefined })
|
||||
}>({ show: true, files: [], nextCursor: undefined, folderId: undefined })
|
||||
const [isCarouselLoading, setIsCarouselLoading] = useState(true)
|
||||
const $patchMetadata = client.api.files[':fileId'].metadata.$patch
|
||||
const { mutate: patchMetadata } = useMutation<
|
||||
InferResponseType<typeof $patchMetadata>,
|
||||
@@ -382,9 +383,11 @@ function FileViewPage() {
|
||||
useEffect(() => {
|
||||
if (!parentFolderId || !activeFileId) return
|
||||
if (carouselState.folderId === parentFolderId) {
|
||||
setIsCarouselLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setIsCarouselLoading(true)
|
||||
let isMounted = true
|
||||
|
||||
const fetchCarouselData = async () => {
|
||||
@@ -446,32 +449,30 @@ function FileViewPage() {
|
||||
}
|
||||
|
||||
if (isMounted) {
|
||||
if (found) {
|
||||
setCarouselState({
|
||||
show: true,
|
||||
files: allFiles,
|
||||
nextCursor: lastCursor,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
} else {
|
||||
setCarouselState({
|
||||
show: false,
|
||||
files: [],
|
||||
nextCursor: undefined,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
}
|
||||
const fallbackFiles = fileData ? [fileData as unknown as AssetInfo] : []
|
||||
const finalFiles = found ? allFiles : fallbackFiles
|
||||
setCarouselState({
|
||||
show: true,
|
||||
files: finalFiles,
|
||||
nextCursor: found ? lastCursor : undefined,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
if (isMounted) {
|
||||
const fallbackFiles = fileData ? [fileData as unknown as AssetInfo] : []
|
||||
setCarouselState({
|
||||
show: false,
|
||||
files: [],
|
||||
show: true,
|
||||
files: fallbackFiles,
|
||||
nextCursor: undefined,
|
||||
folderId: parentFolderId,
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
if (isMounted) {
|
||||
setIsCarouselLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,7 +481,7 @@ function FileViewPage() {
|
||||
return () => {
|
||||
isMounted = false
|
||||
}
|
||||
}, [parentFolderId, activeFileId, carouselState.folderId])
|
||||
}, [parentFolderId, activeFileId, carouselState.folderId, fileData])
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentTime(0)
|
||||
@@ -711,15 +712,14 @@ function FileViewPage() {
|
||||
annotations={annotations}
|
||||
startTime={startTime}
|
||||
>
|
||||
{carouselState.show && (
|
||||
<FileViewerLeftSidebar
|
||||
projectId={projectId}
|
||||
currentAssetId={activeFileId}
|
||||
parentFolderId={parentFolderId}
|
||||
initialFiles={carouselState.files}
|
||||
initialNextCursor={carouselState.nextCursor}
|
||||
/>
|
||||
)}
|
||||
<FileViewerLeftSidebar
|
||||
projectId={projectId}
|
||||
currentAssetId={activeFileId}
|
||||
parentFolderId={parentFolderId}
|
||||
initialFiles={carouselState.files}
|
||||
initialNextCursor={carouselState.nextCursor}
|
||||
isLoading={isCarouselLoading}
|
||||
/>
|
||||
</FileViewer>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
|
||||
|
||||
export const Route = createFileRoute('/projects/$projectId/files/$fileId')({
|
||||
pendingComponent: () => <FileDetailSkeleton />,
|
||||
validateSearch: (search: Record<string, unknown>) => {
|
||||
return {
|
||||
version: (search.version as string) || undefined,
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const APP_VERSION = '0.5.3'
|
||||
export const APP_VERSION = '0.6.0'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.5.3",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { WorkflowTaskStatus, AssetStatus, AssetType, Prisma } from '@shumai/db'
|
||||
import { defineStep } from '../workflow-utils'
|
||||
|
||||
export async function getAssetStatusActivity(params: {
|
||||
export const getAssetStatusActivity = defineStep(async function getAssetStatusActivity(params: {
|
||||
assetId: string
|
||||
}): Promise<AssetStatus | null> {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
@@ -9,9 +10,9 @@ export async function getAssetStatusActivity(params: {
|
||||
select: { status: true },
|
||||
})
|
||||
return asset?.status || null
|
||||
}
|
||||
})
|
||||
|
||||
export async function getAssetActivity(assetId: string) {
|
||||
export const getAssetActivity = defineStep(async function getAssetActivity(assetId: string) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
@@ -53,7 +54,7 @@ export async function getAssetActivity(assetId: string) {
|
||||
...asset,
|
||||
sizeByte: Number(asset.sizeByte),
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export interface UpdateTaskStatusParams {
|
||||
taskId: string
|
||||
@@ -61,15 +62,18 @@ export interface UpdateTaskStatusParams {
|
||||
output?: unknown
|
||||
}
|
||||
|
||||
export async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output as Prisma.InputJsonValue,
|
||||
},
|
||||
})
|
||||
}
|
||||
export const updateTaskStatusActivity = defineStep(
|
||||
async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output as PrismaJson.WorkflowTaskOutput,
|
||||
},
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface UpdateAssetStatusParams {
|
||||
assetId: string
|
||||
@@ -77,36 +81,39 @@ export interface UpdateAssetStatusParams {
|
||||
error?: string
|
||||
}
|
||||
|
||||
export async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
if (params.status === AssetStatus.failed) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
select: { media: true, status: true },
|
||||
})
|
||||
// Never overwrite an asset that has already completed media processing
|
||||
if (asset?.status === AssetStatus.processed) {
|
||||
export const updateAssetStatusActivity = defineStep(
|
||||
async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
if (params.status === AssetStatus.failed) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
select: { media: true, status: true },
|
||||
})
|
||||
// Never overwrite an asset that has already completed media processing
|
||||
if (asset?.status === AssetStatus.processed) {
|
||||
return
|
||||
}
|
||||
const data: Prisma.AssetUpdateInput = { status: params.status }
|
||||
if (params.error !== undefined) {
|
||||
const existingMedia = (asset?.media as PrismaJson.MediaInfo | null) || {}
|
||||
data.media = {
|
||||
...existingMedia,
|
||||
error: params.error.slice(0, 500),
|
||||
} as PrismaJson.MediaInfo
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false, status: { not: AssetStatus.processed } },
|
||||
data,
|
||||
})
|
||||
return
|
||||
}
|
||||
const data: Prisma.AssetUpdateInput = { status: params.status }
|
||||
if (params.error !== undefined) {
|
||||
const existingMedia = (asset?.media as PrismaJson.MediaInfo | null) || {}
|
||||
data.media = {
|
||||
...existingMedia,
|
||||
error: params.error.slice(0, 500),
|
||||
} as PrismaJson.MediaInfo
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false, status: { not: AssetStatus.processed } },
|
||||
data,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false },
|
||||
data: { status: params.status },
|
||||
})
|
||||
}
|
||||
await prisma.asset.updateMany({
|
||||
where: { id: params.assetId, isDeleted: false },
|
||||
data: { status: params.status },
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
export interface UpdateTaskUsageParams {
|
||||
taskId: string
|
||||
@@ -115,7 +122,9 @@ export interface UpdateTaskUsageParams {
|
||||
model: string
|
||||
}
|
||||
|
||||
export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Promise<void> {
|
||||
export const updateTaskUsageActivity = defineStep(async function updateTaskUsageActivity(
|
||||
params: UpdateTaskUsageParams,
|
||||
): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
@@ -124,7 +133,7 @@ export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Pr
|
||||
model: params.model,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export interface UpdateWorkflowTaskParams {
|
||||
taskId: string
|
||||
@@ -136,16 +145,21 @@ export interface UpdateWorkflowTaskParams {
|
||||
model?: string | null
|
||||
}
|
||||
|
||||
export async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
...(params.status !== undefined ? { status: params.status } : {}),
|
||||
...(params.heartbeat ? { heartbeat: new Date() } : {}),
|
||||
...(params.output !== undefined ? { output: params.output as Prisma.InputJsonValue } : {}),
|
||||
...(params.inputTokens !== undefined ? { inputTokens: params.inputTokens } : {}),
|
||||
...(params.outputTokens !== undefined ? { outputTokens: params.outputTokens } : {}),
|
||||
...(params.model !== undefined ? { model: params.model } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
export const updateWorkflowTaskActivity = defineStep(
|
||||
async function updateWorkflowTaskActivity(params: UpdateWorkflowTaskParams): Promise<void> {
|
||||
await prisma.workflowTask.updateMany({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
...(params.status !== undefined ? { status: params.status } : {}),
|
||||
...(params.heartbeat ? { heartbeat: new Date() } : {}),
|
||||
...(params.output !== undefined
|
||||
? { output: params.output as PrismaJson.WorkflowTaskOutput }
|
||||
: {}),
|
||||
...(params.inputTokens !== undefined ? { inputTokens: params.inputTokens } : {}),
|
||||
...(params.outputTokens !== undefined ? { outputTokens: params.outputTokens } : {}),
|
||||
...(params.model !== undefined ? { model: params.model } : {}),
|
||||
},
|
||||
})
|
||||
},
|
||||
{ runOnCancel: true },
|
||||
)
|
||||
|
||||
@@ -133,18 +133,8 @@ describe('DbosExecutor Tests', () => {
|
||||
})
|
||||
|
||||
it('should only update queues the worker listens to or configures, leaving unmanaged queues untouched', async () => {
|
||||
// Step 1: Agent worker sets agent concurrency to 1
|
||||
process.env.CONCURRENCY_AGENT = '1'
|
||||
const agentWorker = new DbosExecutor([TaskQueueAgent])
|
||||
agentWorker.start()
|
||||
await agentWorker.ensureLaunched()
|
||||
const registerQueueSpy = vi.spyOn(DBOS, 'registerQueue')
|
||||
|
||||
const agentQueue = await DBOS.retrieveQueue(TaskQueueAgent)
|
||||
expect(agentQueue?.workerConcurrency).toBe(1)
|
||||
await agentWorker.shutdown()
|
||||
|
||||
// Step 2: Dedicated transcode worker starts with transcode concurrency = 3 and unconfigured agent env
|
||||
delete process.env.CONCURRENCY_AGENT
|
||||
process.env.CONCURRENCY_TRANSCODE = '3'
|
||||
const transcodeWorker = new DbosExecutor([TaskQueueTranscode])
|
||||
try {
|
||||
@@ -152,12 +142,15 @@ describe('DbosExecutor Tests', () => {
|
||||
await transcodeWorker.ensureLaunched()
|
||||
|
||||
const transcodeQueue = await DBOS.retrieveQueue(TaskQueueTranscode)
|
||||
const agentQueueAfter = await DBOS.retrieveQueue(TaskQueueAgent)
|
||||
|
||||
expect(transcodeQueue?.workerConcurrency).toBe(3)
|
||||
// Agent queue should still be 1, NOT overwritten by default 5
|
||||
expect(agentQueueAfter?.workerConcurrency).toBe(1)
|
||||
|
||||
// transcodeWorker should only have registered TaskQueueTranscode, not unmanaged queues like TaskQueueAgent
|
||||
const registeredQueueNames = registerQueueSpy.mock.calls.map((call) => call[0])
|
||||
expect(registeredQueueNames).toContain(TaskQueueTranscode)
|
||||
expect(registeredQueueNames).not.toContain(TaskQueueAgent)
|
||||
} finally {
|
||||
registerQueueSpy.mockRestore()
|
||||
delete process.env.CONCURRENCY_TRANSCODE
|
||||
await transcodeWorker.shutdown()
|
||||
}
|
||||
})
|
||||
@@ -255,13 +248,18 @@ describe('DbosExecutor Tests', () => {
|
||||
await restartedWorker.ensureLaunched()
|
||||
|
||||
// Verify that on restart with the SAME executor ID, DBOS startup recovery DOES re-enqueue it
|
||||
const rowsAfterRestart = await prisma.$queryRawUnsafe<
|
||||
Array<{ status: string; executorId: string }>
|
||||
>(
|
||||
'SELECT status, executor_id AS "executorId" FROM dbos.workflow_status WHERE workflow_uuid = $1',
|
||||
taskUuid,
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
const rowsAfterRestart = await prisma.$queryRawUnsafe<
|
||||
Array<{ status: string; executorId: string }>
|
||||
>(
|
||||
'SELECT status, executor_id AS "executorId" FROM dbos.workflow_status WHERE workflow_uuid = $1',
|
||||
taskUuid,
|
||||
)
|
||||
expect(rowsAfterRestart[0]?.status).toBe('ENQUEUED')
|
||||
},
|
||||
{ timeout: 5000, interval: 50 },
|
||||
)
|
||||
expect(rowsAfterRestart[0].status).toBe('ENQUEUED')
|
||||
|
||||
await restartedWorker.shutdown()
|
||||
} finally {
|
||||
@@ -390,4 +388,89 @@ describe('DbosExecutor Tests', () => {
|
||||
expect(mockClient.enqueue).toHaveBeenCalled()
|
||||
}, 15000)
|
||||
})
|
||||
|
||||
describe('Workflow events and conflict handling', () => {
|
||||
it('should emit workflowStarted and workflowFinished events during execution', async () => {
|
||||
let startedTask: WorkflowTask | null = null
|
||||
let finishedPayload: { taskId: string; success: boolean } | null = null
|
||||
|
||||
executor.on('workflowStarted', (task) => {
|
||||
startedTask = task
|
||||
})
|
||||
executor.on('workflowFinished', (payload) => {
|
||||
finishedPayload = payload
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const wrapper = (executor as any).createDbosWorkflowWrapper('test-events-workflow')
|
||||
const { registerWorkflow } = await import('./dbos-executor')
|
||||
registerWorkflow('test-events-workflow', async () => {
|
||||
// do work
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
id: 'test-events-task',
|
||||
assetId: 'asset-events',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await wrapper(task)
|
||||
|
||||
expect(startedTask).toBeDefined()
|
||||
expect((startedTask as WorkflowTask | null)?.id).toBe('test-events-task')
|
||||
expect(finishedPayload).toBeDefined()
|
||||
expect((finishedPayload as { taskId: string; success: boolean } | null)?.taskId).toBe(
|
||||
'test-events-task',
|
||||
)
|
||||
expect((finishedPayload as { taskId: string; success: boolean } | null)?.success).toBe(true)
|
||||
})
|
||||
|
||||
it('should handle DBOSWorkflowConflictError without marking task failed', async () => {
|
||||
const { DBOSWorkflowConflictError: DbosWorkflowConflictError } =
|
||||
await import('@dbos-inc/dbos-sdk')
|
||||
const { registerWorkflow } = await import('./dbos-executor')
|
||||
|
||||
registerWorkflow('test-conflict-workflow', async () => {
|
||||
throw new DbosWorkflowConflictError('test-conflict-task')
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const wrapper = (executor as any).createDbosWorkflowWrapper('test-conflict-workflow')
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
id: 'test-conflict-task',
|
||||
assetId: 'asset-conflict',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(wrapper(task)).rejects.toThrow('is no longer owned by this execution')
|
||||
|
||||
const updatedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: 'test-conflict-task' },
|
||||
})
|
||||
// Task should NOT be marked as failed!
|
||||
expect(updatedTask?.status).not.toBe(WorkflowTaskStatus.failed)
|
||||
})
|
||||
|
||||
it('should pass workflowCompletionTimeoutMs to DBOS.shutdown', async () => {
|
||||
const shutdownSpy = vi.spyOn(DBOS, 'shutdown').mockResolvedValue(undefined)
|
||||
const isInitSpy = vi.spyOn(DBOS, 'isInitialized').mockReturnValue(true)
|
||||
|
||||
await executor.shutdown({ workflowCompletionTimeoutMs: 290000 })
|
||||
|
||||
expect(shutdownSpy).toHaveBeenCalledWith({
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS SDK parameter name
|
||||
workflowCompletionTimeoutMS: 290000,
|
||||
})
|
||||
|
||||
shutdownSpy.mockRestore()
|
||||
isInitSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import EventEmitter from 'node:events'
|
||||
import os from 'node:os'
|
||||
import { DBOS, DBOSClient } from '@dbos-inc/dbos-sdk'
|
||||
import { DBOS, DBOSClient, DBOSWorkflowConflictError } from '@dbos-inc/dbos-sdk'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { prisma, WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import type { Executor } from './executor'
|
||||
import { getRegisteredWorkflows } from './registry'
|
||||
import {
|
||||
getConcurrencyLimit,
|
||||
registerLocalTaskAbortController,
|
||||
@@ -14,6 +13,33 @@ import {
|
||||
unregisterLocalTaskAbortController,
|
||||
} from './workflow-utils'
|
||||
|
||||
export function isWorkflowConflictError(err: unknown): boolean {
|
||||
if (err instanceof DBOSWorkflowConflictError) return true
|
||||
if (
|
||||
err &&
|
||||
typeof err === 'object' &&
|
||||
'dbosErrorCode' in err &&
|
||||
(err as { dbosErrorCode: unknown }).dbosErrorCode === 5
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (err instanceof Error && err.message.includes('is no longer owned by this execution')) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export type WorkflowFn = (task: WorkflowTask) => Promise<void>
|
||||
const workflowRegistry = new Map<string, WorkflowFn>()
|
||||
|
||||
export function registerWorkflow(type: string, fn: WorkflowFn): void {
|
||||
workflowRegistry.set(type, fn)
|
||||
}
|
||||
|
||||
export function getRegisteredWorkflows(): Map<string, WorkflowFn> {
|
||||
return workflowRegistry
|
||||
}
|
||||
|
||||
export function getDbosDatabaseUrl(rawUrl?: string): string {
|
||||
const urlStr =
|
||||
rawUrl || process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:5432/shumai'
|
||||
@@ -54,7 +80,7 @@ export function getQueueForTaskType(type: string | null | undefined): string {
|
||||
let dbosMigrationsRan = false
|
||||
const registeredDbosWorkflowNames = new Set<string>()
|
||||
|
||||
export class DbosExecutor implements Executor {
|
||||
export class DbosExecutor extends EventEmitter {
|
||||
private launchPromise: Promise<void> | null = null
|
||||
private started = false
|
||||
private client: DBOSClient | null = null
|
||||
@@ -65,6 +91,7 @@ export class DbosExecutor implements Executor {
|
||||
private instanceSuffix = Math.random().toString(36).slice(2, 8)
|
||||
|
||||
constructor(listenQueues?: string[], executorId?: string) {
|
||||
super()
|
||||
if (listenQueues) {
|
||||
this.listenQueues = listenQueues
|
||||
}
|
||||
@@ -107,6 +134,7 @@ export class DbosExecutor implements Executor {
|
||||
if (!fn) {
|
||||
throw new Error(`No workflow registered for type: ${type}`)
|
||||
}
|
||||
this.emit('workflowStarted', task)
|
||||
// Mark task as processing and start heartbeat
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
@@ -142,11 +170,20 @@ export class DbosExecutor implements Executor {
|
||||
const abortController = new AbortController()
|
||||
registerLocalTaskAbortController(task.id, abortController)
|
||||
|
||||
let workflowError: unknown
|
||||
try {
|
||||
await runInLocalTaskContext({ taskId: task.id, abortController }, async () => {
|
||||
await fn(task)
|
||||
})
|
||||
} catch (err) {
|
||||
workflowError = err
|
||||
if (isWorkflowConflictError(err)) {
|
||||
logger.warn(
|
||||
{ taskId: task.id, type, err },
|
||||
'[DbosExecutor] Workflow execution superseded (ownership lost or conflict). Skipping marking task as failed.',
|
||||
)
|
||||
throw err
|
||||
}
|
||||
logger.error({ taskId: task.id, type, err }, `[DbosExecutor] Error in workflow ${type}`)
|
||||
try {
|
||||
await prisma.workflowTask.updateMany({
|
||||
@@ -167,6 +204,12 @@ export class DbosExecutor implements Executor {
|
||||
clearInterval(heartbeatInterval)
|
||||
this.heartbeatIntervals.delete(task.id)
|
||||
unregisterLocalTaskAbortController(task.id)
|
||||
this.emit('workflowFinished', {
|
||||
taskId: task.id,
|
||||
type,
|
||||
success: !workflowError,
|
||||
error: workflowError,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -357,14 +400,17 @@ export class DbosExecutor implements Executor {
|
||||
close(): void {
|
||||
this.started = false
|
||||
this.waitForPendingSubmissions().catch(() => {})
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
const cleanupResources = () => {
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
}
|
||||
}
|
||||
|
||||
if (DBOS.isInitialized()) {
|
||||
DBOS.shutdown()
|
||||
.then(() => {
|
||||
@@ -373,23 +419,43 @@ export class DbosExecutor implements Executor {
|
||||
.catch((err) => {
|
||||
logger.warn({ err }, '[DbosExecutor] Error during DBOS shutdown')
|
||||
})
|
||||
.finally(cleanupResources)
|
||||
} else {
|
||||
cleanupResources()
|
||||
}
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
async shutdown(options?: { workflowCompletionTimeoutMs?: number }): Promise<void> {
|
||||
this.started = false
|
||||
await this.waitForPendingSubmissions()
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
await this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
}
|
||||
if (DBOS.isInitialized()) {
|
||||
await DBOS.shutdown()
|
||||
this.launchPromise = null
|
||||
|
||||
const timeoutMs =
|
||||
options?.workflowCompletionTimeoutMs ??
|
||||
(process.env.SHUMAI_WORKER_DRAIN_TIMEOUT_MS
|
||||
? parseInt(process.env.SHUMAI_WORKER_DRAIN_TIMEOUT_MS, 10)
|
||||
: undefined)
|
||||
|
||||
try {
|
||||
if (DBOS.isInitialized()) {
|
||||
await DBOS.shutdown(
|
||||
timeoutMs !== undefined
|
||||
? {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- DBOS SDK parameter name
|
||||
workflowCompletionTimeoutMS: timeoutMs,
|
||||
}
|
||||
: undefined,
|
||||
)
|
||||
this.launchPromise = null
|
||||
}
|
||||
} finally {
|
||||
for (const timer of this.heartbeatIntervals.values()) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
this.heartbeatIntervals.clear()
|
||||
if (this.client) {
|
||||
await this.client.destroy().catch(() => {})
|
||||
this.client = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { WorkflowTask } from '@shumai/db'
|
||||
|
||||
export interface Executor {
|
||||
submit(task: WorkflowTask): Promise<string>
|
||||
cancel?(taskId: string): Promise<void>
|
||||
start(): void
|
||||
close(): void
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
export * from './executor'
|
||||
export * from './dbos-executor'
|
||||
export * from './registry'
|
||||
export * from './workflow-utils'
|
||||
export * from './workflow'
|
||||
export * from './activities/task'
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import { WorkflowTask } from '@shumai/db'
|
||||
import * as taskActivities from './activities/task'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
export type WorkflowFn = (task: WorkflowTask) => Promise<void>
|
||||
|
||||
const workflowRegistry = new Map<string, WorkflowFn>()
|
||||
const activityRegistry: Record<string, unknown> = { ...taskActivities }
|
||||
|
||||
export function registerWorkflow(type: string, fn: WorkflowFn): void {
|
||||
workflowRegistry.set(type, fn)
|
||||
}
|
||||
|
||||
export function getRegisteredWorkflows(): Map<string, WorkflowFn> {
|
||||
return workflowRegistry
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const globalObj = globalThis as typeof globalThis & {
|
||||
__localActivities?: Record<string, unknown>
|
||||
__localLogger?: unknown
|
||||
}
|
||||
/* eslint-enable @typescript-eslint/naming-convention */
|
||||
|
||||
export function registerActivities(acts: Record<string, unknown>): void {
|
||||
Object.assign(activityRegistry, acts)
|
||||
globalObj.__localActivities = activityRegistry
|
||||
}
|
||||
|
||||
export function getActivityRegistry(): Record<string, unknown> {
|
||||
return activityRegistry
|
||||
}
|
||||
|
||||
// Inject dependencies into global scope for workflow-utils
|
||||
globalObj.__localActivities = activityRegistry
|
||||
globalObj.__localLogger = logger
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user