Compare commits

..
6 Commits
Author SHA1 Message Date
yiling 882b03e083 fix(workflow): only register listened queues and update concurrency on change
- Only register queues that the executor instance actively listens to

- Use always_update conflict resolution so environment variable changes take effect on restart

- Prevent dedicated workers from overwriting unmanaged queue concurrency configurations

- Add tests verifying concurrency updates and queue isolation across worker roles
2026-10-17 20:18:35 +08:00
yiling c8e6f959c1 fix(workflow): ensure unique per-instance executor identity for worker replicas
- Derive unique per-instance DBOS executor IDs across worker replicas

- Support SHUMAI_WORKER_ID, DBOS__VMID, and POD_NAME (Kubernetes Downward API)

- Disambiguate multi-replica bare metal/container deployments with host, PID, and instance suffix

- Prevent startup recovery from re-enqueueing workflows actively executed by other live workers

- Add multi-instance startup recovery tests and update deployment documentation
2026-10-17 19:21:44 +08:00
yiling 7e1e2441d7 fix(workflow): ensure CLI tasks are enqueued to DBOS and run DBOS migrations in global setup
- Initialize workflows and wait for pending DBOS submissions in shumai regenerate-embeddings CLI
- Remove no-op submit bypass and enqueue tasks via DBOSClient in producer and CLI contexts
- Add DBOS migration runner in test global setup to avoid concurrent migration deadlocks across test forks
- Update changelog and add regression tests
2026-10-17 19:06:22 +08:00
yiling 6966e5876e feat(web): support SHUMAI_WORKERS environment variable 2026-10-17 16:46:46 +08:00
yiling 5f89be86d6 fix(workflow): submit tasks via DBOSClient to allow enqueueing from steps
Enqueuing workflows using DBOS.enqueueWorkflowWithOptions threw a
DBOSInvalidWorkflowTransitionError when triggered from within a running
step or activity (e.g. creating embedding or autofill tasks during
video transcoding).

