Files
shumai/packages/e2e/workflow/transcode-watermark.test.ts
T
Yiling-J 03aea2cb36 feat(sharelink): add sharelink watermark support (#270)
* feat(sharelink): add sharelink watermark support

* fix(sharelink): harden watermark feature against races, crashes, and tenant leaks

Addresses review findings on the sharelink watermark feature:

- fix(watermark): read back sharelink via transaction client so the
  updateShareLinkWatermark response reflects the just-committed state
  (global-client reads on a pooled connection miss uncommitted changes)
- fix(watermark): use prisma upsert on the config hash instead of
  find-then-create to avoid P2002 races on concurrent enables
- fix(watermark): resolve nested symlinks when walking the share tree and
  batch the walk level-by-level instead of one query per node
- fix(watermark): keep watermark tasks in flight from being purged by
  orphan-config GC (avoids FK violations in completing activities)
- fix(transcode): re-transcode stale 'processing' watermark rows instead
  of silently skipping (crash recovery); downscale embedded block images;
  use pino structured logging; drop unused any casts
- fix(api): scope watermark-template list/create to the caller's teams,
  reject teamless template creation, and make teamless templates
  read-only; validate watermark config required when enabling (400);
  map sharelink-not-found to 404
- fix(api): resolve symlink target ids once in public share children
  endpoint instead of twice per item
- refactor(db): dedicated WatermarkFileStatus enum (migration included)
- test: activity unit tests (init crash recovery, image + video transcode
  paths), concurrent upsert, nested-symlink resolution, API scoping and
  validation, e2e video watermark path

* refactor(transcode): move sharp usage out of watermark activity into transcodeService

The transcode package does not declare sharp as a dependency (only
@shumai/core does), so importing it directly in the watermark activity
broke CI typecheck for the transcode package.

- add transcodeService.renderSvgToPng, downscaleImageToPng and
  compositeOverlayToWebpFile encapsulating the sharp logic
- watermark activity now calls these methods instead of importing sharp
- activity tests mock the new methods (no sharp/real fixture needed)
- add unit tests for the new transcodeService helpers

* feat(watermark): restrict watermark transcode to existing image and video transcodes

* refactor(transcode): reuse transcodeVideo in watermark activity

* refactor(watermark): use Bun.hash instead of node crypto for watermark config hash

* refactor(watermark): move computeWatermarkConfigHash from dtos to core watermark-hash module

* refactor(api): delegate watermark DB queries from public-share route to watermarkService

* refactor(share): replace dynamic watermarkService import with static import

* feat(watermark): add waitForWatermarkFileActivity for in-flight watermark transcoding tasks

* refactor(asset): replace dynamic watermarkService import with static import

* test(watermark): harden purgeOrphanWatermarkConfigs coverage

Replace the single happy-path GC test with a dedicated suite covering:

- orphan config with proxies: purged, watermarkFiles removed, all four
  proxy keys deleted from S3 while the original key is preserved
- config still referenced by a share link is not purged
- config with pending/processing transcode_watermark tasks is not purged
  (in-flight guard), but completed tasks do not block purging
- pending tasks of other types (transcode_video) do not protect a config
- an S3 delete failure is non-fatal: remaining keys still deleted and the
  config is still purged
- mixed run: only the orphan config is purged while a referenced one
  survives (exact count assertion)

* feat(webui): add sharelink watermark editor and sidebar controls

* style(webui): enlarge watermark editor dialog and allocate 2/3 width to preview column

* fix(webui): override sm:max-w-lg in DialogContent to allow full 1400px width

* fix(webui): stop block click propagation and remove preview mode toggles

* fix(webui): store watermark block size as fraction of canvas width

The editor stored block.size in pixels (slider 10-120px, preview
fontSize: `${block.size}px`) while the SVG generator
(generateWatermarkSvg) interprets size as a fraction (0..1) of canvas
width. A 36px block therefore rendered as a ~36x-canvas glyph covering
the entire image.

- Keep backend fraction semantics (canvasWidth * size) so watermarks
  scale proportionally with output resolution across proxies
- Editor: defaults (text 5%, image 15%), slider ranges (1-12% / 2-50%)
  and number input now work in percent, storing a fraction
- Preview: scales blocks by the measured canvas width so WYSIWYG
- DTO schema: size constrained to (0..1) to enforce the contract
- Update DTO/editor tests to fraction sizes

* feat(webui): add single-row aspect ratio selector and 5 predefined background colors to watermark editor preview

* feat(webui): update aspect ratio to multi-toggle group and enable dot-grid pattern for all background colors

* fix(webui): update background swatches to distinct colors and share PRESET_BACKGROUND_OPTIONS array

* fix(webui): hide redundant absolute close button on watermark editor dialog header

* fix(transcode): skip raw video transcode when generating watermark proxies

The raw marker entry (isRaw: true) in videoTranscodes points at the
original source file and is only used to offer the 'Original' playback
option. It is not a transcoded proxy, so watermarking it produced a
redundant full-resolution transcode (the most expensive pass) plus an
unneeded S3 upload.

Skip entries with isRaw: true in transcodeWatermarkMediaActivity, and
cover the behavior with a unit regression test plus an e2e assertion
that exactly one watermark proxy is produced for a video asset.

* feat(webui): replace watermark image asset ID with 1MB file uploader

* fix(webui): correct watermark editor preview block sizing

The preview canvas width was measured in a useEffect([open]) that ran
before the Radix Dialog had mounted its content, so canvasRef.current was
still null, canvasWidthPx stayed 0, and every block silently fell back to
the hardcoded 640px width (block.size * (canvasWidthPx || 640)). A 100%
size therefore rendered at ~640px on an ~876px canvas (~72%), making the
preview smaller than the real watermarked output for both image and text
blocks.

- Measure the canvas via a ref callback (fires exactly when the node
  mounts, regardless of dialog mount timing) and keep a ResizeObserver
  attached for aspect-ratio/window changes.
- Use clientWidth (padding-box width) instead of getBoundingClientRect(),
  which includes the dialog's zoom-in-95 animation transform.
- Drop max-w-full/max-h-full on the preview <img> so logos scale up to
  the block size like the backend SVG rendering does, instead of being
  capped at their natural pixel size.

* fix(webui): keep watermark editor preview aspect ratio and restore config scroll

- Compute the preview canvas size with a JS contain-fit (ResizeObserver on the
  frame) instead of relying on CSS aspect-ratio + w-full/max-h-full, which
  broke the selected ratio on wide-and-short (or tall-and-narrow) windows.
- Add min-h-0 to the config ScrollArea so it shrinks to the column's remaining
  height instead of growing to its content height, restoring the scroll range.

* fix(webui): remove toast notification on template load

* fix(share): serve per-file watermark proxies in public share APIs

Stop gating watermark replacement on the share-link-wide watermarkStatus.
Public share endpoints now resolve each asset's own completed watermark
proxy and:

- replace videoTranscodes/imageTranscodes with the watermarked entries
  when the watermark file is completed;
- empty those arrays when no completed proxy exists yet (still
  transcoding or failed) so original, unwatermarked media is never
  exposed while a newly added file is being processed;
- leave non-video/image media (pdf, audio, ...) untouched, since they
  never receive watermark transcodes.

This removes the previous behavior where adding a file to a ready
watermark share flipped the whole share link to processing and served
original media for every file until the new transcode finished.

Adds API tests for detail/children endpoints (ready, in-flight, pdf, and
watermark-disabled cases) and a workflow E2E test for adding an asset to
an already-ready watermark sharelink.
2026-08-07 21:36:20 +08:00

468 lines
16 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import { prisma, WatermarkFileStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
import { initTranscodeWorkflows } from '@shumai/transcode'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { shareService } from '@shumai/core/src/share/share'
import { s3Service } from '@shumai/core/src/s3/s3'
import { fileURLToPath } from 'url'
import * as path from 'path'
import * as fs from 'fs'
import type { WatermarkConfigSpec } from '@shumai/dtos'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
const fixturesDir = path.resolve(currentDir, '../fixtures')
describe.each(['local', 'temporal'] as const)(
'Workflow E2E - transcodeWatermarkWorkflow (executor: %s)',
(mode) => {
setupTestDbHooks()
let transcodeWorkerPromise: Promise<void> | null = null
beforeAll(async () => {
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-watermark'
workflowService.setExecutorType(mode)
initTranscodeWorkflows()
if (mode === 'temporal') {
console.log('Starting background worker for watermark Temporal E2E tests...')
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
workflowsPath: transcodeWorkflowsPath,
})
await new Promise((resolve) => setTimeout(resolve, 2000))
} else {
console.log('Starting local workflow service polling...')
workflowService.start()
}
})
afterAll(async () => {
if (mode === 'temporal') {
console.log('Shutting down Temporal workers...')
await workflowService.shutdownWorkers()
await Promise.all([transcodeWorkerPromise].filter(Boolean))
}
workflowService.close()
vi.restoreAllMocks()
try {
await s3Service.deletePrefix('shumai-e2e-test-bucket-watermark', '')
} catch (err) {
console.error('Failed to clean up E2E storage folder:', err)
}
})
it('should generate watermark proxy for an image asset and update sharelink status to ready', async () => {
// 1. Seed Database
const team = await prisma.team.create({
data: { name: 'E2E Watermark Team' },
})
const projectFolder = await prisma.asset.create({
data: { name: 'root', type: 'root', status: 'processed' },
})
const project = await prisma.project.create({
data: { name: 'E2E Watermark Project', teamId: team.id, rootFolderId: projectFolder.id },
})
const storageKey = await prisma.storageKey.create({
data: { key: 'files/e2e-watermark-asset/original.png' },
})
const sampleImagePath = path.join(fixturesDir, 'sample.png')
let sampleBuffer: Buffer
if (fs.existsSync(sampleImagePath)) {
sampleBuffer = fs.readFileSync(sampleImagePath)
} else {
// Minimal 1x1 PNG fallback if fixture is missing
sampleBuffer = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64',
)
}
await s3Service.putObject(
'shumai-e2e-test-bucket-watermark',
storageKey.key,
sampleBuffer,
sampleBuffer.length,
'image/png',
)
const asset = await prisma.asset.create({
data: {
name: 'sample.png',
type: 'file',
mediaType: 'image/png',
status: 'processed',
projectId: project.id,
storageKeyId: storageKey.id,
media: {
duration: 0,
filesize: sampleBuffer.length,
frames: 0,
proxyType: 'image',
imageTranscodes: [
{ key: storageKey.key, width: 100, height: 100, quality: 90, format: 'webp' },
],
videoTranscodes: [],
videoPreview: { width: 100, height: 100 },
finishedAt: new Date().toISOString(),
metadata: {
originalWidth: 100,
originalHeight: 100,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: 0,
startTimecode: '00:00:00:00',
hasAudio: false,
format: {},
},
original: {
key: storageKey.key,
downloadUrl: '',
filesizeInBytes: sampleBuffer.length,
codec: '',
},
},
},
})
const shareLink = await shareService.createShareLink(project.id, {
name: 'Public Watermarked Share',
})
await shareService.addAssetToShare(shareLink.id, { assetIds: [asset.id] })
const watermarkConfig: WatermarkConfigSpec = {
blocks: [
{
id: 'b1',
type: 'text',
x: 0.5,
y: 0.5,
opacity: 0.5,
rotation: 0,
text: 'CONFIDENTIAL E2E',
size: 0.2,
color: '#FF0000',
},
],
}
// 2. Enable Watermark on Sharelink
const updatedShare = await watermarkService.updateShareLinkWatermark(
shareLink.id,
true,
watermarkConfig,
)
expect(updatedShare.watermarkStatus).toBe('processing')
// 3. Poll for WorkflowTask completion & ShareLink status 'ready'
let finalShare = await shareService.getShareLink(shareLink.id)
const startTime = Date.now()
while (finalShare.watermarkStatus === 'processing' && Date.now() - startTime < 15000) {
await new Promise((resolve) => setTimeout(resolve, 500))
finalShare = await shareService.getShareLink(shareLink.id)
}
expect(finalShare.watermarkStatus).toBe('ready')
// Verify WatermarkFile record was created and completed
const watermarkFile = await prisma.watermarkFile.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId: {
assetId: asset.id,
watermarkConfigId: updatedShare.watermarkConfigId!,
},
},
})
expect(watermarkFile).toBeDefined()
expect(watermarkFile?.status).toBe(WatermarkFileStatus.completed)
expect(watermarkFile?.media).toBeDefined()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((watermarkFile?.media as any)?.imageTranscodes?.length).toBeGreaterThan(0)
})
it('should generate watermark proxy for a video asset and update sharelink status to ready', async () => {
// 1. Seed Database
const team = await prisma.team.create({
data: { name: 'E2E Watermark Video Team' },
})
const projectFolder = await prisma.asset.create({
data: { name: 'root', type: 'root', status: 'processed' },
})
const project = await prisma.project.create({
data: {
name: 'E2E Watermark Video Project',
teamId: team.id,
rootFolderId: projectFolder.id,
},
})
const storageKey = await prisma.storageKey.create({
data: { key: 'files/e2e-watermark-video/original.mp4' },
})
const videoPath = path.join(fixturesDir, 'small.mp4')
const videoBuffer = fs.readFileSync(videoPath)
await s3Service.putObject(
'shumai-e2e-test-bucket-watermark',
storageKey.key,
videoBuffer,
videoBuffer.length,
'video/mp4',
)
const asset = await prisma.asset.create({
data: {
name: 'small.mp4',
type: 'file',
mediaType: 'video/mp4',
status: 'processed',
projectId: project.id,
storageKeyId: storageKey.id,
media: {
duration: 1,
filesize: videoBuffer.length,
frames: 30,
proxyType: 'video',
imageTranscodes: [],
videoTranscodes: [
{ key: storageKey.key, width: 640, height: 360, resolution: '360p' },
// Raw marker entry (as produced by transcodeVideoWorkflow) — must
// not be watermarked.
{ key: storageKey.key, width: 640, height: 360, isRaw: true },
],
videoPreview: { width: 640, height: 360 },
finishedAt: new Date().toISOString(),
metadata: {
originalWidth: 640,
originalHeight: 360,
duration: 1,
bitRate: 0,
frameRate: 30,
totalFrames: 30,
startTimecode: '00:00:00:00',
hasAudio: false,
format: {},
},
original: {
key: storageKey.key,
downloadUrl: '',
filesizeInBytes: videoBuffer.length,
codec: '',
},
},
},
})
const shareLink = await shareService.createShareLink(project.id, {
name: 'Public Watermarked Video Share',
})
await shareService.addAssetToShare(shareLink.id, { assetIds: [asset.id] })
const watermarkConfig: WatermarkConfigSpec = {
blocks: [
{
id: 'b1',
type: 'text',
x: 0.5,
y: 0.5,
opacity: 0.5,
rotation: 0,
text: 'CONFIDENTIAL VIDEO',
size: 0.2,
color: '#FF0000',
},
],
}
// 2. Enable Watermark on Sharelink
const updatedShare = await watermarkService.updateShareLinkWatermark(
shareLink.id,
true,
watermarkConfig,
)
expect(updatedShare.watermarkStatus).toBe('processing')
// 3. Poll for WorkflowTask completion & ShareLink status 'ready'
let finalShare = await shareService.getShareLink(shareLink.id)
const startTime = Date.now()
while (finalShare.watermarkStatus === 'processing' && Date.now() - startTime < 30000) {
await new Promise((resolve) => setTimeout(resolve, 500))
finalShare = await shareService.getShareLink(shareLink.id)
}
expect(finalShare.watermarkStatus).toBe('ready')
const watermarkFile = await prisma.watermarkFile.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId: {
assetId: asset.id,
watermarkConfigId: updatedShare.watermarkConfigId!,
},
},
})
expect(watermarkFile).toBeDefined()
expect(watermarkFile?.status).toBe(WatermarkFileStatus.completed)
expect(watermarkFile?.media).toBeDefined()
// Only the transcoded proxy should be watermarked — the raw marker entry
// (isRaw: true) must be skipped, so exactly one watermark proxy is produced.
const mediaInfo = watermarkFile?.media as PrismaJson.MediaInfo | null
expect(mediaInfo?.videoTranscodes?.length).toBe(1)
expect(mediaInfo?.videoTranscodes?.[0].resolution).toBe('360p')
})
it('should watermark a newly added asset after the sharelink is already ready', async () => {
// 1. Seed Database
const team = await prisma.team.create({
data: { name: 'E2E Watermark Team' },
})
const projectFolder = await prisma.asset.create({
data: { name: 'root', type: 'root', status: 'processed' },
})
const project = await prisma.project.create({
data: { name: 'E2E Watermark Project', teamId: team.id, rootFolderId: projectFolder.id },
})
const readSampleImage = (): Buffer => {
const sampleImagePath = path.join(fixturesDir, 'sample.png')
if (fs.existsSync(sampleImagePath)) {
return fs.readFileSync(sampleImagePath)
}
// Minimal 1x1 PNG fallback if fixture is missing
return Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64',
)
}
const createImageAsset = async (key: string, name: string) => {
const buffer = readSampleImage()
const storageKey = await prisma.storageKey.create({ data: { key } })
await s3Service.putObject(
'shumai-e2e-test-bucket-watermark',
key,
buffer,
buffer.length,
'image/png',
)
return await prisma.asset.create({
data: {
name,
type: 'file',
mediaType: 'image/png',
status: 'processed',
projectId: project.id,
storageKeyId: storageKey.id,
media: {
duration: 0,
filesize: buffer.length,
frames: 0,
proxyType: 'image',
imageTranscodes: [{ key, width: 100, height: 100, quality: 90, format: 'webp' }],
videoTranscodes: [],
videoPreview: { width: 100, height: 100 },
finishedAt: new Date().toISOString(),
metadata: {
originalWidth: 100,
originalHeight: 100,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: 0,
startTimecode: '00:00:00:00',
hasAudio: false,
format: {},
},
original: {
key,
downloadUrl: '',
filesizeInBytes: buffer.length,
codec: '',
},
},
},
})
}
const assetA = await createImageAsset('files/e2e-add-after-ready/a.png', 'a.png')
const shareLink = await shareService.createShareLink(project.id, {
name: 'Public Watermarked Share',
})
await shareService.addAssetToShare(shareLink.id, { assetIds: [assetA.id] })
const watermarkConfig: WatermarkConfigSpec = {
blocks: [
{
id: 'b1',
type: 'text',
x: 0.5,
y: 0.5,
opacity: 0.5,
rotation: 0,
text: 'CONFIDENTIAL E2E',
size: 0.2,
color: '#FF0000',
},
],
}
// 2. Enable Watermark on Sharelink and wait for initial 'ready'
const updatedShare = await watermarkService.updateShareLinkWatermark(
shareLink.id,
true,
watermarkConfig,
)
expect(updatedShare.watermarkStatus).toBe('processing')
let share = await shareService.getShareLink(shareLink.id)
let startTime = Date.now()
while (share.watermarkStatus === 'processing' && Date.now() - startTime < 30000) {
await new Promise((resolve) => setTimeout(resolve, 500))
share = await shareService.getShareLink(shareLink.id)
}
expect(share.watermarkStatus).toBe('ready')
expect(share.watermarkConfigId).toBe(updatedShare.watermarkConfigId)
// 3. Add a NEW asset to the ready sharelink
const assetB = await createImageAsset('files/e2e-add-after-ready/b.png', 'b.png')
await shareService.addAssetToShare(shareLink.id, { assetIds: [assetB.id] })
// 4. Status flips back to 'processing' while the new asset is transcoded
share = await shareService.getShareLink(shareLink.id)
expect(share.watermarkStatus).toBe('processing')
// 5. Poll until the sharelink is 'ready' again
startTime = Date.now()
while (share.watermarkStatus === 'processing' && Date.now() - startTime < 30000) {
await new Promise((resolve) => setTimeout(resolve, 500))
share = await shareService.getShareLink(shareLink.id)
}
expect(share.watermarkStatus).toBe('ready')
// 6. Both assets now have completed watermark files
for (const asset of [assetA, assetB]) {
const wf = await prisma.watermarkFile.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId: {
assetId: asset.id,
watermarkConfigId: updatedShare.watermarkConfigId!,
},
},
})
expect(wf).toBeDefined()
expect(wf?.status).toBe(WatermarkFileStatus.completed)
}
})
},
)