Use DBOSClient to submit and cancel workflow tasks directly against the
system database, detaching execution from the ambient workflow/step
context.
2026-10-17 16:25:02 +08:00
yiling 97af81d157 feat(workflow): migrate workflow engine from temporal to dbos
Replace Temporal and LocalExecutor with DBOS Transact (@dbos-inc/dbos-sdk) as the unified workflow engine. Background tasks, media transcoding, and AI agent workflows now execute with durable steps and task queues directly against PostgreSQL, eliminating the need for an external Temporal cluster and separate polling executors.
2026-10-17 15:50:17 +08:00
158 changed files with 3383 additions and 8800 deletions
+4 -4
View File
@@ -24,7 +24,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.4
bun-version: 1.4.2
- name: Install dependencies
run: bun install
@@ -81,7 +81,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.4
bun-version: 1.4.2
- name: Install dependencies
run: bun install
@@ -126,7 +126,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.4
bun-version: 1.4.2
- name: Install dependencies
run: bun install
@@ -163,7 +163,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.4
bun-version: 1.4.2
- name: Install dependencies
run: bun install
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.4
bun-version: 1.4.2
- name: Setup Node.js
uses: actions/setup-node@v6
-28
View File
@@ -74,31 +74,3 @@ 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 }}
-2
View File
@@ -25,5 +25,3 @@ code_quality.md
# Paraglide JS
packages/webui/paraglide
runner-package.json
-3
View File
@@ -9,6 +9,3 @@ packages/webui/paraglide
*.md
**/*.md
docs/changelog.mdx
packages/webui/public
**/*.min.*
+4 -18
View File
@@ -159,7 +159,7 @@ The project is a monorepo managed by **Bun Workspaces**. It follows a strictly d
We follow Bun's monorepo conventions for dependency management:
1. **Self-Contained Packages**: Every workspace package MUST declare its own runtime `dependencies` in its local `package.json`. Do not rely on dependencies being available via the root.
2. **Shared DevDependencies**: Common development tools (e.g., `typescript`, `eslint`, `vitest`, `prisma`) MUST be declared in the root `package.json` to ensure version consistency across the workspace.
2. **Shared DevDependencies**: Common development tools (e.g., `typescript`, `eslint`, `vitest`, `prettier`, `prisma`) MUST be declared in the root `package.json` to ensure version consistency across the workspace.
3. **Local DevDependencies**: Tools specific to a single package (e.g., `@vitejs/plugin-react` for `webui`) should be declared in that package's local `package.json`.
4. **Workspace Imports**: Use `workspace:*` for internal package dependencies.
5. **Clean Root**: The root `package.json` must not contain runtime `dependencies`. It is reserved for shared `devDependencies` and workspace-wide `scripts`.
@@ -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 are dynamically registered onto the workflow registry at bootstrap time via initializer functions (e.g., `initAgentWorkflows()`, `initTranscodeWorkflows()`).
To avoid circular dependencies, workflows and activities are dynamically registered onto the workflow registry at bootstrap time via initializer functions (e.g., `initAgentWorkflows()`, `initTranscodeWorkflows()`).
### Non-Retryable Error Handling
@@ -409,27 +409,17 @@ 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 Invocation**: Workflows import and call activities directly as standard async functions.
- **Activity Access**: Activities should be accessed via `getActivities()` within a workflow.
- **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
@@ -442,10 +432,6 @@ 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'`).
+4 -26
View File
@@ -10,35 +10,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed
### Changed
## [0.6.1] - 2026-10-24
### Added
* **dashboard**: Add Workflow Tasks section to the Team Dashboard allowing team owners to monitor background workflow jobs, inspect execution payloads and outputs, and stop in-flight tasks
### Fixed
* **metadata**: Fix an issue where clicking to edit a metadata field on a card or list row inadvertently selected the file, and prevent expanded text overlays or date pickers from being clipped by container borders
* **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
* **deps**: Upgrade Bun to 1.4.4
## [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
+2 -2
View File
@@ -1,6 +1,6 @@
#syntax=docker/dockerfile:1.7-labs
# Stage 1: Builder
FROM oven/bun:1.4.4 AS builder
FROM oven/bun:1.4.2 AS builder
WORKDIR /app
@@ -28,7 +28,7 @@ RUN bun run build.ts
RUN bun run scripts/extract-runtime-deps.ts
# Stage 2: Runner
FROM oven/bun:1.4.4 AS runner
FROM oven/bun:1.4.2 AS runner
# Install system dependencies and Jellyfin-FFmpeg (with VA-API support)
RUN apt-get update && apt-get install -y --no-install-recommends \
-80
View File
@@ -1,80 +0,0 @@
#syntax=docker/dockerfile:1.7-labs
# Stage 1: Builder
FROM oven/bun:1.4.4 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.4 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"]
+4 -39
View File
@@ -12,7 +12,7 @@
<a href="https://hub.docker.com/r/shumaione/shumai"><img alt="Docker pulls" src="https://img.shields.io/docker/pulls/shumaione/shumai" /></a>
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://deepwiki.com/badge.svg" /></a>
</p>
<p align="center">
@@ -29,8 +29,7 @@ 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.
* **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).
* **Distributed Transcoding via Temporal**: Offload resource-intensive video transcoding to a background worker pool orchestrated by Temporal.
* **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.
@@ -70,13 +69,11 @@ The ultimate goal is an **agentic Kanban**, where agents and team members can wo
> * **For Images:** Shumai generates a high-quality WebP proxy at the exact same resolution as your original file for optimized viewing.
> * **For Videos:** It generates at least one proxy video (depending on your transcoding settings), alongside a sprite image and a small preview video (capped at 1600 frames) to enable fast timeline scrubbing and lightning-quick previews.
Have feedback or ideas? [Share them with us](https://github.com/shumaiOne/shumai/issues/328), and if you find Shumai useful, please give us a ⭐ or recommend Shumai to someone who might find it useful, it really helps!
---
## Installation
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).
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).
### Option 1: Docker Compose
@@ -144,38 +141,6 @@ Docker Compose is the fastest way to get Shumai running. You do not need to clon
```
6. Open your browser and access Shumai at `http://localhost:3000` (or `http://<your-server-ip>:3000` for remote deployments).
#### **Scaling Transcode Workers (Parallel Processing)**
By default, the Docker Compose deployment transcodes videos one-by-one. This is by design, as video transcoding is compute-intensive and can saturate available CPU or GPU resources.
However, when uploading large batches (e.g., 100+ videos at once) or massive raw camera files that take hours to process and block subsequent uploads, you can scale transcoding throughput across additional machines. Each machine still processes tasks sequentially, but adding more worker instances increases overall parallel capacity.
Shumai makes this seamless with a dedicated [`shumaione/shumai-transcode`](https://hub.docker.com/r/shumaione/shumai-transcode) Docker image:
1. **Connect**: Launch a temporary machine and ensure network access to your PostgreSQL database and storage backend (e.g., S3 or shared storage).
2. **Start the worker**: Run the container with matching database and storage credentials:
```bash
docker run -d --name shumai_transcode_worker \
-e DATABASE_URL="postgres://shumai:shumai_password@<postgres-host>:5432/shumai_db?sslmode=disable" \
-e STORAGE_BACKEND="s3" \
-e S3_BUCKET="your-bucket-name" \
-e AWS_ENDPOINT_URL_S3="https://s3.us-east-1.amazonaws.com" \
-e S3_ACCESS_KEY_ID="your-access-key-id" \
-e S3_SECRET_ACCESS_KEY="your-secret-access-key" \
shumaione/shumai-transcode:latest
```
The worker will automatically attach to the task queue and begin processing pending transcode jobs in parallel with your primary instance.
3. **Stop anytime**: Once the transcoding backlog finishes (or whenever you no longer need the extra compute), simply stop or remove the worker:
```bash
docker stop shumai_transcode_worker
```
There is no downtime or impact on the main Shumai application.
### Option 2: Run from Source (Development)
To set up Shumai locally for development:
+3 -39
View File
@@ -12,7 +12,7 @@
<a href="https://hub.docker.com/r/shumaione/shumai"><img alt="Docker pulls" src="https://img.shields.io/docker/pulls/shumaione/shumai" /></a>
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://img.shields.io/badge/Ask-DeepWiki-6E56CF" /></a>
<a target="_blank" href="https://deepwiki.com/shumaiOne/shumai"><img alt="Ask DeepWiki" src="https://deepwiki.com/badge.svg" /></a>
</p>
<p align="center">
@@ -29,8 +29,7 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
* **逐帧标注和评论**:支持按帧进行精确反馈,可以直接在视频和图片素材上画重点、写评论,还能留下时间戳。
* **安全分享和合集管理**:可以生成私密分享链接,也能整理成精选合集,方便给客户、同事和合作方查看。
* **细粒度权限控制**:支持按团队、项目设置角色权限,方便管理不同成员的访问范围。
* **基于 DBOS 的持久化工作流**:后台任务与 AI 工作流基于 PostgreSQL 由 DBOS 统一持久化编排与调度,具备自动恢复和容错能力。
* **Kubernetes 弹性扩缩容部署**:支持在多个实例上横向自动扩缩容视频转码工作负载。详见 [EKS 部署示例](eks/README.md)。
* **基于 Temporal 的分布式转码**:把吃资源的视频转码任务交给后台 worker 池处理,由 Temporal 统一调度。
* **自定义素材元数据**:可以按你的制作流程,自由定义动态元数据字段。
* **分享链接水印**:通过可自定义的文字和图片水印保护共享媒体,并将水印配置保存为模板以便重复使用。
* **丰富的文件格式支持**:支持预览常见创意文件格式,包括图片(支持 PSD)、视频、音频和文档,同时可上传和存储任意类型的文件。
@@ -70,7 +69,7 @@ Shumai 也将项目管理融入了创意工作流程。 内置的看板可以帮
## 安装指南
以下是使用本地存储运行 Shumai 的快速上手指南。如需了解高级配置(包括 S3 兼容存储配置、分布式 worker 编排等),请参阅我们的[官方文档](https://docs.shumai.one/getting-started/overview)。
以下是使用本地存储运行 Shumai 的快速上手指南。如需了解高级配置(包括 S3 兼容存储配置、Temporal 工作流编排等),请参阅我们的[官方文档](https://docs.shumai.one/getting-started/overview)。
### 方案一:使用 Docker Compose(推荐)
<details>
@@ -165,41 +164,6 @@ https://gh-proxy.com/https://raw.githubusercontent.com/shumaiOne/shumai/main/REA
5. 打开浏览器,访问 `http://localhost:3000` 即可开始使用(若是远程部署,请访问 `http://<您的服务器IP>:3000`)。
#### **扩展转码 Worker(并行处理)**
默认情况下,Docker Compose 部署会按顺序逐个处理视频转码任务。这是出于系统设计考虑,因为视频转码属于计算密集型任务,容易耗尽可用的 CPU 或 GPU 资源。
但在批量上传(例如一次性上传 100+ 个视频)或处理需要耗费数小时的大型摄像机原始素材时,长时间的转码任务可能会阻塞后续文件的处理。此时,您可以通过增加额外的机器来横向扩展转码吞吐量。每台机器依然按顺序执行任务,但增加 worker 实例能够显著提升整体的并行处理能力。
Shumai 提供了独立的转码 Worker 镜像(支持 Docker Hub 与阿里云镜像源):
1. **连接准备**:启动一台临时机器,确保其能够正常访问您的 PostgreSQL 数据库和存储后端(例如 S3 或共享存储)。
2. **启动 Worker**:配置相同的数据库与存储连接凭据并运行容器:
**阿里云镜像(国内推荐):**
```bash
docker run -d --name shumai_transcode_worker \
-e DATABASE_URL="postgres://shumai:shumai_password@<postgres-host>:5432/shumai_db?sslmode=disable" \
-e STORAGE_BACKEND="s3" \
-e S3_BUCKET="your-bucket-name" \
-e AWS_ENDPOINT_URL_S3="https://s3.us-east-1.amazonaws.com" \
-e S3_ACCESS_KEY_ID="your-access-key-id" \
-e S3_SECRET_ACCESS_KEY="your-secret-access-key" \
crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai-transcode:latest
```
*如使用 Docker Hub,镜像为 [`shumaione/shumai-transcode:latest`](https://hub.docker.com/r/shumaione/shumai-transcode)。*
Worker 启动后会自动接入任务队列,并与主实例并行消费并处理积压的转码任务。
3. **随时停止**:当转码队列处理完毕(或不再需要额外的算力)时,只需停止或移除 Worker 容器:
```bash
docker stop shumai_transcode_worker
```
主 Shumai 服务的运行不会受到任何影响,亦无停机时间。
### 方案二:源码编译运行(开发环境)
如果您希望在本地参与 Shumai 的开发,请按以下步骤配置开发环境:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent-app",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/cli",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/premiere-uxp",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "commonjs",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"bin": {
+1 -77
View File
@@ -14,85 +14,9 @@ async function run() {
// Initialize workflows and activities
initTranscodeWorkflows()
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)...')
}
console.log('🚀 Starting Transcode Worker...')
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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"dependencies": {
+1 -4
View File
@@ -109,7 +109,6 @@ async function run() {
}
workflowService.start(listenQueues)
workflowService.startStaleTaskRecovery()
const isProd = process.env.NODE_ENV === 'production'
@@ -207,10 +206,8 @@ async function run() {
console.log(`🚀 Server running at ${server.url}`)
const shutdown = async () => {
const shutdown = () => {
console.log('\nShutting down gracefully...')
workflowService.stopStaleTaskRecovery()
await workflowService.shutdownWorkers().catch(() => {})
assetService.stopCleanupJob()
server.stop(true)
process.exit(0)
+25 -29
View File
@@ -7,42 +7,38 @@ import { rm } from 'fs/promises'
console.log('\n🚀 Starting build process...\n')
const outdir = 'dist'
const target = process.argv[2] || 'all'
if (existsSync(outdir) && target === 'all') {
if (existsSync(outdir)) {
console.log(`🗑️ Cleaning previous build at ${outdir}`)
await rm(outdir, { recursive: true, force: true })
}
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'),
},
})
}
const allWorkers = [
{
name: 'transcode',
entrypoint: './apps/transcode/src/index.ts',
naming: 'transcode-worker.[ext]',
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'),
},
{ 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) {
for (const worker of [
{ entrypoint: './apps/transcode/src/index.ts', naming: 'transcode-worker.[ext]' },
{ entrypoint: './apps/agent/src/index.ts', naming: 'agent-worker.[ext]' },
]) {
await Bun.build({
entrypoints: [worker.entrypoint],
root: '.',
+30 -19
View File
@@ -11,13 +11,14 @@
"@testcontainers/postgresql": "12.1.0",
"@testing-library/dom": "10.4.1",
"@testing-library/react": "16.3.3",
"@types/bun": "1.4.3",
"@types/bun": "1.4.0",
"@types/node": "25.9.1",
"bun-plugin-pino": "1.5.0",
"bun-plugin-tailwind": "0.1.2",
"bun-types": "1.4.3",
"bun-types": "1.4.0",
"eslint": "10.9.1",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-prettier": "5.5.6",
"eslint-plugin-react": "7.37.5",
"globals": "17.11.0",
"happy-dom": "20.12.0",
@@ -32,7 +33,7 @@
},
"apps/agent": {
"name": "@shumai/agent-app",
"version": "0.6.1",
"version": "0.5.3",
"bin": {
"shumai-agent": "./src/index.ts",
},
@@ -44,7 +45,7 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.6.1",
"version": "0.5.3",
"bin": {
"shumai-cli": "./src/index.ts",
},
@@ -59,7 +60,7 @@
},
"apps/premiere-uxp": {
"name": "@shumai/premiere-uxp",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
@@ -113,7 +114,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.6.1",
"version": "0.5.3",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -125,7 +126,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -145,7 +146,7 @@
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.74",
"@earendil-works/pi-agent-core": "0.82.1",
@@ -168,7 +169,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@hono/zod-validator": "0.7.6",
"@shumai/core": "workspace:*",
@@ -182,7 +183,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@ai-sdk/alibaba": "2.0.38",
"@ai-sdk/amazon-bedrock": "5.0.67",
@@ -243,7 +244,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"@prisma/adapter-pg": "7.10.0",
@@ -259,7 +260,7 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"zod": "4.5.4",
@@ -267,7 +268,7 @@
},
"packages/e2e": {
"name": "@shumai/e2e",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"@google/genai": "2.28.0",
@@ -282,11 +283,11 @@
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.6.1",
"version": "0.5.3",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -297,7 +298,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@base-ui/react": "1.7.0",
"@dnd-kit/abstract": "0.5.0",
@@ -399,7 +400,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.6.1",
"version": "0.5.3",
"dependencies": {
"@dbos-inc/dbos-sdk": "5.2.11",
"@shumai/core": "workspace:*",
@@ -881,6 +882,8 @@
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@pkgr/core": ["@pkgr/core@0.3.6", "", {}, "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA=="],
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
"@pondwader/socks5-server": ["@pondwader/socks5-server@1.0.10", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
@@ -1425,7 +1428,7 @@
"@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="],
"@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
"@types/bun": ["@types/bun@1.4.0", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="],
"@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
@@ -1705,7 +1708,7 @@
"bun-plugin-tailwind": ["bun-plugin-tailwind@0.1.2", "", { "peerDependencies": { "bun": ">=1.0.0" } }, "sha512-41jNC1tZRSK3s1o7pTNrLuQG8kL/0vR/JgiTmZAJ1eHwe0w5j6HFPKeqEk0WAD13jfrUC7+ULuewFBBCoADPpg=="],
"bun-types": ["bun-types@1.4.3", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
"bun-types": ["bun-types@1.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="],
"byline": ["byline@5.0.0", "", {}, "sha512-s6webAy+R4SR8XVuJWt2V2rGvhnrhxN+9S15GNuTK3wKPOXFF6RNc+8ug2XhH+2s4f+uudG4kUVYmYOQWL2g0Q=="],
@@ -1939,6 +1942,8 @@
"eslint-config-prettier": ["eslint-config-prettier@10.1.8", "", { "peerDependencies": { "eslint": ">=7.0.0" }, "bin": { "eslint-config-prettier": "bin/cli.js" } }, "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w=="],
"eslint-plugin-prettier": ["eslint-plugin-prettier@5.5.6", "", { "dependencies": { "prettier-linter-helpers": "^1.0.1", "synckit": "^0.11.13" }, "peerDependencies": { "@types/eslint": ">=8.0.0", "eslint": ">=8.0.0", "eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0", "prettier": ">=3.0.0" }, "optionalPeers": ["@types/eslint", "eslint-config-prettier"] }, "sha512-ifetmTcxWfz+4qRW3pH/ujdTq2jQIj59AxJMIN26K5avYgU8dxycUETQonWiW+wPrYXA0j3Try0l1CnwVQtDqQ=="],
"eslint-plugin-react": ["eslint-plugin-react@7.37.5", "", { "dependencies": { "array-includes": "^3.1.8", "array.prototype.findlast": "^1.2.5", "array.prototype.flatmap": "^1.3.3", "array.prototype.tosorted": "^1.1.4", "doctrine": "^2.1.0", "es-iterator-helpers": "^1.2.1", "estraverse": "^5.3.0", "hasown": "^2.0.2", "jsx-ast-utils": "^2.4.1 || ^3.0.0", "minimatch": "^3.1.2", "object.entries": "^1.1.9", "object.fromentries": "^2.0.8", "object.values": "^1.2.1", "prop-types": "^15.8.1", "resolve": "^2.0.0-next.5", "semver": "^6.3.1", "string.prototype.matchall": "^4.0.12", "string.prototype.repeat": "^1.0.0" }, "peerDependencies": { "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" } }, "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA=="],
"eslint-scope": ["eslint-scope@9.1.2", "", { "dependencies": { "@types/esrecurse": "^4.3.1", "@types/estree": "^1.0.8", "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ=="],
@@ -1995,6 +2000,8 @@
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-diff": ["fast-diff@1.3.0", "", {}, "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw=="],
"fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="],
"fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="],
@@ -2569,6 +2576,8 @@
"prettier": ["prettier@3.9.6", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g=="],
"prettier-linter-helpers": ["prettier-linter-helpers@1.0.1", "", { "dependencies": { "fast-diff": "^1.1.2" } }, "sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg=="],
"pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="],
"prisma": ["prisma@7.10.0", "", { "dependencies": { "@prisma/config": "7.10.0", "@prisma/dev": "0.24.17", "@prisma/engines": "7.10.0", "@prisma/studio-core": "0.33.0", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw=="],
@@ -2793,6 +2802,8 @@
"supports-preserve-symlinks-flag": ["supports-preserve-symlinks-flag@1.0.0", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],
"synckit": ["synckit@0.11.13", "", { "dependencies": { "@pkgr/core": "^0.3.6" } }, "sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg=="],
"tabbable": ["tabbable@6.5.0", "", {}, "sha512-wieBHXygIm7OyQOu5hQlkk62/WyCFYGlWg7L6/ZCUZwx0o398Zkn4pVmMyfYhfMG8kGrj/Krt8eIk6UKC6VzwA=="],
"tailwind-merge": ["tailwind-merge@3.6.0", "", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="],
@@ -15,7 +15,7 @@ services:
retries: 5
embedding-server:
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/embedding-server:latest
image: shumaione/embedding-server:latest
container_name: shumai_embedding
restart: unless-stopped
@@ -15,12 +15,12 @@ services:
retries: 5
embedding-server:
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/embedding-server:latest
image: shumaione/embedding-server:latest
container_name: shumai_embedding
restart: unless-stopped
turntable-renderer:
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/turntable-renderer:latest
image: shumaione/turntable-renderer:latest
container_name: shumai_turntable
restart: unless-stopped
@@ -0,0 +1,84 @@
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:
-34
View File
@@ -3,40 +3,6 @@ title: "Changelog"
description: "Recent updates, new features, and improvements in Shumai"
---
<Update label="v0.6.1" description="October 24, 2026">
### Added
* **dashboard**: Add Workflow Tasks section to the Team Dashboard allowing team owners to monitor background workflow jobs, inspect execution payloads and outputs, and stop in-flight tasks
### Fixed
* **metadata**: Fix an issue where clicking to edit a metadata field on a card or list row inadvertently selected the file, and prevent expanded text overlays or date pickers from being clipped by container borders
### Changed
* **deps**: Upgrade Bun to 1.4.4
</Update>
<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
-173
View File
@@ -1,173 +0,0 @@
---
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.
+7 -8
View File
@@ -64,15 +64,14 @@ For example, if you deploy Shumai on a remote server at `http://123.456.7.8` and
## Workflow Config
Configures background worker execution, concurrency limits, and worker identity for DBOS Transact queues.
Configures whether background transcoding and AI agents are executed locally or offloaded to a Temporal cluster.
| 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` |
| 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) |
---
+85
View File
@@ -0,0 +1,85 @@
---
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
View File
@@ -76,8 +76,8 @@
"pages": ["configuration/env-variables", "configuration/hardware-transcoding"]
},
{
"group": "Distributed Deployment",
"pages": ["configuration/distributed"]
"group": "Temporal Deployment",
"pages": ["configuration/temporal"]
},
{
"group": "Releases",
+1 -1
View File
@@ -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 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).
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).
_Note: S3-compatible cloud storage is required for distributed deployments so that all workers can access the uploaded files._
+2 -2
View File
@@ -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 (Distributed Workers)
### Production Deployments (Temporal)
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.
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.
---
+2 -2
View File
@@ -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 (Dedicated 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 (Temporal Worker mode).
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.
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.
-245
View File
@@ -1,245 +0,0 @@
# 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
```
-31
View File
@@ -1,31 +0,0 @@
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'
-57
View File
@@ -1,57 +0,0 @@
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
View File
@@ -1,238 +0,0 @@
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!"
-11
View File
@@ -1,11 +0,0 @@
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
-4
View File
@@ -1,4 +0,0 @@
apiVersion: v1
kind: Namespace
metadata:
name: shumai
-79
View File
@@ -1,79 +0,0 @@
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
-85
View File
@@ -1,85 +0,0 @@
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
-90
View File
@@ -1,90 +0,0 @@
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
-12
View File
@@ -1,12 +0,0 @@
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
+5 -4
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"repository": {
@@ -24,7 +24,7 @@
"test:e2e:workflow": "bun --bun vitest run -c packages/e2e/vitest.config.ts",
"test:e2e:install": "playwright install --with-deps",
"harness:dev": "bun run packages/webui/e2e/harness/serve.ts",
"format": "bun fmt",
"format": "prettier --write .",
"db:migrate": "bun run prisma migrate dev",
"db:deploy": "bun run prisma migrate deploy",
"db:generate": "cd packages/db && bunx prisma generate",
@@ -50,13 +50,14 @@
"@testcontainers/postgresql": "12.1.0",
"@testing-library/dom": "10.4.1",
"@testing-library/react": "16.3.3",
"@types/bun": "1.4.3",
"@types/bun": "1.4.0",
"@types/node": "25.9.1",
"bun-plugin-pino": "1.5.0",
"bun-plugin-tailwind": "0.1.2",
"bun-types": "1.4.3",
"bun-types": "1.4.0",
"eslint": "10.9.1",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-prettier": "5.5.6",
"eslint-plugin-react": "7.37.5",
"globals": "17.11.0",
"happy-dom": "20.12.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"main": "./src/index.ts",
File diff suppressed because it is too large Load Diff
+270 -459
View File
@@ -2,17 +2,11 @@ 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 { execFile } from 'child_process'
import { promisify } from 'util'
import { ulid } from 'ulid'
import { ApplicationFailure, defineStep } from '@shumai/workflow-core'
import { ApplicationFailure } from '@shumai/workflow-core'
import { prisma } from '@shumai/db'
import sharp from 'sharp'
const execFileAsync = promisify(execFile)
export interface Usage {
inputTokens: number
outputTokens: number
@@ -118,44 +112,42 @@ export interface GenerateTextEmbeddingParams {
teamId: string
}
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,
})
}
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,
})
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,
})
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,
})
}
}
export interface ExtractAiMetadataParams {
assetKey: string
@@ -164,7 +156,7 @@ export interface ExtractAiMetadataParams {
isImage: boolean
}
export const extractAiMetadataActivity = defineStep(async function extractAiMetadataActivity(
export async function extractAiMetadataActivity(
params: ExtractAiMetadataParams,
): Promise<string[]> {
const bucket = process.env.S3_BUCKET || 'shumai'
@@ -215,51 +207,50 @@ export const extractAiMetadataActivity = defineStep(async function extractAiMeta
}
return generatedFiles
})
}
export const getEmbeddingContextActivity = defineStep(
async function getEmbeddingContextActivity(params: { teamId: string; assetId: string }) {
const team = await prisma.team.findUnique({
where: { id: params.teamId },
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,
})
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,
})
}
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 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 parsedDuration = parseFloat(process.env.EMBEDDING_CHUNK_DURATION || '')
const chunkDuration =
Number.isFinite(parsedDuration) && parsedDuration > 0 ? parsedDuration : 60.0
const parsedDuration = parseFloat(process.env.EMBEDDING_CHUNK_DURATION || '')
const chunkDuration =
Number.isFinite(parsedDuration) && parsedDuration > 0 ? parsedDuration : 60.0
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 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[]>`
const existingEmbeddings = await prisma.$queryRaw<ExistingAssetEmbeddingInfo[]>`
SELECT
id,
start_time as "startTime",
@@ -270,16 +261,15 @@ export const getEmbeddingContextActivity = defineStep(
WHERE asset_id = ${params.assetId}
`
return {
agent,
asset,
chunkDuration,
chunkOverlap,
embeddingProvider,
existingEmbeddings,
}
},
)
return {
agent,
asset,
chunkDuration,
chunkOverlap,
embeddingProvider,
existingEmbeddings,
}
}
export interface ExistingAssetEmbeddingInfo {
id: string
@@ -289,66 +279,62 @@ export interface ExistingAssetEmbeddingInfo {
has768: boolean
}
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 {
await prisma.assetEmbedding.deleteMany({
where: {
assetId: params.assetId,
},
})
}
},
)
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 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
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())
`
}
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 {
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())
`
}
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 {
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
@@ -356,60 +342,60 @@ export interface GenerateImageEmbeddingParams {
mediaType: string
}
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,
)
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,
)
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:
@@ -448,296 +434,121 @@ export interface GenerateVideoChunkEmbeddingParams {
chunkKey: string
}
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')
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')
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) {
let filesMap: Map<string, File>
try {
const archive = new Bun.Archive(data)
filesMap = await archive.files()
} catch (err) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
message: `Failed to read chunk archive ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const frameFiles = Array.from(filesMap.keys())
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
.sort()
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
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,
}
} catch (err) {
if (frameFiles.length === 0) {
throw ApplicationFailure.create({
message: `Failed to generate video chunk embedding for key ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
message: `No extracted frames found in chunk archive ${params.chunkKey}`,
nonRetryable: true,
})
}
},
)
export interface TranscodeVideoChunkParams {
assetId: string
assetKey?: string
filePath?: string
startTime: number
endTime: number
format?: 'video' | 'frames'
}
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
}
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
params: TranscodeVideoChunkParams,
): Promise<{ chunkKey: string }> {
if (!params.filePath && !params.assetKey) {
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: 'Neither filePath nor assetKey was provided for video chunk transcoding',
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
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 resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
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 usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}-${ulid()}.mp4`)
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 { 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 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 transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
message: `Failed to generate video chunk embedding for key ${params.chunkKey}: ${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 },
)
}
+6 -1
View File
@@ -604,7 +604,9 @@ export function formatSkillsForPrompt(
}
import { WorkflowTaskType } from '@shumai/db'
import { registerWorkflow } from '@shumai/workflow-core'
import { registerActivities, registerWorkflow } from '@shumai/workflow-core'
import * as agentActivities from './activities/agent'
import * as aiActivities from './activities/ai'
import { agentAutofillMedia } from './workflows/agent-autofill'
import { agentChat } from './workflows/agent-chat'
import { agentEmbeddingMedia } from './workflows/agent-embedding'
@@ -613,6 +615,9 @@ 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'
@@ -34,7 +34,8 @@ export async function resolveAnnotationsById(
})
if (entry) {
const details = (entry.data as Record<string, unknown> | null)?.details as
ShumaiMessageContext | undefined
| ShumaiMessageContext
| undefined
const entryAssetId = entry.assetId || details?.currentAsset?.id
if (entryAssetId && entryAssetId !== assetId) {
throw new Error(
+4 -2
View File
@@ -355,7 +355,8 @@ export function createReadAssetTool(
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode screenshot output
const output = completedTask.output as any
const screenshots = output?.screenshots as
Array<{ key: string; timestamp: number }> | undefined
| Array<{ key: string; timestamp: number }>
| undefined
if (!screenshots || screenshots.length === 0) {
throw new Error(
@@ -619,7 +620,8 @@ export function createReadAssetTool(
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode screenshot output
const output = completedTask.output as any
const screenshots = output?.screenshots as
Array<{ key: string; timestamp: number }> | undefined
| Array<{ key: string; timestamp: number }>
| undefined
if (!screenshots || screenshots.length === 0) {
throw new Error('No screenshots were generated.')
@@ -2,29 +2,14 @@ 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 workflowCore from '@shumai/workflow-core'
import * as agentActivities from '../activities/agent'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async () => {
const actual = await vi.importActual('@shumai/workflow-core')
return {
...actual,
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(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
}
})
@@ -38,15 +23,26 @@ describe('Agent Autofill Workflow', () => {
vi.clearAllMocks()
mockActivities = {
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),
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' }),
}
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
@@ -69,6 +65,13 @@ 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 () => {
+48 -35
View File
@@ -1,33 +1,38 @@
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
updateTaskStatusActivity,
updateTaskUsageActivity,
executeActivity,
getActivities,
TaskQueueAgent,
} 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 updateTaskStatusActivity({
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
// 0. Create Placeholder Comment
const payload = task.payload
const placeholder = await createCommentActivity({
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
assetId: task.assetId,
message: '__AUTOFILL__',
sessionId: payload?.agent?.sessionId || task.id,
@@ -36,7 +41,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
placeholderCommentId = placeholder.id
// 1. Get Asset
const asset = await getAssetActivity(task.assetId)
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
if (!asset || !asset.project) {
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
}
@@ -44,15 +49,19 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
const projectId = asset.project.id
// 2. Get Project Autofill Fields
const fields = await getProjectAutofillFieldsActivity(projectId)
const fields = await executeActivity(
agentWorkerQueue,
getProjectAutofillFieldsActivity,
projectId,
)
if (fields.length === 0) {
if (placeholderCommentId) {
await updateCommentActivity({
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed: No autofill fields defined in project.',
})
}
await updateTaskStatusActivity({
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
@@ -60,7 +69,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
}
// 3. Fetch Agent Context
const context = await getAgentAutofillContextActivity({
const context = await executeActivity(agentWorkerQueue, getAgentAutofillContextActivity, {
teamId,
})
@@ -82,7 +91,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
: undefined
: undefined
const aiResult = await autofillAiActivity({
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
teamId,
assetId: asset.id,
assetName: asset.name,
@@ -90,17 +99,19 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
duration,
pageCount,
projectId: asset.projectId ?? undefined,
fields: fields.map((f) => ({
id: f.key,
config: (f.config as unknown as PrismaJson.FieldConfig) ?? {},
description: f.description,
})),
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,
}),
),
context,
})
if (aiResult.usage) {
// Update Usage
await updateTaskUsageActivity({
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
@@ -118,7 +129,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
}))
if (metadataUpdates.length > 0) {
await updateAssetMetadataActivity({
await executeActivity(agentWorkerQueue, updateAssetMetadataActivity, {
assetId: asset.id,
metadata: metadataUpdates,
})
@@ -126,7 +137,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
// 7. Update Placeholder Comment
if (placeholderCommentId) {
await updateCommentActivity({
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed successfully.',
sessionId: aiResult.sessionId,
@@ -134,7 +145,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
}
// Update status to completed
await updateTaskStatusActivity({
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
@@ -142,9 +153,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) {
if (placeholderCommentId && agentWorkerQueue) {
try {
await updateCommentActivity({
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
})
@@ -154,11 +165,13 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
}
// Update status to failed
await updateTaskStatusActivity({
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
if (agentWorkerQueue) {
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
}
throw err
}
}
+38 -37
View File
@@ -2,34 +2,14 @@ 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 workflowCore from '@shumai/workflow-core'
import * as agentActivities from '../activities/agent'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async () => {
const actual = await vi.importActual('@shumai/workflow-core')
return {
...actual,
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(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
}
})
@@ -43,20 +23,34 @@ describe('Agent Chat Workflow', () => {
vi.clearAllMocks()
mockActivities = {
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),
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',
}),
}
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
@@ -94,6 +88,13 @@ 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 () => {
+63 -40
View File
@@ -1,22 +1,10 @@
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
updateTaskStatusActivity,
updateTaskUsageActivity,
executeActivity,
getActivities,
TaskQueueAgent,
} from '@shumai/workflow-core'
import {
agentChatActivity,
createCommentActivity,
generateSessionNameActivity,
getAgentChatContextActivity,
getAssetActivity,
getAssetPathContextActivity,
getAssetPathHierarchyActivity,
getCommentActivity,
getUserTeamInfoActivity,
initializeAgentSessionActivity,
updateCommentActivity,
} from '../activities/agent'
import type {
ShumaiMessageContext,
ShumaiAssetContext,
@@ -27,11 +15,28 @@ 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 updateTaskStatusActivity({
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
@@ -60,7 +65,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
let commentAnnotations: unknown[] | undefined
if (userCommentId) {
userComment = await getCommentActivity(userCommentId)
userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
if (!userComment) {
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
}
@@ -79,7 +84,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
// 2. Create Placeholder Comment
const placeholder = await createCommentActivity({
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
assetId: task.assetId,
message: '__CHAT__',
sessionId: sessionId || 'pending',
@@ -114,7 +119,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
// 3. Get Asset
const asset = await getAssetActivity(task.assetId)
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
if (!asset || !asset.project) {
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
}
@@ -129,7 +134,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
nonRetryable: true,
})
}
sessionId = await initializeAgentSessionActivity({
sessionId = await executeActivity(agentWorkerQueue, initializeAgentSessionActivity, {
teamId,
agentId: agentId,
userCommentId,
@@ -139,14 +144,18 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
// 4b. Fetch Agent Context
const context = await getAgentChatContextActivity({
const context = await executeActivity(agentWorkerQueue, getAgentChatContextActivity, {
teamId,
agentId: agentId,
userId: payload.agent?.userId,
projectId: payload.projectId,
})
const pathHierarchy = await getAssetPathHierarchyActivity(task.assetId)
const pathHierarchy = await executeActivity(
agentWorkerQueue,
getAssetPathHierarchyActivity,
task.assetId,
)
const assetPath = pathHierarchy?.path || ''
const ancestors = pathHierarchy?.ancestors || []
@@ -171,7 +180,11 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
if (userCommentId && userComment?.attachments) {
for (const att of userComment.attachments) {
if (att.asset) {
const filePath = await getAssetPathContextActivity(att.asset.id)
const filePath = await executeActivity(
agentWorkerQueue,
getAssetPathContextActivity,
att.asset.id,
)
const attProxyType =
(att.asset.media as PrismaJson.MediaInfo | null)?.proxyType ||
getProxyType(att.asset.mediaType, att.asset.name) ||
@@ -190,9 +203,13 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
} else if (payload.agent?.attachedFiles) {
for (const fileId of payload.agent.attachedFiles) {
const file = await getAssetActivity(fileId)
const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId)
if (file) {
const filePath = await getAssetPathContextActivity(fileId)
const filePath = await executeActivity(
agentWorkerQueue,
getAssetPathContextActivity,
fileId,
)
const fileProxyType =
(file.media as PrismaJson.MediaInfo | null)?.proxyType ||
getProxyType(file.mediaType, file.name) ||
@@ -215,9 +232,13 @@ 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 getAssetActivity(assetId)
const referencedAsset = await executeActivity(agentWorkerQueue, getAssetActivity, assetId)
if (referencedAsset) {
const filePath = await getAssetPathContextActivity(assetId)
const filePath = await executeActivity(
agentWorkerQueue,
getAssetPathContextActivity,
assetId,
)
const refProxyType =
(referencedAsset.media as PrismaJson.MediaInfo | null)?.proxyType ||
getProxyType(referencedAsset.mediaType, referencedAsset.name) ||
@@ -244,7 +265,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 getUserTeamInfoActivity({
userInfo = await executeActivity(agentWorkerQueue, getUserTeamInfoActivity, {
userId: targetUserId,
teamId,
})
@@ -304,7 +325,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
folderId = asset.parentId
}
const aiResult = await agentChatActivity({
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
taskId: task.id,
teamId,
agentId: agentId,
@@ -323,7 +344,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// 7. Update Placeholder Comment
if (placeholderCommentId) {
await updateCommentActivity({
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
message: aiResult.text,
sessionId: aiResult.sessionId,
@@ -332,7 +353,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// 8. Update Usage
if (aiResult.usage) {
await updateTaskUsageActivity({
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
@@ -342,7 +363,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// 9. Generate Session Name for new chats
if (isNewChat) {
await generateSessionNameActivity({
await executeActivity(agentWorkerQueue, generateSessionNameActivity, {
teamId,
agentId,
prompt,
@@ -354,7 +375,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
// Update status to completed
await updateTaskStatusActivity({
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
output: { sessionId: aiResult.sessionId },
@@ -363,7 +384,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) {
if (placeholderCommentId && agentWorkerQueue) {
try {
let errorMessage = 'Sorry, I encountered an error while processing your request.'
if (err instanceof Error) {
@@ -385,7 +406,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
errorMessage = 'Agent execution stopped.'
}
await updateCommentActivity({
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
message: errorMessage,
})
@@ -395,11 +416,13 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
}
// Update status to failed
await updateTaskStatusActivity({
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
if (agentWorkerQueue) {
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
}
throw err
}
}
@@ -2,39 +2,14 @@ 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 workflowCore from '@shumai/workflow-core'
import * as agentActivities from '../activities/agent'
import * as aiActivities from '../activities/ai'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async () => {
const actual = await vi.importActual('@shumai/workflow-core')
return {
...actual,
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(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
}
})
@@ -48,21 +23,39 @@ describe('Agent Embedding Workflow', () => {
vi.clearAllMocks()
mockActivities = {
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),
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',
}),
}
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
@@ -98,6 +91,13 @@ 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 () => {
+57 -38
View File
@@ -1,20 +1,11 @@
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
updateTaskStatusActivity,
updateTaskUsageActivity,
getActivities,
executeActivity,
TaskQueueAgent,
TaskQueueTranscode,
} 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[]
@@ -22,21 +13,43 @@ export interface GeneratedEmbedding {
endTime?: number
}
export type { ExistingAssetEmbeddingInfo }
export interface ExistingAssetEmbeddingInfo {
id: string
startTime: number | null
endTime: number | null
has1536: boolean
has768: boolean
}
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 updateTaskStatusActivity({
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
// 0. Create Placeholder Comment
const payload = task.payload
const placeholder = await createCommentActivity({
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
assetId: task.assetId,
message: '__EMBEDDING__',
sessionId: payload?.agent?.sessionId || task.id,
@@ -49,7 +62,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
}
// 1. Fetch Agent Context
const context = (await getEmbeddingContextActivity({
const context = (await executeActivity(agentWorkerQueue, getEmbeddingContextActivity, {
teamId: task.teamId,
assetId: task.assetId,
})) as unknown as {
@@ -76,7 +89,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
.map((e) => e.id)
if (incompatibleIds.length > 0) {
await deleteAssetEmbeddingsActivity({
await executeActivity(agentWorkerQueue, deleteAssetEmbeddingsActivity, {
assetId: task.assetId,
ids: incompatibleIds,
})
@@ -138,12 +151,12 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
(e) => e.startTime === null && e.endTime === null,
)
if (!alreadyEmbedded) {
const result = await generateImageEmbeddingActivity({
const result = await executeActivity(agentWorkerQueue, generateImageEmbeddingActivity, {
teamId: task.teamId,
assetKey: embeddingKey,
mediaType: embeddingMediaType || 'image/jpeg',
mediaType: embeddingMediaType,
})
await saveAssetEmbeddingsActivity({
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
assetId: task.assetId,
embeddings: [{ embedding: result.embedding }],
})
@@ -184,7 +197,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
}
// Step A: Slice chunk on transcode worker and upload to S3
const chunkRes = await transcodeVideoChunkActivity({
const chunkRes = await executeActivity(transcodeWorkerQueue, transcodeVideoChunkActivity, {
assetId: asset.id,
assetKey: embeddingKey,
startTime: start,
@@ -195,13 +208,17 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
try {
// Step B: Generate embedding on agent worker
const chunkResult = await generateVideoChunkEmbeddingActivity({
teamId: task.teamId,
chunkKey,
})
const chunkResult = await executeActivity(
agentWorkerQueue,
generateVideoChunkEmbeddingActivity,
{
teamId: task.teamId,
chunkKey,
},
)
// Step C: Save chunk embedding to database immediately
await saveAssetEmbeddingsActivity({
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
assetId: task.assetId,
embeddings: [
{
@@ -218,7 +235,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
}
} finally {
// Step D: Delete temporary chunk from S3
await deleteS3ObjectActivity({
await executeActivity(transcodeWorkerQueue, deleteS3ObjectActivity, {
key: chunkKey,
})
}
@@ -231,7 +248,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
}
// Update Usage
await updateTaskUsageActivity({
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: usage.inputTokens,
outputTokens: usage.outputTokens,
@@ -240,14 +257,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
// 7. Update Placeholder Comment
if (placeholderCommentId) {
await updateCommentActivity({
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Embedding completed successfully.',
})
}
// Update status to completed
await updateTaskStatusActivity({
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
@@ -255,9 +272,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) {
if (placeholderCommentId && agentWorkerQueue) {
try {
await updateCommentActivity({
await executeActivity(agentWorkerQueue, updateCommentActivity, {
commentId: placeholderCommentId,
message: `Embedding failed: ${err instanceof Error ? err.message : String(err)}`,
})
@@ -267,11 +284,13 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
}
// Update status to failed
await updateTaskStatusActivity({
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
if (agentWorkerQueue) {
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
}
throw err
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"main": "./src/index.ts",
-131
View File
@@ -68,14 +68,6 @@ vi.mock('@shumai/core/src/gotenberg/gotenberg', () => ({
},
}))
vi.mock('@shumai/core/src/workflowTask/workflowTask', () => ({
workflowTaskService: {
listWorkflowTasks: vi.fn(),
getBatchWorkflowTaskStatus: vi.fn(),
stopWorkflowTask: vi.fn(),
},
}))
describe('team api', () => {
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -663,129 +655,6 @@ describe('team api', () => {
)
})
it('GET /teams/:teamId/workflow-tasks returns list of workflow tasks for team owner', async () => {
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
vi.mocked(workflowTaskService.listWorkflowTasks).mockResolvedValue({
nodes: [
{
id: 'task1',
uid: 'uid1',
teamId: 't1',
projectId: 'p1',
assetId: 'a1',
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
status: 'processing' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
payload: {},
output: null,
heartbeat: null,
inputTokens: 0,
outputTokens: 0,
model: null,
sessionId: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
pageInfo: {
hasNextPage: false,
endCursor: null,
},
total: 1,
})
const res = await app.request('/teams/t1/workflow-tasks')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.nodes).toHaveLength(1)
expect(data.nodes[0].id).toBe('task1')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
}),
)
})
it('POST /teams/:teamId/workflow-tasks/batch-status returns batch task statuses', async () => {
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
vi.mocked(workflowTaskService.getBatchWorkflowTaskStatus).mockResolvedValue({
tasks: [
{
id: 'task1',
uid: 'uid1',
teamId: 't1',
projectId: 'p1',
assetId: 'a1',
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
status: 'completed' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
payload: {},
output: null,
heartbeat: null,
inputTokens: 0,
outputTokens: 0,
model: null,
sessionId: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
})
const res = await app.request('/teams/t1/workflow-tasks/batch-status', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ taskIds: ['task1'] }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.tasks).toHaveLength(1)
expect(data.tasks[0].status).toBe('completed')
})
it('POST /teams/:teamId/workflow-tasks/:taskId/stop stops task for team owner', async () => {
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
vi.mocked(workflowTaskService.stopWorkflowTask).mockResolvedValue({
success: true,
task: {
id: 'task1',
uid: 'uid1',
teamId: 't1',
projectId: 'p1',
assetId: 'a1',
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
status: 'failed' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
payload: {},
output: { error: 'Task was stopped by user' },
heartbeat: null,
inputTokens: 0,
outputTokens: 0,
model: null,
sessionId: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
})
const res = await app.request('/teams/t1/workflow-tasks/task1/stop', {
method: 'POST',
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.success).toBe(true)
expect(data.task.status).toBe('failed')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
}),
)
})
it('GET /teams/:teamId/turntable-settings returns turntable settings', async () => {
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
vi.mocked(turntableService.getSettings).mockResolvedValue({
-71
View File
@@ -16,8 +16,6 @@ import {
updateTeamMemberRoleRequestSchema,
createApiTokenRequestSchema,
listAuditLogsQuerySchema,
listWorkflowTasksQuerySchema,
batchWorkflowTaskStatusSchema,
} from '@shumai/dtos'
import {
updateUserMetadataRequestSchema,
@@ -27,7 +25,6 @@ import {
import { apiTokenService } from '@shumai/core/src/user/api-token'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { workflowTaskService } from '@shumai/core/src/workflowTask/workflowTask'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { NotificationType } from '@shumai/db'
@@ -520,73 +517,5 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(logs)
})
.get(
'/teams/:teamId/workflow-tasks',
zValidator('query', listWorkflowTasksQuerySchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const query = c.req.valid('query')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const tasks = await workflowTaskService.listWorkflowTasks({
teamId,
status: query.status,
types: query.types,
first: query.first,
after: query.after,
})
return c.json(tasks)
},
)
.post(
'/teams/:teamId/workflow-tasks/batch-status',
zValidator('json', batchWorkflowTaskStatusSchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const result = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId,
taskIds: req.taskIds,
})
return c.json(result)
},
)
.post('/teams/:teamId/workflow-tasks/:taskId/stop', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const taskId = c.req.param('taskId')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const result = await workflowTaskService.stopWorkflowTask({
teamId,
taskId,
})
return c.json(result)
})
export default route
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/core",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"main": "./src/index.ts",
+3 -6
View File
@@ -3240,7 +3240,7 @@ describe('AssetService — natural sort by name', () => {
await expect(assetService.emptyTrash(project.id)).resolves.not.toThrow()
})
it('should purge trashed assets whose status was processed, cancel their in-flight tasks, and retain WorkflowTasks as failed', async () => {
it('should purge trashed assets whose status was processed, cancel their in-flight tasks, and delete WorkflowTasks', async () => {
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
const team = await prisma.team.create({ data: { name: 'Purge Task Team' } })
@@ -3292,12 +3292,9 @@ describe('AssetService — natural sort by name', () => {
// Task should be cancelled
expect(cancelSpy).toHaveBeenCalledWith(task.id)
// WorkflowTask should be retained in DB and marked as failed
// WorkflowTask should be deleted from DB
const taskInDb = await prisma.workflowTask.findUnique({ where: { id: task.id } })
expect(taskInDb).not.toBeNull()
expect(taskInDb?.status).toBe(WorkflowTaskStatus.failed)
const output = taskInDb?.output as { error?: string }
expect(output?.error).toBe('Asset was purged')
expect(taskInDb).toBeNull()
cancelSpy.mockRestore()
})
+19 -23
View File
@@ -1419,17 +1419,6 @@ export class AssetService {
logger.warn({ taskId: task.id, err }, 'Failed to cancel workflow task during purge')
}
}
await this.prismaClient.workflowTask.updateMany({
where: {
assetId: { in: affectedIds },
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Asset was purged' },
},
})
}
}
@@ -1529,15 +1518,8 @@ export class AssetService {
}
}
await this.prismaClient.workflowTask.updateMany({
where: {
assetId: { in: pendingAssetIds },
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Asset was purged' },
},
await this.prismaClient.workflowTask.deleteMany({
where: { assetId: { in: pendingAssetIds } },
})
}
@@ -2426,7 +2408,12 @@ export class AssetService {
}
const proxyType = (media?.proxyType || null) as
'image' | 'video' | 'audio' | 'pdf' | '3d' | null
| 'image'
| 'video'
| 'audio'
| 'pdf'
| '3d'
| null
result.push({
id: a.id,
@@ -2793,7 +2780,12 @@ export class AssetService {
if (!asset.media) return null
const proxyType = (asset.media?.proxyType || null) as
'image' | 'video' | 'audio' | 'pdf' | '3d' | null
| 'image'
| 'video'
| 'audio'
| 'pdf'
| '3d'
| null
let rawThumbKey: string | undefined
if (proxyType === 'image' && asset.media.thumbnail?.key) {
@@ -2872,7 +2864,11 @@ export class AssetService {
'GET',
)
const attachmentProxyType = (a.asset.media?.proxyType || null) as
'image' | 'video' | 'audio' | 'pdf' | null
| 'image'
| 'video'
| 'audio'
| 'pdf'
| null
attachments.push({
id: a.id,
assetId: a.asset.id,
+3 -1
View File
@@ -90,7 +90,9 @@ export class GotenbergService {
})
if (versionRes.ok) {
const vData = (await versionRes.json().catch(() => null)) as
{ version?: string } | string | null
| { version?: string }
| string
| null
if (vData && typeof vData === 'object' && 'version' in vData) {
version = String(vData.version)
} else if (typeof vData === 'string') {
+2 -1
View File
@@ -68,7 +68,8 @@ export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Set
})
const teamSettings = team?.settings as PrismaJson.Settings | null
const serviceSettings = teamSettings?.[def.settingsKey] as
{ url?: string; username?: string; password?: string } | undefined
| { url?: string; username?: string; password?: string }
| undefined
if (serviceSettings?.url?.trim()) {
return {
+3 -1
View File
@@ -41,7 +41,9 @@ export interface ProxyServerInfo {
}
export type ConnectionOutcome =
{ status: 'connected' } | { status: 'needs-auth' } | { status: 'error'; message: string }
| { status: 'connected' }
| { status: 'needs-auth' }
| { status: 'error'; message: string }
export interface CallToolOutcome {
ok: boolean
+2 -1
View File
@@ -351,7 +351,8 @@ export class McpService {
instructions?: string | null
} = {}
const impl = connection.serverVersion as
{ name?: string; title?: string; description?: string } | undefined
| { name?: string; title?: string; description?: string }
| undefined
if (impl && typeof impl === 'object') {
const reportedName = impl.title ?? impl.name
if (typeof reportedName === 'string' && reportedName.trim() !== '') {
+21 -33
View File
@@ -43,30 +43,24 @@ export function getNextOptionColor(existingOptions: PrismaJson.SelectOption[] =
export class MetadataService {
constructor(private client: typeof prisma = prisma) {}
async syncSystemFields(): Promise<void> {
await this.client.$transaction(
async (tx) => {
for (const field of systemFields) {
await tx.metadataField.upsert({
where: { key: field.key },
update: {
scope: field.scope,
readOnly: field.readOnly,
config: field.config,
},
create: {
key: field.key,
scope: field.scope,
readOnly: field.readOnly ?? false,
config: field.config,
},
})
}
},
{
maxWait: 10000,
timeout: 30000,
},
)
await this.client.$transaction(async (tx) => {
for (const field of systemFields) {
await tx.metadataField.upsert({
where: { key: field.key },
update: {
scope: field.scope,
readOnly: field.readOnly,
config: field.config,
},
create: {
key: field.key,
scope: field.scope,
readOnly: field.readOnly ?? false,
config: field.config,
},
})
}
})
}
async createTeamField(
@@ -318,15 +312,9 @@ export class MetadataService {
reqs: UpdateAssetMetadataRequest[],
allowReadOnly = false,
): Promise<void> {
await this.client.$transaction(
async (tx) => {
await this.updateAssetMetadataInternal(tx, assetId, reqs, allowReadOnly)
},
{
maxWait: 10000,
timeout: 30000,
},
)
await this.client.$transaction(async (tx) => {
await this.updateAssetMetadataInternal(tx, assetId, reqs, allowReadOnly)
})
}
/**
@@ -1,54 +0,0 @@
{
"anthropic": {
"models": {
"claude-3-5-sonnet-20241022": {
"id": "claude-3-5-sonnet-20241022",
"name": "Claude 3.5 Sonnet",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 200000,
"output": 8192
},
"cost": {
"input": 3,
"output": 15,
"cache_read": 0.3,
"cache_write": 3.75
}
}
}
},
"openai": {
"models": {
"gpt-4o": {
"id": "gpt-4o",
"name": "GPT-4o",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
},
"gpt-4o-extra-new": {
"id": "gpt-4o-extra-new",
"name": "GPT-4o Extra New",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
}
}
}
}
@@ -1,7 +0,0 @@
{
"data": [
{
"id": "meta/llama-3.1-70b-instruct"
}
]
}
@@ -1,17 +0,0 @@
{
"data": [
{
"id": "meta-llama/llama-3.1-8b-instruct",
"name": "Meta: Llama 3.1 8B Instruct",
"context_length": 131072,
"pricing": {
"prompt": "0.00000005",
"completion": "0.00000008"
},
"top_provider": {
"max_completion_tokens": 8192
},
"supported_parameters": ["tools"]
}
]
}
@@ -1141,7 +1141,8 @@ async function loadModelsDevData(): Promise<Model<any>[]> {
baseUrl: getBedrockBaseUrl(id),
reasoning: m.reasoning === true,
input: (m.modalities?.input?.includes('image') ? ['text', 'image'] : ['text']) as (
'text' | 'image'
| 'text'
| 'image'
)[],
cost: {
input: m.cost?.input || 0,
+6 -44
View File
@@ -8,42 +8,6 @@ import * as generateModelsModule from './generator/generate-models'
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
import { z } from 'zod'
import modelsDevFixture from './fixtures/models-dev.json'
import openRouterFixture from './fixtures/openrouter.json'
import nvidiaFixture from './fixtures/nvidia.json'
const originalFetch = globalThis.fetch
function setupCatalogFetchMock() {
return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
if (url.includes('models.dev')) {
return new Response(JSON.stringify(modelsDevFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('openrouter.ai')) {
return new Response(JSON.stringify(openRouterFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('nvidia')) {
return new Response(JSON.stringify(nvidiaFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('ai-gateway')) {
return new Response(JSON.stringify({ data: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return originalFetch(input)
})
}
type ProviderModel = z.infer<typeof providerModelSchema>
@@ -385,9 +349,10 @@ describe('ProviderService', () => {
expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages')
})
it('should check for updates and correctly segregate new vs existing providers', async () => {
const fetchSpy = setupCatalogFetchMock()
try {
it(
'should check for updates and correctly segregate new vs existing providers',
{ timeout: 30000 },
async () => {
// 1. Check updates with empty team: all discovered providers are new
const emptyTeam = await prisma.team.create({
data: { name: 'Empty Provider Team' },
@@ -403,7 +368,6 @@ describe('ProviderService', () => {
// 3. Check updates after init: existing providers should have isNewProvider: false
const afterInitCheck = await providerService.checkUpdates(teamWithBuiltins.id)
const existing = afterInitCheck.providers.find((p) => !p.isNewProvider)
expect(existing).toBeDefined()
if (existing) {
expect(existing.isNewProvider).toBe(false)
const dbModels = await providerService.listModelsByProvider(
@@ -417,10 +381,8 @@ describe('ProviderService', () => {
expect(dbModelIds.has(m.modelId)).toBe(false)
}
}
} finally {
fetchSpy.mockRestore()
}
})
},
)
it('should throw an error when upstream catalog fetch fails in checkUpdates', async () => {
const team = await teamService.ensureDefaultTeam()
+1 -39
View File
@@ -351,35 +351,7 @@ 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',
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)
expect(presignSpy).toHaveBeenCalledWith('test-bucket', 'video.mp4', 'GET')
})
it('should stream in uploadFileToKey', async () => {
@@ -670,16 +642,6 @@ 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', () => {
+11 -33
View File
@@ -111,7 +111,6 @@ export interface S3Service {
method: string,
download?: boolean,
filename?: string,
internal?: boolean,
) => Promise<string>
presignMultipart: (
bucket: string,
@@ -124,7 +123,6 @@ export interface S3Service {
export class S3StorageService implements S3Service {
private client: S3Client
private presignClient: S3Client
private bucket: string
private presignCache = new LruTtlCache<string, string>(50000)
@@ -134,7 +132,6 @@ export class S3StorageService implements S3Service {
secretAccessKey: string,
bucket: string,
region: string = 'auto',
publicEndpoint?: string,
) {
this.client = new S3Client({
region,
@@ -147,20 +144,6 @@ 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
}
@@ -359,13 +342,12 @@ 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 || ''}&internal=${internal || false}`
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}`
if (method === 'GET' && !download) {
const cached = this.presignCache.get(cacheKey)
if (cached) {
@@ -373,7 +355,6 @@ export class S3StorageService implements S3Service {
}
}
const signingClient = internal ? this.client : this.presignClient
let url: string
if (method === 'GET') {
@@ -382,19 +363,19 @@ export class S3StorageService implements S3Service {
Key: key,
ResponseContentDisposition: download ? buildContentDisposition(filename) : undefined,
})
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (method === 'PUT') {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (method === 'DELETE') {
const command = new DeleteObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(signingClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
throw new Error(`Unsupported method for presign: ${method}`)
}
@@ -424,13 +405,13 @@ export class S3StorageService implements S3Service {
UploadId: request.uploadId,
PartNumber: request.partNumber,
})
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
}
} else if (request.method === 'POST') {
if (request.uploadId) {
@@ -439,13 +420,13 @@ export class S3StorageService implements S3Service {
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
const command = new CreateMultipartUploadCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
}
} else if (request.method === 'GET') {
if (!request.uploadId) {
@@ -456,7 +437,7 @@ export class S3StorageService implements S3Service {
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (request.method === 'DELETE') {
if (!request.uploadId) {
throw new Error('Abort multipart upload requires uploadId')
@@ -466,7 +447,7 @@ export class S3StorageService implements S3Service {
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.presignClient, command, { expiresIn: expiresInSeconds })
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
throw new Error(`Unsupported method for presignMultipart: ${request.method}`)
}
@@ -485,7 +466,7 @@ export class S3StorageService implements S3Service {
}
async resolveInput(bucket: string, key: string): Promise<string> {
return this.presign(bucket, key, 'GET', false, undefined, true)
return this.presign(bucket, key, 'GET')
}
}
@@ -762,8 +743,6 @@ 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'
@@ -773,6 +752,5 @@ 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,550 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
prisma,
WorkflowTaskStatus,
WorkflowTaskType,
AssetStatus,
registerWorkflowCancel,
} from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { HTTPException } from 'hono/http-exception'
import { workflowTaskService } from './workflowTask'
describe('WorkflowTaskService', () => {
setupTestDbHooks()
it('lists workflow tasks for a team with pagination and filters', async () => {
const team1 = await prisma.team.create({
data: { name: 'Workflow Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Workflow Team 2' },
})
const project1 = await prisma.project.create({
data: { name: 'Project 1', teamId: team1.id },
})
const asset1 = await prisma.asset.create({
data: {
name: 'video1.mp4',
type: 'file',
sizeByte: 2048,
status: 'uploaded',
projectId: project1.id,
},
})
// Task 1: Team 1 direct
const task1 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
teamId: team1.id,
projectId: project1.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.completed,
},
})
// Task 2: Team 1 via project (teamId is null)
const task2 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
projectId: project1.id,
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
},
})
// Task 3: Team 2
await prisma.workflowTask.create({
data: {
assetId: 'other-asset',
teamId: team2.id,
type: WorkflowTaskType.transcode_image,
status: WorkflowTaskStatus.processing,
},
})
// 1. List all for Team 1
const listAll = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
})
expect(listAll.total).toBe(2)
expect(listAll.nodes).toHaveLength(2)
expect(listAll.nodes.map((n) => n.id)).toEqual([task2.id, task1.id]) // ordered by id desc
expect(listAll.nodes[0].fileName).toBe('video1.mp4')
expect(listAll.nodes[0].fileSize).toBe(2048)
expect(listAll.nodes[0].projectName).toBe('Project 1')
expect(listAll.nodes[0].projectId).toBe(project1.id)
expect(listAll.nodes[1].fileName).toBe('video1.mp4')
expect(listAll.nodes[1].fileSize).toBe(2048)
expect(listAll.nodes[1].projectName).toBe('Project 1')
// 2. Filter by status
const listPending = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
status: [WorkflowTaskStatus.pending],
})
expect(listPending.total).toBe(1)
expect(listPending.nodes[0].id).toBe(task2.id)
// 3. Filter by type
const listChat = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
types: [WorkflowTaskType.chat],
})
expect(listChat.total).toBe(1)
expect(listChat.nodes[0].id).toBe(task2.id)
// 4. Pagination
const page1 = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
first: 1,
})
expect(page1.nodes).toHaveLength(1)
expect(page1.nodes[0].id).toBe(task2.id)
expect(page1.pageInfo.hasNextPage).toBe(true)
const page2 = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
first: 1,
after: page1.pageInfo.endCursor!,
})
expect(page2.nodes).toHaveLength(1)
expect(page2.nodes[0].id).toBe(task1.id)
})
it('gets batch status for specific task IDs with team security', async () => {
const team1 = await prisma.team.create({
data: { name: 'Batch Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Batch Team 2' },
})
const task1 = await prisma.workflowTask.create({
data: {
assetId: 'a1',
teamId: team1.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: 'a2',
teamId: team2.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
// Query empty
const empty = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team1.id,
taskIds: [],
})
expect(empty.tasks).toEqual([])
// Query both task1 and task2 under team1
const res = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team1.id,
taskIds: [task1.id, task2.id],
})
// task2 should be excluded because it belongs to team2
expect(res.tasks).toHaveLength(1)
expect(res.tasks[0].id).toBe(task1.id)
expect(res.tasks[0].status).toBe(WorkflowTaskStatus.processing)
})
it('stops a pending or processing task successfully', async () => {
const team = await prisma.team.create({
data: { name: 'Stop Team' },
})
const pendingTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-pending',
teamId: team.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
payload: { projectId: 'p1' },
},
})
const processingTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-processing',
teamId: team.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.processing,
},
})
// Stop pending task
const stopPendingRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: pendingTask.id,
})
expect(stopPendingRes.success).toBe(true)
expect(stopPendingRes.task.status).toBe(WorkflowTaskStatus.failed)
const pendingOutput = stopPendingRes.task.output as { error: string }
expect(pendingOutput.error).toBe('Task was stopped by user')
// Stop processing task
const stopProcessingRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: processingTask.id,
})
expect(stopProcessingRes.success).toBe(true)
expect(stopProcessingRes.task.status).toBe(WorkflowTaskStatus.failed)
})
it('updates associated asset status to failed atomically when task is stopped', async () => {
const team = await prisma.team.create({
data: { name: 'Asset Stop Team' },
})
const project = await prisma.project.create({
data: { name: 'Asset Stop Project', teamId: team.id },
})
// Asset 1: currently uploaded (e.g. pending transcode)
const asset1 = await prisma.asset.create({
data: {
name: 'pending-video.mp4',
type: 'file',
status: AssetStatus.uploaded,
projectId: project.id,
media: {
duration: 120,
filesize: 1000,
frames: 3000,
imageTranscodes: [],
videoTranscodes: [],
finishedAt: '',
metadata: null,
original: null,
},
},
})
const task1 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
// Asset 2: already processed (media finished)
const asset2 = await prisma.asset.create({
data: {
name: 'completed-video.mp4',
type: 'file',
status: AssetStatus.processed,
projectId: project.id,
media: {
duration: 60,
filesize: 500,
frames: 1500,
imageTranscodes: [],
videoTranscodes: [],
finishedAt: '2026-01-01',
metadata: null,
original: null,
},
},
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: asset2.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.processing,
},
})
// Stop task 1 (pending transcode)
await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task1.id,
})
const updatedAsset1 = await prisma.asset.findUniqueOrThrow({
where: { id: asset1.id },
})
expect(updatedAsset1.status).toBe(AssetStatus.failed)
const media1 = updatedAsset1.media as PrismaJson.MediaInfo
expect(media1.duration).toBe(120) // preserved other json properties
expect(media1.filesize).toBe(1000)
expect(media1.error).toBe('Task was stopped by user')
// Stop task 2 (asset already processed)
await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task2.id,
})
const updatedAsset2 = await prisma.asset.findUniqueOrThrow({
where: { id: asset2.id },
})
// Must NOT be overwritten to failed
expect(updatedAsset2.status).toBe(AssetStatus.processed)
const media2 = updatedAsset2.media as PrismaJson.MediaInfo
expect(media2.duration).toBe(60)
expect(media2.error).toBeUndefined()
})
it('throws 400 when attempting to stop completed or failed task', async () => {
const team = await prisma.team.create({
data: { name: 'Stop Error Team' },
})
const completedTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-completed',
teamId: team.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.completed,
},
})
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: completedTask.id,
}),
).rejects.toThrow(HTTPException)
})
it('throws 404 when stopping non-existent task and 403 when task belongs to other team', async () => {
const team1 = await prisma.team.create({
data: { name: 'Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Team 2' },
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: 'asset-team2',
teamId: team2.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
// Non-existent task
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team1.id,
taskId: 'non-existent-task-id',
}),
).rejects.toThrow(HTTPException)
// Task belongs to team 2
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team1.id,
taskId: task2.id,
}),
).rejects.toThrow(HTTPException)
})
it('throws 502 and does not modify task or asset when workflow cancellation fails', async () => {
const team = await prisma.team.create({
data: { name: 'Cancel Fail Team' },
})
const project = await prisma.project.create({
data: { name: 'Cancel Fail Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'fail-cancel.mp4',
type: 'file',
status: AssetStatus.processing,
projectId: project.id,
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
registerWorkflowCancel(async () => {
throw new Error('DBOS connection failure')
})
try {
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task.id,
}),
).rejects.toMatchObject({ status: 502 })
// Verify task status was NOT changed to failed
const currentTask = await prisma.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
expect(currentTask.status).toBe(WorkflowTaskStatus.processing)
// Verify asset status was NOT changed to failed
const currentAsset = await prisma.asset.findUniqueOrThrow({
where: { id: asset.id },
})
expect(currentAsset.status).toBe(AssetStatus.processing)
} finally {
registerWorkflowCancel(async () => {})
}
})
it('throws 409 and does not overwrite status when task completes during cancellation', async () => {
const team = await prisma.team.create({
data: { name: 'Race Team' },
})
const project = await prisma.project.create({
data: { name: 'Race Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'race.mp4',
type: 'file',
status: AssetStatus.processing,
projectId: project.id,
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
// Simulate task completing in the background while cancelWorkflowTask is awaiting
registerWorkflowCancel(async () => {
await prisma.workflowTask.update({
where: { id: task.id },
data: { status: WorkflowTaskStatus.completed },
})
await prisma.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
})
})
try {
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task.id,
}),
).rejects.toMatchObject({ status: 409 })
// Verify task remains completed, not overwritten to failed
const currentTask = await prisma.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
expect(currentTask.status).toBe(WorkflowTaskStatus.completed)
// Verify asset remains processed, not overwritten to failed
const currentAsset = await prisma.asset.findUniqueOrThrow({
where: { id: asset.id },
})
expect(currentAsset.status).toBe(AssetStatus.processed)
} finally {
registerWorkflowCancel(async () => {})
}
})
it('enriches tasks with fileName, fileSize, and projectName, and handles purged assets gracefully', async () => {
const team = await prisma.team.create({
data: { name: 'Enrich Team' },
})
const project = await prisma.project.create({
data: { name: 'Enrich Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'sample_audio.mp3',
type: 'file',
sizeByte: 5242880,
status: 'uploaded',
projectId: project.id,
},
})
const taskWithAsset = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
const taskWithPurgedAsset = await prisma.workflowTask.create({
data: {
assetId: 'purged-asset-id',
teamId: team.id,
type: WorkflowTaskType.transcode_image,
status: WorkflowTaskStatus.completed,
},
})
const listRes = await workflowTaskService.listWorkflowTasks({ teamId: team.id })
expect(listRes.total).toBe(2)
const foundActive = listRes.nodes.find((n) => n.id === taskWithAsset.id)
expect(foundActive).toBeDefined()
expect(foundActive?.fileName).toBe('sample_audio.mp3')
expect(foundActive?.fileSize).toBe(5242880)
expect(foundActive?.projectName).toBe('Enrich Project')
expect(foundActive?.projectId).toBe(project.id)
const foundPurged = listRes.nodes.find((n) => n.id === taskWithPurgedAsset.id)
expect(foundPurged).toBeDefined()
expect(foundPurged?.fileName).toBeNull()
expect(foundPurged?.fileSize).toBeNull()
expect(foundPurged?.projectName).toBeNull()
// Test batch status enrichment
const batchRes = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team.id,
taskIds: [taskWithAsset.id, taskWithPurgedAsset.id],
})
expect(batchRes.tasks).toHaveLength(2)
const batchActive = batchRes.tasks.find((t) => t.id === taskWithAsset.id)
expect(batchActive?.fileName).toBe('sample_audio.mp3')
expect(batchActive?.fileSize).toBe(5242880)
expect(batchActive?.projectName).toBe('Enrich Project')
// Test stopWorkflowTask enrichment
const stopRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: taskWithAsset.id,
})
expect(stopRes.success).toBe(true)
expect(stopRes.task.fileName).toBe('sample_audio.mp3')
expect(stopRes.task.fileSize).toBe(5242880)
expect(stopRes.task.projectName).toBe('Enrich Project')
})
})
@@ -1,330 +0,0 @@
import {
prisma,
cancelWorkflowTask,
WorkflowTaskStatus,
type WorkflowTaskType,
type Prisma,
} from '@shumai/db'
import type { WorkflowTaskItem, ListWorkflowTasksResponse } from '@shumai/dtos'
import { paginateQuery } from '@shumai/core/src/pagination'
import { logger } from '@shumai/core/src/logger'
import { HTTPException } from 'hono/http-exception'
export interface ListWorkflowTasksParams {
teamId: string
status?: WorkflowTaskStatus[]
types?: WorkflowTaskType[]
first?: number
after?: string
}
export interface StopWorkflowTaskParams {
teamId: string
taskId: string
}
export interface GetBatchWorkflowTaskStatusParams {
teamId: string
taskIds: string[]
}
interface EnrichedMetadata {
fileName?: string | null
fileSize?: number | null
projectId?: string | null
projectName?: string | null
}
function mapToWorkflowTaskItem(
task: {
id: string
uid: string
teamId: string | null
projectId: string | null
assetId: string
type: WorkflowTaskType | null
status: WorkflowTaskStatus | null
payload: unknown
output: unknown
heartbeat: Date | null
inputTokens: number
outputTokens: number
model: string | null
sessionId: string | null
createdAt: Date
updatedAt: Date
},
extra?: EnrichedMetadata,
): WorkflowTaskItem {
return {
id: task.id,
uid: task.uid,
teamId: task.teamId,
projectId: extra?.projectId !== undefined ? extra.projectId : task.projectId,
projectName: extra?.projectName ?? null,
assetId: task.assetId,
fileName: extra?.fileName ?? null,
fileSize: extra?.fileSize ?? null,
type: task.type,
status: task.status,
payload: task.payload,
output: task.output,
heartbeat: task.heartbeat ? task.heartbeat.toISOString() : null,
inputTokens: task.inputTokens,
outputTokens: task.outputTokens,
model: task.model,
sessionId: task.sessionId,
createdAt: task.createdAt.toISOString(),
updatedAt: task.updatedAt.toISOString(),
}
}
export class WorkflowTaskService {
private async enrichWorkflowTasks<
T extends {
id: string
uid: string
teamId: string | null
projectId: string | null
assetId: string
type: WorkflowTaskType | null
status: WorkflowTaskStatus | null
payload: unknown
output: unknown
heartbeat: Date | null
inputTokens: number
outputTokens: number
model: string | null
sessionId: string | null
createdAt: Date
updatedAt: Date
},
>(tasks: T[]): Promise<WorkflowTaskItem[]> {
if (tasks.length === 0) {
return []
}
const assetIds = [...new Set(tasks.map((t) => t.assetId).filter(Boolean))]
const assets =
assetIds.length > 0
? await prisma.asset.findMany({
where: { id: { in: assetIds } },
select: { id: true, name: true, sizeByte: true, projectId: true },
})
: []
const assetMap = new Map(assets.map((a) => [a.id, a]))
const allProjectIds = [
...new Set(
[...tasks.map((t) => t.projectId), ...assets.map((a) => a.projectId)].filter(
(id): id is string => Boolean(id),
),
),
]
const projects =
allProjectIds.length > 0
? await prisma.project.findMany({
where: { id: { in: allProjectIds } },
select: { id: true, name: true },
})
: []
const projectMap = new Map(projects.map((p) => [p.id, p.name]))
return tasks.map((task) => {
const asset = assetMap.get(task.assetId)
const effectiveProjectId = task.projectId || asset?.projectId || null
const projectName = effectiveProjectId ? (projectMap.get(effectiveProjectId) ?? null) : null
const fileName = asset?.name ?? null
const fileSize = asset ? Number(asset.sizeByte) : null
return mapToWorkflowTaskItem(task, {
fileName,
fileSize,
projectId: effectiveProjectId,
projectName,
})
})
}
async listWorkflowTasks(params: ListWorkflowTasksParams): Promise<ListWorkflowTasksResponse> {
const teamProjects = await prisma.project.findMany({
where: { teamId: params.teamId },
select: { id: true },
})
const projectIds = teamProjects.map((p) => p.id)
const where: Prisma.WorkflowTaskWhereInput = {
OR: [
{ teamId: params.teamId },
...(projectIds.length > 0 ? [{ projectId: { in: projectIds } }] : []),
],
}
if (params.status && params.status.length > 0) {
where.status = { in: params.status }
}
if (params.types && params.types.length > 0) {
where.type = { in: params.types }
}
const result = await paginateQuery(
(skip, take) =>
prisma.workflowTask.findMany({
where,
orderBy: { id: 'desc' },
skip,
take,
}),
() => prisma.workflowTask.count({ where }),
{ first: params.first, after: params.after },
)
const nodes = await this.enrichWorkflowTasks(result.data)
return {
nodes,
pageInfo: {
hasNextPage: !!result.pageInfo.cursor,
endCursor: result.pageInfo.cursor || null,
},
total: result.pageInfo.total ?? 0,
}
}
async getBatchWorkflowTaskStatus(
params: GetBatchWorkflowTaskStatusParams,
): Promise<{ tasks: WorkflowTaskItem[] }> {
if (!params.taskIds || params.taskIds.length === 0) {
return { tasks: [] }
}
const teamProjects = await prisma.project.findMany({
where: { teamId: params.teamId },
select: { id: true },
})
const projectIds = teamProjects.map((p) => p.id)
const tasks = await prisma.workflowTask.findMany({
where: {
id: { in: params.taskIds },
OR: [
{ teamId: params.teamId },
...(projectIds.length > 0 ? [{ projectId: { in: projectIds } }] : []),
],
},
orderBy: { id: 'desc' },
})
const enriched = await this.enrichWorkflowTasks(tasks)
return { tasks: enriched }
}
async stopWorkflowTask(
params: StopWorkflowTaskParams,
): Promise<{ success: boolean; task: WorkflowTaskItem }> {
const task = await prisma.workflowTask.findUnique({
where: { id: params.taskId },
})
if (!task) {
throw new HTTPException(404, { message: 'Workflow task not found' })
}
// Verify task belongs to this team (either directly or via project)
let belongsToTeam = task.teamId === params.teamId
if (!belongsToTeam && task.projectId) {
const project = await prisma.project.findUnique({
where: { id: task.projectId },
select: { teamId: true },
})
if (project?.teamId === params.teamId) {
belongsToTeam = true
}
}
if (!belongsToTeam) {
throw new HTTPException(403, { message: 'Permission denied: Task does not belong to team' })
}
if (
task.status !== WorkflowTaskStatus.pending &&
task.status !== WorkflowTaskStatus.processing
) {
throw new HTTPException(400, {
message: `Only pending or processing tasks can be stopped. Current status: ${task.status}`,
})
}
// Notify workflow engine (DBOS) to cancel workflow execution
try {
await cancelWorkflowTask(task.id)
} catch (err) {
logger.error({ taskId: task.id, err }, 'Failed to cancel workflow task in workflow engine')
throw new HTTPException(502, {
message: `Failed to cancel workflow task in engine: ${err instanceof Error ? err.message : String(err)}`,
})
}
const errorMsg = 'Task was stopped by user'
const prevOutput =
typeof task.output === 'object' && task.output !== null
? (task.output as Record<string, unknown>)
: {}
const updated = await prisma.$transaction(async (tx) => {
const updateResult = await tx.workflowTask.updateMany({
where: {
id: task.id,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: {
...prevOutput,
error: errorMsg,
},
},
})
if (updateResult.count === 0) {
const latestTask = await tx.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
throw new HTTPException(409, {
message: `Task is no longer active. Current status: ${latestTask.status}`,
})
}
if (task.assetId) {
await tx.$executeRaw`
UPDATE "assets"
SET
"status" = 'failed'::"AssetStatus",
"media" = COALESCE("media", '{}'::jsonb) || jsonb_build_object('error', ${errorMsg}::text)
WHERE "id" = ${task.assetId}
AND "is_deleted" = false
AND "status" != 'processed'::"AssetStatus"
`
}
return await tx.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
})
logger.info({ taskId: task.id, teamId: params.teamId }, 'Workflow task stopped by user')
const [enriched] = await this.enrichWorkflowTasks([updated])
return {
success: true,
task: enriched,
}
}
}
export const workflowTaskService = new WorkflowTaskService()
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/db",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"main": "./src/index.ts",
-7
View File
@@ -360,13 +360,6 @@ declare global {
imageAnnotation?: ImageAnnotationSpec
pdfPages?: PdfPagesSpec
watermark?: WatermarkTaskPayload
recoveryAttempts?: number
}
export interface WorkflowTaskOutput {
error?: string
recoveryAttempts?: number
[key: string]: unknown
}
// ----------------------------------------------------------------------
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/dtos",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"main": "./src/index.ts",
-1
View File
@@ -28,4 +28,3 @@ export * from './kanban'
export * from './recents'
export * from './context'
export * from './media-generation'
export * from './workflowTask'
-79
View File
@@ -1,79 +0,0 @@
import { z } from 'zod'
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db/enums'
export { WorkflowTaskType, WorkflowTaskStatus }
export const workflowTaskTypeSchema = z.nativeEnum(WorkflowTaskType)
export type WorkflowTaskTypeEnum = z.infer<typeof workflowTaskTypeSchema>
export const workflowTaskStatusSchema = z.nativeEnum(WorkflowTaskStatus)
export type WorkflowTaskStatusEnum = z.infer<typeof workflowTaskStatusSchema>
export const workflowTaskItemSchema = z.object({
id: z.string(),
uid: z.string(),
teamId: z.string().nullable().optional(),
projectId: z.string().nullable().optional(),
projectName: z.string().nullable().optional(),
assetId: z.string(),
fileName: z.string().nullable().optional(),
fileSize: z.number().nullable().optional(),
type: z.nativeEnum(WorkflowTaskType).nullable().optional(),
status: z.nativeEnum(WorkflowTaskStatus).nullable().optional(),
payload: z.unknown().optional(),
output: z.unknown().optional(),
heartbeat: z.string().nullable().optional(),
inputTokens: z.number(),
outputTokens: z.number(),
model: z.string().nullable().optional(),
sessionId: z.string().nullable().optional(),
createdAt: z.string(),
updatedAt: z.string(),
})
export type WorkflowTaskItem = z.infer<typeof workflowTaskItemSchema>
export const listWorkflowTasksQuerySchema = z.object({
first: z.coerce.number().optional(),
after: z.string().optional(),
status: z
.union([z.nativeEnum(WorkflowTaskStatus), z.array(z.nativeEnum(WorkflowTaskStatus))])
.transform((val) => (Array.isArray(val) ? val : [val]))
.optional(),
types: z
.union([z.nativeEnum(WorkflowTaskType), z.array(z.nativeEnum(WorkflowTaskType))])
.transform((val) => (Array.isArray(val) ? val : [val]))
.optional(),
})
export type ListWorkflowTasksQuery = z.infer<typeof listWorkflowTasksQuerySchema>
export const listWorkflowTasksResponseSchema = z.object({
nodes: z.array(workflowTaskItemSchema),
pageInfo: z.object({
hasNextPage: z.boolean(),
endCursor: z.string().nullable(),
}),
total: z.number(),
})
export type ListWorkflowTasksResponse = z.infer<typeof listWorkflowTasksResponseSchema>
export const batchWorkflowTaskStatusSchema = z.object({
taskIds: z.array(z.string()).max(100),
})
export type BatchWorkflowTaskStatus = z.infer<typeof batchWorkflowTaskStatusSchema>
export const batchWorkflowTaskStatusResponseSchema = z.object({
tasks: z.array(workflowTaskItemSchema),
})
export type BatchWorkflowTaskStatusResponse = z.infer<typeof batchWorkflowTaskStatusResponseSchema>
export const stopWorkflowTaskResponseSchema = z.object({
success: z.boolean(),
task: workflowTaskItemSchema,
})
export type StopWorkflowTaskResponse = z.infer<typeof stopWorkflowTaskResponseSchema>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/e2e",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"dependencies": {
-134
View File
@@ -4,7 +4,6 @@ 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'
@@ -290,137 +289,4 @@ 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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/tableprinter",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode",
"version": "0.6.1",
"version": "0.5.3",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -25,7 +25,6 @@ vi.mock('@shumai/core/src/turntable/turntable', () => ({
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
putObject: vi.fn(),
downloadToFile: vi.fn(),
},
}))
@@ -121,46 +120,6 @@ 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',
@@ -367,24 +326,6 @@ 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', () => {
@@ -410,23 +351,5 @@ 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,7 +12,6 @@ vi.mock('child_process', () => ({
execFile: vi.fn(),
}))
import {
ensureLocalMediaFile,
getMediaInfoActivity,
overlayAnnotationsActivity,
renderPdfPagesActivity,
@@ -108,7 +107,6 @@ 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 () => {
@@ -220,40 +218,6 @@ 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' },
@@ -943,43 +907,14 @@ describe('Transcode Activities', () => {
})
describe('Non-retryable Error Handling', () => {
it('should throw non-retryable ApplicationFailure when downloadMediaToTmpActivity fails with ENOENT or AWS SDK NoSuchKey', async () => {
it('should throw non-retryable ApplicationFailure when downloadMediaToTmpActivity fails with ENOENT', async () => {
vi.mocked(s3Service.downloadToFile).mockRejectedValue({
name: 'NoSuchKey',
message: 'The specified key does not exist.',
code: 'ENOENT',
message: 'ENOENT: no such file or directory',
})
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,
await expect(downloadMediaToTmpActivity({ assetKey: 'missing.mp4' })).rejects.toThrowError(
/Failed to download media to tmp/,
)
})
@@ -1173,37 +1108,6 @@ 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'))
+249 -345
View File
@@ -22,19 +22,38 @@ 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)
function getActivityCancellationSignal(taskId?: string): AbortSignal | undefined {
return getLocalTaskAbortSignal(taskId)
export interface GetMediaInfoActivityParams {
assetId: string
assetKey: string
mediaType: string
}
function getErrorDetails(err: unknown): { code?: string; message: string; name?: string } {
@@ -56,46 +75,6 @@ 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 },
@@ -114,46 +93,20 @@ async function ensureAssetNotPurging(assetKey: string): Promise<void> {
}
}
export const getMediaInfoActivity = defineStep(async function getMediaInfoActivity(params: {
filePath?: string
assetKey?: string
export async function getMediaInfoActivity(params: {
filePath: 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 || params.assetKey) ||
undefined
params.proxyType || getProxyType(params.mediaType, params.filePath) || 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
@@ -192,11 +145,11 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi
let isDowngradedToAudio = false
let videoInfo: Awaited<ReturnType<typeof transcodeService.getVideoInfo>> | null = null
try {
videoInfo = await transcodeService.getVideoInfo(mediaSource)
videoInfo = await transcodeService.getVideoInfo(params.filePath)
} catch (err) {
if (err instanceof Error && err.message.includes('No video stream found')) {
try {
const audioInfo = await transcodeService.getAudioInfo(mediaSource)
const audioInfo = await transcodeService.getAudioInfo(params.filePath)
isDowngradedToAudio = true
mediaInfo.proxyType = 'audio'
mediaInfo.duration = audioInfo.duration
@@ -294,7 +247,7 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi
metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth })
}
} else if (isAudio) {
const info = await transcodeService.getAudioInfo(mediaSource)
const info = await transcodeService.getAudioInfo(params.filePath)
mediaInfo.duration = info.duration
mediaInfo.metadata = {
originalWidth: 0,
@@ -325,7 +278,7 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi
if (info.audioBitDepth !== undefined)
metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth })
} else if (isImage) {
const info = await transcodeService.getImageInfo(mediaSource)
const info = await transcodeService.getImageInfo(params.filePath)
mediaInfo.metadata = {
originalWidth: info.originalWidth,
originalHeight: info.originalHeight,
@@ -342,7 +295,7 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi
{ key: 'resolution_height', value: info.originalHeight },
)
} else if (isPdf) {
const info = await transcodeService.getPdfInfo(mediaSource)
const info = await transcodeService.getPdfInfo(params.filePath)
mediaInfo.frames = info.totalFrames
mediaInfo.metadata = {
originalWidth: info.originalWidth,
@@ -375,16 +328,8 @@ export const getMediaInfoActivity = defineStep(async function getMediaInfoActivi
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
@@ -406,7 +351,7 @@ export interface VideoActivityParams {
audioStreamIndex?: number
}
export const transcodeVideoActivity = defineStep(async function transcodeVideoActivity(
export async function transcodeVideoActivity(
params: VideoActivityParams,
): Promise<PrismaJson.VideoTranscode> {
const bucket = process.env.S3_BUCKET || 'shumai'
@@ -515,7 +460,7 @@ export const transcodeVideoActivity = defineStep(async function transcodeVideoAc
} finally {
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
}
})
}
export interface HlsActivityParams {
taskId: string
@@ -539,9 +484,7 @@ export interface HlsActivityParams {
audioStreamIndex?: number
}
export const transcodeHlsActivity = defineStep(async function transcodeHlsActivity(
params: HlsActivityParams,
): Promise<PrismaJson.HlsInfo> {
export 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')
@@ -705,7 +648,7 @@ export const transcodeHlsActivity = defineStep(async function transcodeHlsActivi
}
}
}
})
}
export interface AudioActivityParams {
taskId?: string
@@ -715,7 +658,7 @@ export interface AudioActivityParams {
audioStreamIndex?: number
}
export const transcodeAudioActivity = defineStep(async function transcodeAudioActivity(
export async function transcodeAudioActivity(
params: AudioActivityParams,
): Promise<PrismaJson.VideoTranscode> {
const bucket = process.env.S3_BUCKET || 'shumai'
@@ -793,7 +736,7 @@ export const transcodeAudioActivity = defineStep(async function transcodeAudioAc
} finally {
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile)
}
})
}
export interface ImageActivityParams {
assetKey: string
@@ -801,7 +744,7 @@ export interface ImageActivityParams {
imageSpec: PrismaJson.ImageTranscode
}
export const transcodeImageActivity = defineStep(async function transcodeImageActivity(
export async function transcodeImageActivity(
params: ImageActivityParams,
): Promise<PrismaJson.ImageTranscode> {
const bucket = process.env.S3_BUCKET || 'shumai'
@@ -864,21 +807,18 @@ export const transcodeImageActivity = defineStep(async function transcodeImageAc
} 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 const generateSpriteActivity = defineStep(async function generateSpriteActivity(
params: GenerateSpriteActivityParams,
) {
export async function generateSpriteActivity(params: GenerateSpriteActivityParams) {
const bucket = process.env.S3_BUCKET || 'shumai'
const signal = getActivityCancellationSignal(params.taskId)
if (signal?.aborted) {
@@ -896,7 +836,7 @@ export const generateSpriteActivity = defineStep(async function generateSpriteAc
// Not found
}
await ensureLocalMediaFile(params.inputKey || params.assetKey, params.filePath)
await ensureLocalMediaFile(params.assetKey, params.filePath)
const tmpDir = path.dirname(params.filePath)
const spriteFile = path.join(tmpDir, 'sprite.webp')
const posterFile = path.join(tmpDir, 'poster.webp')
@@ -989,7 +929,7 @@ export const generateSpriteActivity = defineStep(async function generateSpriteAc
if (fs.existsSync(spriteFile)) fs.unlinkSync(spriteFile)
if (fs.existsSync(posterFile)) fs.unlinkSync(posterFile)
}
})
}
export interface GeneratePdfProxyActivityParams {
teamId?: string | null
@@ -1000,11 +940,9 @@ export interface GeneratePdfProxyActivityParams {
filename: string
}
export const generatePdfProxyActivity = defineStep(async function generatePdfProxyActivity(
export 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)
@@ -1116,62 +1054,47 @@ export const generatePdfProxyActivity = defineStep(async function generatePdfPro
cause: err instanceof Error ? err : undefined,
})
}
})
}
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))
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))
if (!fs.existsSync(tmpDir)) {
fs.mkdirSync(tmpDir, { recursive: true })
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,
})
}
throw err
}
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
}
return { filePath, tmpDir }
}
return { filePath, tmpDir }
},
)
export const cleanupTmpDirActivity = defineStep(
async function cleanupTmpDirActivity(params: { tmpDir: string }): Promise<void> {
transcodeService.removeDir(params.tmpDir)
},
{ runOnCancel: true },
)
export async function cleanupTmpDirActivity(params: { tmpDir: string }): Promise<void> {
transcodeService.removeDir(params.tmpDir)
}
export interface UpdateAssetMediaActivityParams {
assetId: string
mediaInfo: PrismaJson.MediaInfo
}
export const updateAssetMediaActivity = defineStep(async function updateAssetMediaActivity(
params: UpdateAssetMediaActivityParams,
) {
export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityParams) {
const bucket = process.env.S3_BUCKET || 'shumai'
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
@@ -1203,9 +1126,9 @@ export const updateAssetMediaActivity = defineStep(async function updateAssetMed
'[updateAssetMediaActivity] Asset was deleted or pending purge before media update completed',
)
}
})
}
export const takeScreenshotsActivity = defineStep(async function takeScreenshotsActivity(params: {
export async function takeScreenshotsActivity(params: {
taskId?: string
assetKey: string
assetId: string
@@ -1257,7 +1180,7 @@ export const takeScreenshotsActivity = defineStep(async function takeScreenshots
}
throw err
}
})
}
export interface ExtractPosterActivityParams {
assetKey: string
@@ -1270,7 +1193,7 @@ export interface ExtractPosterActivityParams {
streamIndex?: number
}
export const extractPosterActivity = defineStep(async function extractPosterActivity(
export async function extractPosterActivity(
params: ExtractPosterActivityParams,
): Promise<{ poster: PrismaJson.PosterInfo }> {
const signal = params.signal || getActivityCancellationSignal(params.taskId)
@@ -1349,38 +1272,36 @@ export const extractPosterActivity = defineStep(async function extractPosterActi
} finally {
transcodeService.removeDir(tmpDir)
}
})
}
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
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,
})
}
},
)
throw err
}
}
export const renderPdfPagesActivity = defineStep(async function renderPdfPagesActivity(params: {
export async function renderPdfPagesActivity(params: {
taskId?: string
assetKey: string
assetId: string
@@ -1431,7 +1352,7 @@ export const renderPdfPagesActivity = defineStep(async function renderPdfPagesAc
}
throw err
}
})
}
export interface CreateEmbeddingTaskIfEnabledParams {
assetId: string
@@ -1439,77 +1360,75 @@ export interface CreateEmbeddingTaskIfEnabledParams {
projectId: string | null
}
export const createEmbeddingTaskIfEnabledActivity = defineStep(
async function createEmbeddingTaskIfEnabledActivity(
params: CreateEmbeddingTaskIfEnabledParams,
): Promise<void> {
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: {
project: true,
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 },
},
})
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
@@ -1517,68 +1436,66 @@ export interface CreateAutofillTaskIfEnabledParams {
projectId: string | null
}
export const createAutofillTaskIfEnabledActivity = defineStep(
async function createAutofillTaskIfEnabledActivity(
params: CreateAutofillTaskIfEnabledParams,
): Promise<void> {
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: {
project: true,
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 },
},
})
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
@@ -1589,7 +1506,7 @@ export interface TranscodeVideoChunkParams {
format?: 'video' | 'frames'
}
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
export async function transcodeVideoChunkActivity(
params: TranscodeVideoChunkParams,
): Promise<{ chunkKey: string }> {
if (!params.filePath && !params.assetKey) {
@@ -1743,15 +1660,12 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
}
}
}
})
}
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 async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
const bucket = process.env.S3_BUCKET || 'shumai'
await s3Service.deleteObject(bucket, params.key)
}
export interface Render3dModelActivityParams {
taskId: string
@@ -1788,7 +1702,7 @@ export interface Start3dRenderActivityResult {
modelMetadata?: Record<string, unknown>
}
export const start3dRenderActivity = defineStep(async function start3dRenderActivity(
export async function start3dRenderActivity(
params: Start3dRenderActivityParams,
): Promise<Start3dRenderActivityResult> {
const signal = getActivityCancellationSignal(params.taskId)
@@ -1799,8 +1713,6 @@ export const start3dRenderActivity = defineStep(async function start3dRenderActi
})
}
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')
@@ -1871,7 +1783,7 @@ export const start3dRenderActivity = defineStep(async function start3dRenderActi
nonRetryable: true,
})
}
})
}
export interface WaitFor3dVideoRenderActivityParams {
taskId: string
@@ -1886,7 +1798,7 @@ export interface WaitFor3dVideoRenderActivityResult {
videoFilePath: string
}
export const waitFor3dVideoRenderActivity = defineStep(async function waitFor3dVideoRenderActivity(
export async function waitFor3dVideoRenderActivity(
params: WaitFor3dVideoRenderActivityParams,
): Promise<WaitFor3dVideoRenderActivityResult> {
const signal = getActivityCancellationSignal(params.taskId)
@@ -1985,12 +1897,12 @@ export const waitFor3dVideoRenderActivity = defineStep(async function waitFor3dV
nonRetryable: true,
})
}
})
}
/**
* @deprecated Legacy monolithic 3D render activity. Prefer using `start3dRenderActivity` and `waitFor3dVideoRenderActivity`.
*/
export const render3dModelActivity = defineStep(async function render3dModelActivity(
export async function render3dModelActivity(
params: Render3dModelActivityParams,
): Promise<Render3dModelActivityResult> {
const tmpDir = path.dirname(params.filePath)
@@ -2018,17 +1930,16 @@ export const render3dModelActivity = defineStep(async function render3dModelActi
posterFilePath: startResult.posterFilePath,
modelMetadata: startResult.modelMetadata,
}
})
}
export interface Generate3dSpriteActivityParams {
taskId: string
assetKey: string
videoKey?: string
videoFilePath: string
spriteKey: string
}
export const generate3dSpriteActivity = defineStep(async function generate3dSpriteActivity(
export async function generate3dSpriteActivity(
params: Generate3dSpriteActivityParams,
): Promise<{ spriteKey: string }> {
const signal = getActivityCancellationSignal(params.taskId)
@@ -2039,9 +1950,6 @@ export const generate3dSpriteActivity = defineStep(async function generate3dSpri
})
}
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')
@@ -2070,17 +1978,16 @@ export const generate3dSpriteActivity = defineStep(async function generate3dSpri
nonRetryable: true,
})
}
})
}
export interface Generate3dViewsActivityParams {
taskId: string
assetKey: string
videoKey?: string
videoFilePath: string
viewsKey: string
}
export const generate3dViewsActivity = defineStep(async function generate3dViewsActivity(
export async function generate3dViewsActivity(
params: Generate3dViewsActivityParams,
): Promise<{ viewsKey: string }> {
const signal = getActivityCancellationSignal(params.taskId)
@@ -2091,9 +1998,6 @@ export const generate3dViewsActivity = defineStep(async function generate3dViews
})
}
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')
@@ -2122,4 +2026,4 @@ export const generate3dViewsActivity = defineStep(async function generate3dViews
nonRetryable: true,
})
}
})
}
+404 -412
View File
@@ -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, defineStep } from '@shumai/workflow-core'
import { ApplicationFailure } 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 const initWatermarkFileActivity = defineStep(async function initWatermarkFileActivity(
export async function initWatermarkFileActivity(
params: InitWatermarkFileParams,
): Promise<InitWatermarkFileResult> {
return await prisma.$transaction(async (tx) => {
@@ -46,12 +46,12 @@ export const initWatermarkFileActivity = defineStep(async function initWatermark
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 const initWatermarkFileActivity = defineStep(async function initWatermark
return { action: 'created' }
})
})
}
export interface WaitForWatermarkFileParams {
assetId: string
@@ -86,7 +86,7 @@ export interface WaitForWatermarkFileResult {
media?: PrismaJson.MediaInfo | null
}
export const waitForWatermarkFileActivity = defineStep(async function waitForWatermarkFileActivity(
export async function waitForWatermarkFileActivity(
params: WaitForWatermarkFileParams,
): Promise<WaitForWatermarkFileResult> {
const pollIntervalMs = 1000
@@ -113,278 +113,358 @@ export const waitForWatermarkFileActivity = defineStep(async function waitForWat
}
return { status: WatermarkFileStatus.failed }
})
}
export interface TranscodeWatermarkMediaParams {
assetId: string
watermarkConfigId: string
}
export const transcodeWatermarkMediaActivity = defineStep(
async function transcodeWatermarkMediaActivity(
params: TranscodeWatermarkMediaParams,
): Promise<PrismaJson.MediaInfo> {
const bucket = process.env.S3_BUCKET || 'shumai'
export 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 },
const watermarkConfigRecord = await prisma.watermarkConfig.findUnique({
where: { id: params.watermarkConfigId },
})
if (!watermarkConfigRecord) {
throw ApplicationFailure.create({
message: `Watermark config not found: ${params.watermarkConfigId}`,
nonRetryable: true,
})
if (!watermarkConfigRecord) {
throw ApplicationFailure.create({
message: `Watermark config not found: ${params.watermarkConfigId}`,
nonRetryable: true,
})
}
}
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: {
storageKey: true,
project: {
include: { team: true },
},
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: {
storageKey: true,
project: {
include: { team: true },
},
})
},
})
if (!asset || !asset.storageKey?.key) {
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) {
throw ApplicationFailure.create({
message: `Asset or storage key not found: ${params.assetId}`,
message: `Asset ${params.assetId} is neither video nor image`,
nonRetryable: true,
})
}
const teamSettings = asset.project?.team?.settings as PrismaJson.Settings | null
const hardwareAcceleration = teamSettings?.transcode?.hardwareAcceleration ?? 'off'
const threads = teamSettings?.transcode?.threads ?? 0
const inputKey = is3d
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
: assetKey
// 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 (is3d && !inputKey) {
throw ApplicationFailure.create({
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
nonRetryable: true,
})
}
const tmpDir = transcodeService.createTempDir('watermark-')
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
await s3Service.downloadToFile(bucket, inputKey!, rawFilePath)
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')
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 && !isImage && !is3d) {
throw ApplicationFailure.create({
message: `Asset ${params.assetId} is neither video nor image`,
nonRetryable: true,
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',
)
}
}
const inputKey = is3d
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
: assetKey
const originalMedia = asset.media as PrismaJson.MediaInfo | null
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',
)
}
}
const originalMedia = asset.media as PrismaJson.MediaInfo | null
const mediaInfo: PrismaJson.MediaInfo = {
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,
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: '',
},
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 (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',
})
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,
}
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]
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 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`)
const overlayPngPath = path.join(tmpDir, `watermarkOverlay-hls-${ladder}.png`)
fs.writeFileSync(overlayPngPath, overlayPngBuffer)
const outFileName = `${stem}-watermark-${params.watermarkConfigId}-${suffix}.mp4`
const outFilePath = path.join(tmpDir, outFileName)
await transcodeService.transcodeVideo({
const ladderDir = path.join(hlsTmpDir, ladder)
await transcodeService.transcodeHlsRendition({
inputFile: rawFilePath,
outputFile: outFilePath,
outputDir: ladderDir,
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,
@@ -394,169 +474,82 @@ export const transcodeWatermarkMediaActivity = defineStep(
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',
const targetBps = calculateEffectiveBitrateBps(
targetHeight,
targetWidth,
sourceVideoBitrate,
frameRate,
)
mediaInfo.videoTranscodes.push({
key: outputKey,
renditionSpecs.push({
resolution: ladder,
width: targetWidth,
height: targetHeight,
resolution,
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,
})
}
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 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 (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
}
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)
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)
}
}
export interface CompleteWatermarkFileParams {
assetId: string
@@ -566,31 +559,30 @@ export interface CompleteWatermarkFileParams {
shareLinkId?: string | null
}
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: {
export 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,
media: params.mediaInfo ?? undefined,
status: params.status,
},
update: {
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,
},
})
if (params.shareLinkId) {
await watermarkService.checkAndUpdateShareLinkStatus(params.shareLinkId)
}
},
{ runOnCancel: true },
)
if (params.shareLinkId) {
await watermarkService.checkAndUpdateShareLinkStatus(params.shareLinkId)
}
}
+5 -1
View File
@@ -1,5 +1,7 @@
import { WorkflowTaskType } from '@shumai/db'
import { registerWorkflow } from '@shumai/workflow-core'
import { registerActivities, registerWorkflow } from '@shumai/workflow-core'
import * as transcodeActivities from './activities/transcode'
import * as watermarkActivities from './activities/watermark'
import { transcodeVideoWorkflow } from './workflows/transcode-video'
import { transcodeImageWorkflow } from './workflows/transcode-image'
import { transcodePdfWorkflow } from './workflows/transcode-pdf'
@@ -20,6 +22,8 @@ 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'
+45 -39
View File
@@ -1,31 +1,23 @@
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
getAssetActivity,
updateAssetStatusActivity,
updateTaskStatusActivity,
executeActivity,
getActivities,
TaskQueueTranscode,
} from '@shumai/workflow-core'
import { cleanupTmpDirActivity } from '../activities/transcode'
export async function startTask(task: WorkflowTask): Promise<void> {
await updateTaskStatusActivity({
export async function getWorkerQueueAndStartTask(task: WorkflowTask): Promise<string> {
const { updateTaskStatusActivity } = getActivities()
await executeActivity(TaskQueueTranscode, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
return TaskQueueTranscode
}
/**
* @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)
export async function fetchAssetWithKey(workerQueue: string, assetId: string) {
const { getAssetActivity } = getActivities()
const asset = await executeActivity(workerQueue, getAssetActivity, assetId)
const key = asset?.storageKey?.key
if (!asset || !key || asset.status === 'pending_purge') {
throw ApplicationFailure.create({
@@ -36,38 +28,52 @@ export async function fetchAssetWithKey(
return { asset, key }
}
export async function completeTask(taskId: string, output?: Record<string, unknown>) {
await updateTaskStatusActivity({
export async function completeTask(
workerQueue: string,
taskId: string,
output?: Record<string, unknown>,
) {
const { updateTaskStatusActivity } = getActivities()
await executeActivity(workerQueue, updateTaskStatusActivity, {
taskId,
status: 'completed',
...(output ? { output } : {}),
})
}
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 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 cleanupTmpDir(tmpDir: string | undefined) {
if (tmpDir) {
export async function cleanupTmpDir(workerQueue: string, tmpDir: string | undefined) {
if (tmpDir && workerQueue) {
const { cleanupTmpDirActivity } = getActivities()
try {
await cleanupTmpDirActivity({ tmpDir })
await executeActivity(workerQueue, cleanupTmpDirActivity, { tmpDir })
} catch (cleanupErr) {
console.error('Failed to cleanup tmp dir:', cleanupErr)
}
@@ -1,31 +1,49 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { overlayImageAnnotationWorkflow } from './overlay-image-annotation'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
import { overlayAnnotationsActivity } from '../activities/transcode'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
updateTaskStatusActivity: vi.fn(),
getAssetActivity: vi.fn(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: vi.fn(),
}
})
vi.mock('../activities/transcode', () => ({
overlayAnnotationsActivity: vi.fn(),
}))
describe('overlayImageAnnotationWorkflow', () => {
const mockActivities = {
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
getAssetActivity: vi.mocked(getAssetActivity),
overlayAnnotationsActivity: vi.mocked(overlayAnnotationsActivity),
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',
}),
}
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 () => {
@@ -60,8 +78,7 @@ 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 { ApplicationFailure, getAssetActivity } from '@shumai/workflow-core'
import { overlayAnnotationsActivity } from '../activities/transcode'
import { startTask, completeTask, failTask } from './common'
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
import { getWorkerQueueAndStartTask, completeTask, failTask } from './common'
export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promise<void> {
let workerQueue = ''
try {
await startTask(task)
workerQueue = await getWorkerQueueAndStartTask(task)
const payload = task.payload
if (!payload?.imageAnnotation) {
@@ -16,7 +16,8 @@ export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promis
})
}
const asset = await getAssetActivity(task.assetId)
const { getAssetActivity, overlayAnnotationsActivity } = getActivities()
const asset = await executeActivity(workerQueue, getAssetActivity, task.assetId)
let key = asset?.storageKey?.key
if (asset?.media) {
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
@@ -32,16 +33,16 @@ export async function overlayImageAnnotationWorkflow(task: WorkflowTask): Promis
})
}
const keyWithOverlay = await overlayAnnotationsActivity({
const keyWithOverlay = await executeActivity(workerQueue, overlayAnnotationsActivity, {
assetKey: key,
assetId: asset.id,
annotations: payload.imageAnnotation.annotations || [],
annotations: payload.imageAnnotation.annotations,
})
await completeTask(task.id, { key: keyWithOverlay })
await completeTask(workerQueue, task.id, { key: keyWithOverlay })
} catch (err) {
console.error(`overlayImageAnnotationWorkflow failed for task ${task.id}:`, err)
await failTask(task.id, err)
await failTask(workerQueue, task.id, err)
throw err
}
}
@@ -1,31 +1,49 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderPdfPagesWorkflow } from './render-pdf-pages'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
import { renderPdfPagesActivity } from '../activities/transcode'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
updateTaskStatusActivity: vi.fn(),
getAssetActivity: vi.fn(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: vi.fn(),
}
})
vi.mock('../activities/transcode', () => ({
renderPdfPagesActivity: vi.fn(),
}))
describe('renderPdfPagesWorkflow', () => {
const mockActivities = {
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
getAssetActivity: vi.mocked(getAssetActivity),
renderPdfPagesActivity: vi.mocked(renderPdfPagesActivity),
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',
}),
}
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 () => {
@@ -60,8 +78,7 @@ 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 { ApplicationFailure } from '@shumai/workflow-core'
import { renderPdfPagesActivity } from '../activities/transcode'
import { startTask, fetchAssetWithKey, completeTask, failTask } from './common'
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
import { getWorkerQueueAndStartTask, fetchAssetWithKey, completeTask, failTask } from './common'
export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void> {
let workerQueue = ''
try {
await startTask(task)
workerQueue = await getWorkerQueueAndStartTask(task)
const payload = task.payload
if (!payload?.pdfPages) {
@@ -15,10 +15,11 @@ export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void>
})
}
const { asset, key } = await fetchAssetWithKey(task.assetId)
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
const { renderPdfPagesActivity } = getActivities()
const pdfKey = (asset.media as PrismaJson.MediaInfo | null)?.pdfTranscode?.key || key
const pages = await renderPdfPagesActivity({
const pages = await executeActivity(workerQueue, renderPdfPagesActivity, {
taskId: task.id,
assetKey: pdfKey,
assetId: asset.id,
@@ -28,10 +29,10 @@ export async function renderPdfPagesWorkflow(task: WorkflowTask): Promise<void>
annotations: payload.pdfPages.annotations,
})
await completeTask(task.id, { pages })
await completeTask(workerQueue, task.id, { pages })
} catch (err) {
console.error(`renderPdfPagesWorkflow failed for task ${task.id}:`, err)
await failTask(task.id, err)
await failTask(workerQueue, task.id, err)
throw err
}
}
@@ -1,31 +1,47 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { takeVideoScreenshotsWorkflow } from './take-video-screenshots'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { getAssetActivity, updateTaskStatusActivity } from '@shumai/workflow-core'
import { takeScreenshotsActivity } from '../activities/transcode'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
updateTaskStatusActivity: vi.fn(),
getAssetActivity: vi.fn(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: vi.fn(),
}
})
vi.mock('../activities/transcode', () => ({
takeScreenshotsActivity: vi.fn(),
}))
describe('takeVideoScreenshotsWorkflow', () => {
const mockActivities = {
updateTaskStatusActivity: vi.mocked(updateTaskStatusActivity),
getAssetActivity: vi.mocked(getAssetActivity),
takeScreenshotsActivity: vi.mocked(takeScreenshotsActivity),
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' }),
}
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 () => {
@@ -61,8 +77,7 @@ 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 },
@@ -134,8 +149,7 @@ 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 },
@@ -194,8 +208,7 @@ 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 { ApplicationFailure } from '@shumai/workflow-core'
import { takeScreenshotsActivity } from '../activities/transcode'
import { startTask, fetchAssetWithKey, completeTask, failTask } from './common'
import { executeActivity, getActivities, ApplicationFailure } from '@shumai/workflow-core'
import { getWorkerQueueAndStartTask, fetchAssetWithKey, completeTask, failTask } from './common'
export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<void> {
let workerQueue = ''
try {
await startTask(task)
workerQueue = await getWorkerQueueAndStartTask(task)
const payload = task.payload
if (!payload?.screenshot) {
@@ -15,7 +15,7 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
})
}
const { asset, key } = await fetchAssetWithKey(task.assetId)
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
let targetKey = key
if (asset?.media) {
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
@@ -34,7 +34,9 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
}
}
const screenshots = await takeScreenshotsActivity({
const { takeScreenshotsActivity } = getActivities()
const screenshots = await executeActivity(workerQueue, takeScreenshotsActivity, {
taskId: task.id,
assetKey: targetKey,
assetId: asset.id,
@@ -45,10 +47,10 @@ export async function takeVideoScreenshotsWorkflow(task: WorkflowTask): Promise<
annotations: payload.screenshot.annotations,
})
await completeTask(task.id, { screenshots })
await completeTask(workerQueue, task.id, { screenshots })
} catch (err) {
console.error(`takeVideoScreenshotsWorkflow failed for task ${task.id}:`, err)
await failTask(task.id, err)
await failTask(workerQueue, task.id, err)
throw err
}
}
@@ -1,63 +1,69 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcode3dWorkflow } from './transcode-3d'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
import {
getAssetActivity,
updateAssetStatusActivity,
updateTaskStatusActivity,
} from '@shumai/workflow-core'
import {
downloadMediaToTmpActivity,
start3dRenderActivity,
waitFor3dVideoRenderActivity,
generate3dSpriteActivity,
generate3dViewsActivity,
updateAssetMediaActivity,
cleanupTmpDirActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
} from '../activities/transcode'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
updateTaskStatusActivity: vi.fn(),
updateAssetStatusActivity: vi.fn(),
getAssetActivity: vi.fn(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: 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: 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),
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',
}),
}
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',
@@ -96,8 +102,7 @@ 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',
@@ -165,7 +170,6 @@ 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',
})
@@ -173,7 +177,6 @@ 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',
})
@@ -245,8 +248,7 @@ 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,33 +1,42 @@
import type { WorkflowTask } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { updateAssetStatusActivity } from '@shumai/workflow-core'
import { executeActivity, getActivities } from '@shumai/workflow-core'
import {
downloadMediaToTmpActivity,
start3dRenderActivity,
waitFor3dVideoRenderActivity,
generate3dSpriteActivity,
generate3dViewsActivity,
updateAssetMediaActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
} from '../activities/transcode'
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
getWorkerQueueAndStartTask,
fetchAssetWithKey,
completeTask,
failTask,
cleanupTmpDir,
} from './common'
export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
let tmpDir: string | undefined
let workerQueue = ''
let mediaProcessed = false
try {
await startTask(task)
workerQueue = await getWorkerQueueAndStartTask(task)
await updateAssetStatusActivity({
const {
updateAssetStatusActivity,
downloadMediaToTmpActivity,
start3dRenderActivity,
waitFor3dVideoRenderActivity,
generate3dSpriteActivity,
generate3dViewsActivity,
updateAssetMediaActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
} = getActivities()
await executeActivity(workerQueue, updateAssetStatusActivity, {
assetId: task.assetId,
status: 'processing',
})
const { asset, key } = await fetchAssetWithKey(task.assetId)
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
const download = await downloadMediaToTmpActivity({
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
assetKey: key,
})
const currentFilePath = download.filePath
@@ -40,9 +49,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 start3dRenderActivity({
const renderStart = await executeActivity(workerQueue, start3dRenderActivity, {
taskId: task.id,
teamId: task.teamId || '',
teamId: task.teamId,
assetId: asset.id,
assetKey: key,
filePath: currentFilePath,
@@ -82,24 +91,23 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
},
}
await updateAssetMediaActivity({
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
const renderVideo = await waitFor3dVideoRenderActivity({
const renderVideo = await executeActivity(workerQueue, waitFor3dVideoRenderActivity, {
taskId: task.id,
teamId: task.teamId || '',
teamId: task.teamId,
assetKey: key,
renderTaskId: renderStart.renderTaskId,
targetVideoKey: videoKey,
tmpDir,
})
await generate3dSpriteActivity({
await executeActivity(workerQueue, generate3dSpriteActivity, {
taskId: task.id,
assetKey: key,
videoKey,
videoFilePath: renderVideo.videoFilePath,
spriteKey,
})
@@ -111,10 +119,9 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
tileY: 10,
}
await generate3dViewsActivity({
await executeActivity(workerQueue, generate3dViewsActivity, {
taskId: task.id,
assetKey: key,
videoKey,
videoFilePath: renderVideo.videoFilePath,
viewsKey,
})
@@ -129,7 +136,7 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
},
]
await updateAssetMediaActivity({
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
@@ -150,35 +157,35 @@ export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
}
mediaInfo.finishedAt = new Date().toISOString()
await updateAssetMediaActivity({
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
await updateAssetStatusActivity({
await executeActivity(workerQueue, updateAssetStatusActivity, {
assetId: asset.id,
status: 'processed',
})
mediaProcessed = true
await createEmbeddingTaskIfEnabledActivity({
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
assetId: asset.id,
teamId: task.teamId,
projectId: task.projectId,
})
await createAutofillTaskIfEnabledActivity({
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
assetId: asset.id,
teamId: task.teamId,
projectId: task.projectId,
})
await completeTask(task.id)
await completeTask(workerQueue, task.id)
} catch (err) {
console.error(`transcode3dWorkflow failed for task ${task.id}:`, err)
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
throw err
} finally {
await cleanupTmpDir(tmpDir)
await cleanupTmpDir(workerQueue, tmpDir)
}
}
@@ -1,57 +1,64 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcodeImageWorkflow } from './transcode-image'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
import {
getAssetActivity,
updateAssetStatusActivity,
updateTaskStatusActivity,
} from '@shumai/workflow-core'
import {
downloadMediaToTmpActivity,
getMediaInfoActivity,
transcodeImageActivity,
updateAssetMediaActivity,
cleanupTmpDirActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
} from '../activities/transcode'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
updateTaskStatusActivity: vi.fn(),
updateAssetStatusActivity: vi.fn(),
getAssetActivity: vi.fn(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: 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: 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),
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',
}),
}
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',
@@ -87,8 +94,7 @@ 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',
@@ -105,26 +111,17 @@ 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,
@@ -188,8 +185,7 @@ 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({
@@ -207,8 +203,7 @@ describe('transcodeImageWorkflow', () => {
},
videoTranscodes: [],
imageTranscodes: [],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
})
await transcodeImageWorkflow(task)
@@ -1,39 +1,47 @@
import type { WorkflowTask } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { updateAssetStatusActivity } from '@shumai/workflow-core'
import { executeActivity, getActivities } from '@shumai/workflow-core'
import {
downloadMediaToTmpActivity,
getMediaInfoActivity,
transcodeImageActivity,
updateAssetMediaActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
} from '../activities/transcode'
import { startTask, fetchAssetWithKey, completeTask, failTask, cleanupTmpDir } from './common'
getWorkerQueueAndStartTask,
fetchAssetWithKey,
completeTask,
failTask,
cleanupTmpDir,
} from './common'
export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void> {
let tmpDir: string | undefined
let workerQueue = ''
let mediaProcessed = false
try {
await startTask(task)
workerQueue = await getWorkerQueueAndStartTask(task)
await updateAssetStatusActivity({
const {
updateAssetStatusActivity,
getMediaInfoActivity,
transcodeImageActivity,
updateAssetMediaActivity,
downloadMediaToTmpActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
} = getActivities()
await executeActivity(workerQueue, updateAssetStatusActivity, {
assetId: task.assetId,
status: 'processing',
})
const { asset, key } = await fetchAssetWithKey(task.assetId)
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
const download = await downloadMediaToTmpActivity({
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
assetKey: key,
})
const { filePath } = download
tmpDir = download.tmpDir
const spec = task.payload?.transcode || {}
const mediaInfo = await getMediaInfoActivity({
assetKey: key,
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
filePath,
assetId: asset.id,
proxyType: 'image',
@@ -57,7 +65,7 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
quality: 90,
format: 'webp',
}
const imageTranscode = await transcodeImageActivity({
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: key,
filePath,
imageSpec,
@@ -66,7 +74,7 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
}
if (spec.thumbnail && hasUsablePreview) {
const thumbTranscode = await transcodeImageActivity({
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
assetKey: key,
filePath,
imageSpec: { width: 300, height: 300, quality: 80, format: 'webp', isPreview: true },
@@ -74,35 +82,35 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
mediaInfo.thumbnail = thumbTranscode
}
await updateAssetMediaActivity({
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
await updateAssetStatusActivity({
await executeActivity(workerQueue, updateAssetStatusActivity, {
assetId: asset.id,
status: 'processed',
})
mediaProcessed = true
await createEmbeddingTaskIfEnabledActivity({
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
assetId: asset.id,
teamId: task.teamId,
projectId: task.projectId,
})
await createAutofillTaskIfEnabledActivity({
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
assetId: asset.id,
teamId: task.teamId,
projectId: task.projectId,
})
await completeTask(task.id)
await completeTask(workerQueue, task.id)
} catch (err) {
console.error(`transcodeImageWorkflow failed for task ${task.id}:`, err)
await failTask(task.id, err, mediaProcessed ? undefined : task.assetId)
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
throw err
} finally {
await cleanupTmpDir(tmpDir)
await cleanupTmpDir(workerQueue, tmpDir)
}
}
@@ -1,60 +1,67 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcodePdfWorkflow } from './transcode-pdf'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
import {
getAssetActivity,
updateAssetStatusActivity,
updateTaskStatusActivity,
} from '@shumai/workflow-core'
import {
downloadMediaToTmpActivity,
generatePdfProxyActivity,
getMediaInfoActivity,
generateSpriteActivity,
updateAssetMediaActivity,
cleanupTmpDirActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
} from '../activities/transcode'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/workflow-core')>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
updateTaskStatusActivity: vi.fn(),
updateAssetStatusActivity: vi.fn(),
getAssetActivity: vi.fn(),
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: 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: 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),
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',
}),
}
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',
@@ -95,8 +102,7 @@ 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',
@@ -113,8 +119,7 @@ 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 },
@@ -128,17 +133,8 @@ 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' }),

Some files were not shown because too many files have changed in this diff Show More