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.
This commit is contained in:
Yiling-J
2026-08-07 21:36:20 +08:00
committed by GitHub
parent 0a31659588
commit 03aea2cb36
148 changed files with 13590 additions and 120 deletions
@@ -0,0 +1,464 @@
import { prisma, WatermarkFileStatus } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { setupTestDbHooks } from '@shumai/db/test'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import {
initWatermarkFileActivity,
waitForWatermarkFileActivity,
transcodeWatermarkMediaActivity,
completeWatermarkFileActivity,
} from './watermark'
import * as fs from 'fs'
import * as path from 'path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('child_process', () => ({
execFile: vi.fn(
(_cmd: string, args: string[], cb: (err: unknown, stdout: string, stderr: string) => void) => {
const outFile = args[args.length - 1]
if (outFile && typeof outFile === 'string') {
try {
fs.writeFileSync(outFile, 'fake-transcoded-output')
} catch {
// ignore directory creation errors in mock
}
}
cb(null, '', '')
},
),
}))
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
putObject: vi.fn(),
presign: vi.fn(),
downloadToFile: vi.fn().mockImplementation(async (_b, _k, dest) => {
fs.writeFileSync(dest, 'fake-raw')
}),
downloadMediaToTmp: vi.fn().mockImplementation(async () => ({
filePath: '/tmp/raw-file',
tmpDir: '/tmp',
})),
deleteObject: vi.fn(),
},
}))
vi.mock('@shumai/core/src/transcode/transcode', () => ({
transcodeService: {
getVideoInfo: vi.fn(),
getImageInfo: vi.fn(),
createTempDir: vi.fn().mockReturnValue('/tmp'),
removeDir: vi.fn(),
renderSvgToPng: vi.fn().mockResolvedValue(Buffer.from('fake-overlay-png')),
downscaleImageToPng: vi.fn().mockResolvedValue({
buffer: Buffer.from('fake-block-png'),
width: 32,
height: 32,
}),
compositeOverlayToWebpFile: vi.fn().mockImplementation(async (_in, _overlay, out) => {
fs.writeFileSync(out, 'fake-webp')
}),
transcodeVideo: vi.fn().mockImplementation(async (params) => {
fs.writeFileSync(params.outputFile, 'fake-mp4')
}),
},
}))
describe('Watermark Activities', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
describe('initWatermarkFileActivity', () => {
async function seedAssetAndConfig() {
const asset = await prisma.asset.create({
data: { name: 'wm-target.png', type: 'file', status: 'processed' },
})
const config = await prisma.watermarkConfig.create({
data: {
hash: 'init-hash-' + Math.random(),
config: { blocks: [] },
},
})
return { asset, config }
}
it('creates a processing row when none exists', async () => {
const { asset, config } = await seedAssetAndConfig()
const res = await initWatermarkFileActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(res.action).toBe('created')
const row = await prisma.watermarkFile.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId: {
assetId: asset.id,
watermarkConfigId: config.id,
},
},
})
expect(row?.status).toBe(WatermarkFileStatus.processing)
})
it('returns completed action when a completed watermark file exists', async () => {
const { asset, config } = await seedAssetAndConfig()
await prisma.watermarkFile.create({
data: {
assetId: asset.id,
watermarkConfigId: config.id,
status: WatermarkFileStatus.completed,
},
})
const res = await initWatermarkFileActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(res.action).toBe('completed')
})
it('returns processing action when a processing row exists', async () => {
const { asset, config } = await seedAssetAndConfig()
await prisma.watermarkFile.create({
data: {
assetId: asset.id,
watermarkConfigId: config.id,
status: WatermarkFileStatus.processing,
},
})
const res = await initWatermarkFileActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(res.action).toBe('processing')
})
it('returns failed action when a failed row exists', async () => {
const { asset, config } = await seedAssetAndConfig()
await prisma.watermarkFile.create({
data: {
assetId: asset.id,
watermarkConfigId: config.id,
status: WatermarkFileStatus.failed,
},
})
const res = await initWatermarkFileActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(res.action).toBe('failed')
})
it('waits for watermark file completion in waitForWatermarkFileActivity', async () => {
const { asset, config } = await seedAssetAndConfig()
const wf = await prisma.watermarkFile.create({
data: {
assetId: asset.id,
watermarkConfigId: config.id,
status: WatermarkFileStatus.processing,
},
})
setTimeout(async () => {
await prisma.watermarkFile.update({
where: { id: wf.id },
data: { status: WatermarkFileStatus.completed },
})
}, 50)
const res = await waitForWatermarkFileActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(res.status).toBe(WatermarkFileStatus.completed)
})
})
describe('transcodeWatermarkMediaActivity', () => {
const bucket = process.env.S3_BUCKET || 'shumai'
async function seedAsset(name: string, mediaType: string, key: string, proxyType: string) {
const storageKey = await prisma.storageKey.create({ data: { key } })
return prisma.asset.create({
data: {
name,
type: 'file',
mediaType,
status: 'processed',
storageKeyId: storageKey.id,
media: {
duration: 0,
filesize: 0,
frames: 0,
proxyType,
videoTranscodes: [{ key, width: 100, height: 100, resolution: '100p' }],
imageTranscodes: [{ key, width: 100, height: 100, quality: 90, format: 'webp' }],
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: 0,
codec: '',
},
} as PrismaJson.MediaInfo,
},
})
}
async function seedConfig() {
return prisma.watermarkConfig.create({
data: {
config: {
blocks: [
{
id: 'b1',
type: 'text',
x: 0.5,
y: 0.5,
opacity: 0.5,
rotation: 0,
text: 'TEST WM',
size: 0.2,
color: '#FF0000',
},
],
},
hash: 'test-hash-' + Math.random(),
},
})
}
it('produces a watermarked webp proxy for an image asset', async () => {
const assetKey = 'files/e2e-wm/test.png'
const asset = await seedAsset('test.png', 'image/png', assetKey, 'image')
const config = await seedConfig()
vi.mocked(transcodeService.getImageInfo).mockResolvedValue({
originalWidth: 100,
originalHeight: 100,
duration: 0,
bitRate: 0,
frameRate: 0,
totalFrames: 0,
hasAudio: false,
mimeType: 'image/png',
})
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
// compositeOverlayToWebpFile is mocked, but the activity stats the output
// file afterwards, so pre-create it at the expected path.
const outFileName = `test-watermark-${config.id}-100x100.webp`
const outFilePath = path.join('/tmp', outFileName)
fs.writeFileSync(outFilePath, Buffer.from('fake webp'))
const media = await transcodeWatermarkMediaActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(media.proxyType).toBe('image')
expect(media.imageTranscodes?.length).toBeGreaterThan(0)
expect(media.imageTranscodes?.[0].key).toContain('watermark-')
expect(transcodeService.renderSvgToPng).toHaveBeenCalled()
expect(transcodeService.compositeOverlayToWebpFile).toHaveBeenCalledWith(
expect.stringContaining('test.png'),
Buffer.from('fake-overlay-png'),
outFilePath,
100,
100,
)
expect(s3Service.putObject).toHaveBeenCalledWith(
bucket,
expect.stringContaining('watermark-'),
expect.anything(),
expect.any(Number),
'image/webp',
)
fs.rmSync(outFilePath, { force: true })
})
it('skips the raw (isRaw) video transcode when generating watermark proxies', async () => {
const assetKey = 'files/e2e-wm/raw-video.mp4'
const asset = await seedAsset('raw-video.mp4', 'video/mp4', assetKey, 'video')
const config = await seedConfig()
// Simulate the media state produced by transcodeVideoWorkflow: a
// transcoded proxy plus a raw marker entry pointing at the original file.
await prisma.asset.update({
where: { id: asset.id },
data: {
media: {
...(asset.media as PrismaJson.MediaInfo),
videoTranscodes: [
{ key: assetKey, width: 100, height: 100, resolution: '100p' },
{ key: assetKey, width: 1920, height: 1080, isRaw: true },
],
},
},
})
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
bitRate: 1000,
frameRate: 30,
totalFrames: 300,
startTimecode: '00:00:00:00',
hasAudio: true,
mimeType: 'video/mp4',
})
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
// The ffmpeg execFile call is mocked, but the activity stats the output
// file afterwards, so pre-create both expected output paths.
const stem = 'raw-video'
const configId = config.id
const proxyOutFilePath = path.join('/tmp', `${stem}-watermark-${configId}-100p.mp4`)
const rawOutFilePath = path.join('/tmp', `${stem}-watermark-${configId}-1080p.mp4`)
fs.writeFileSync(proxyOutFilePath, Buffer.from('fake mp4'))
fs.writeFileSync(rawOutFilePath, Buffer.from('fake mp4'))
try {
const media = await transcodeWatermarkMediaActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(media.proxyType).toBe('video')
// Only the transcoded proxy should be watermarked, never the raw original.
expect(transcodeService.transcodeVideo).toHaveBeenCalledTimes(1)
expect(media.videoTranscodes).toHaveLength(1)
expect(media.videoTranscodes?.[0].resolution).toBe('100p')
expect(media.videoTranscodes?.[0].key).toContain('watermark-')
} finally {
fs.rmSync(proxyOutFilePath, { force: true })
fs.rmSync(rawOutFilePath, { force: true })
}
})
it('produces a watermarked mp4 proxy for a video asset (ffmpeg path)', async () => {
const assetKey = 'files/e2e-wm/video.mp4'
const asset = await seedAsset('video.mp4', 'video/mp4', assetKey, 'video')
const config = await seedConfig()
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
bitRate: 1000,
frameRate: 30,
totalFrames: 300,
startTimecode: '00:00:00:00',
hasAudio: true,
mimeType: 'video/mp4',
})
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
// The ffmpeg execFile call is mocked, but the activity stats the output
// file afterwards, so pre-create it at the expected path.
const stem = 'video'
const configId = config.id
const outFilePath = path.join('/tmp', `${stem}-watermark-${configId}-100p.mp4`)
fs.writeFileSync(outFilePath, Buffer.from('fake mp4'))
const media = await transcodeWatermarkMediaActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(media.proxyType).toBe('video')
expect(media.videoTranscodes?.length).toBeGreaterThan(0)
expect(media.videoTranscodes?.[0].key).toContain('watermark-')
expect(s3Service.putObject).toHaveBeenCalledWith(
bucket,
expect.stringContaining('watermark-'),
expect.anything(),
expect.any(Number),
'video/mp4',
)
fs.rmSync(outFilePath, { force: true })
})
})
describe('completeWatermarkFileActivity', () => {
it('upserts a completed watermark file with media', async () => {
const asset = await prisma.asset.create({
data: { name: 'wm-complete.png', type: 'file', status: 'processed' },
})
const config = await prisma.watermarkConfig.create({
data: {
hash: 'complete-hash-' + Math.random(),
config: { blocks: [] },
},
})
const media: PrismaJson.MediaInfo = {
duration: 0,
filesize: 0,
frames: 0,
proxyType: 'image',
imageTranscodes: [
{ key: 'files/x/out.webp', 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: 'files/x/original.png',
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
},
}
await completeWatermarkFileActivity({
assetId: asset.id,
watermarkConfigId: config.id,
mediaInfo: media,
status: WatermarkFileStatus.completed,
})
const row = await prisma.watermarkFile.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId: {
assetId: asset.id,
watermarkConfigId: config.id,
},
},
})
expect(row?.status).toBe(WatermarkFileStatus.completed)
expect(row?.media).toBeDefined()
})
})
})
@@ -0,0 +1,400 @@
import { prisma, WatermarkFileStatus } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import {
generateWatermarkSvg,
RenderBlockImageData,
} from '@shumai/core/src/watermark/watermark-svg'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { logger } from '@shumai/core/src/logger'
import { stemFromKey } from '@shumai/core/src/utils/filename'
import { ApplicationFailure } from '@temporalio/activity'
import * as path from 'path'
import * as fs from 'fs'
import { ulid } from 'ulid'
import type { WatermarkConfigSpec, WatermarkBlockImage } from '@shumai/dtos'
// Max dimension for watermark block images embedded into the SVG overlay.
// Bounding this keeps the SVG (and its base64 payload) small for large logos.
const MAX_BLOCK_IMAGE_DIMENSION = 1024
export interface InitWatermarkFileParams {
assetId: string
watermarkConfigId: string
}
export type InitWatermarkFileAction = 'created' | 'completed' | 'processing' | 'failed'
export interface InitWatermarkFileResult {
action: InitWatermarkFileAction
media?: PrismaJson.MediaInfo | null
}
export async function initWatermarkFileActivity(
params: InitWatermarkFileParams,
): Promise<InitWatermarkFileResult> {
return await prisma.$transaction(async (tx) => {
const rows = await tx.$queryRaw<
Array<{
id: string
status: WatermarkFileStatus
media: PrismaJson.MediaInfo | null
}>
>`
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]
if (existing.status === WatermarkFileStatus.completed) {
return { action: 'completed', media: existing.media }
}
if (existing.status === WatermarkFileStatus.failed) {
return { action: 'failed' }
}
return { action: 'processing' }
}
await tx.watermarkFile.create({
data: {
assetId: params.assetId,
watermarkConfigId: params.watermarkConfigId,
status: WatermarkFileStatus.processing,
},
})
return { action: 'created' }
})
}
export interface WaitForWatermarkFileParams {
assetId: string
watermarkConfigId: string
}
export interface WaitForWatermarkFileResult {
status: WatermarkFileStatus
media?: PrismaJson.MediaInfo | null
}
export async function waitForWatermarkFileActivity(
params: WaitForWatermarkFileParams,
): Promise<WaitForWatermarkFileResult> {
const pollIntervalMs = 1000
const maxWaitMs = 600000 // 10 minutes timeout
const startTime = Date.now()
while (Date.now() - startTime < maxWaitMs) {
const wf = await prisma.watermarkFile.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId: {
assetId: params.assetId,
watermarkConfigId: params.watermarkConfigId,
},
},
})
if (wf && wf.status !== WatermarkFileStatus.processing) {
return { status: wf.status, media: wf.media }
}
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs))
}
return { status: WatermarkFileStatus.failed }
}
export interface TranscodeWatermarkMediaParams {
assetId: string
watermarkConfigId: string
}
export async function transcodeWatermarkMediaActivity(
params: TranscodeWatermarkMediaParams,
): Promise<PrismaJson.MediaInfo> {
const bucket = process.env.S3_BUCKET || 'shumai'
const watermarkConfigRecord = await prisma.watermarkConfig.findUnique({
where: { id: params.watermarkConfigId },
})
if (!watermarkConfigRecord) {
throw ApplicationFailure.create({
message: `Watermark config not found: ${params.watermarkConfigId}`,
nonRetryable: true,
})
}
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: { storageKey: true },
})
if (!asset || !asset.storageKey?.key) {
throw ApplicationFailure.create({
message: `Asset or storage key not found: ${params.assetId}`,
nonRetryable: true,
})
}
// 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-')
const rawFilePath = path.join(tmpDir, path.basename(assetKey))
try {
await s3Service.downloadToFile(bucket, assetKey, rawFilePath)
const isVideo =
asset.mediaType?.startsWith('video/') ||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video'
const isImage =
asset.mediaType?.startsWith('image/') ||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image'
let originalWidth = 1920
let originalHeight = 1080
let duration = 0
let frameRate = 30
let totalFrames = 0
let startTimecode = '00:00:00:00'
let hasAudio = false
if (isVideo) {
const info = await transcodeService.getVideoInfo(rawFilePath)
originalWidth = info.originalWidth
originalHeight = info.originalHeight
duration = info.duration
frameRate = info.frameRate
totalFrames = info.totalFrames
startTimecode = info.startTimecode || '00:00:00:00'
hasAudio = info.hasAudio
} else if (isImage) {
const info = await transcodeService.getImageInfo(rawFilePath)
originalWidth = info.originalWidth
originalHeight = info.originalHeight
} else {
throw ApplicationFailure.create({
message: `Asset ${params.assetId} is neither video nor image`,
nonRetryable: true,
})
}
// 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 = {
duration,
filesize: 0,
frames: totalFrames,
proxyType: isVideo ? 'video' : 'image',
imageTranscodes: [],
videoTranscodes: [],
finishedAt: new Date().toISOString(),
metadata: {
originalWidth,
originalHeight,
duration,
bitRate: 0,
frameRate,
totalFrames,
startTimecode,
hasAudio,
format: {},
},
original: {
key: assetKey,
downloadUrl: '',
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) {
const originalTranscodes = originalMedia?.videoTranscodes || []
let totalSize = 0
for (let i = 0; i < originalTranscodes.length; i++) {
const vt = originalTranscodes[i]
// Skip the raw marker entry (points at the original file) — it is not a
// transcoded proxy, so there is nothing to watermark (and transcoding
// the original at full resolution would be needlessly expensive).
if (vt.isRaw) continue
const targetWidth = vt.width || originalWidth
const targetHeight = vt.height || originalHeight
const resolution = vt.resolution || `${targetHeight}p`
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}-${resolution}.mp4`
const outFilePath = path.join(tmpDir, outFileName)
await transcodeService.transcodeVideo({
inputFile: rawFilePath,
outputFile: outFilePath,
width: targetWidth,
height: targetHeight,
disableAudio: !hasAudio,
overlayFile: overlayPngPath,
})
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,
})
}
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
watermarkConfigId: string
mediaInfo?: PrismaJson.MediaInfo | null
status: WatermarkFileStatus
shareLinkId?: string | null
}
export async function completeWatermarkFileActivity(
params: CompleteWatermarkFileParams,
): Promise<void> {
await prisma.watermarkFile.upsert({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId: {
assetId: params.assetId,
watermarkConfigId: params.watermarkConfigId,
},
},
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)
}
}
+6
View File
@@ -1,12 +1,14 @@
import { WorkflowTaskType } from '@shumai/db'
import { registerActivities, registerWorkflow } from '@shumai/workflow-core'
import * as transcodeActivities from './activities/transcode'
import * as watermarkActivities from './activities/watermark'
import { transcodeVideoWorkflow } from './workflows/transcode-video'
import { transcodeImageWorkflow } from './workflows/transcode-image'
import { transcodePdfWorkflow } from './workflows/transcode-pdf'
import { renderPdfPagesWorkflow } from './workflows/render-pdf-pages'
import { takeVideoScreenshotsWorkflow } from './workflows/take-video-screenshots'
import { overlayImageAnnotationWorkflow } from './workflows/overlay-image-annotation'
import { transcodeWatermarkWorkflow } from './workflows/transcode-watermark'
import { transcodeMedia } from './workflows/transcode'
export function initTranscodeWorkflows() {
@@ -17,9 +19,13 @@ export function initTranscodeWorkflows() {
registerWorkflow(WorkflowTaskType.transcode_pdf_pages, renderPdfPagesWorkflow)
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
registerWorkflow(WorkflowTaskType.transcode_watermark, transcodeWatermarkWorkflow)
registerActivities(transcodeActivities)
registerActivities(watermarkActivities)
}
export * from './transcoder'
export * from './workflows/transcode'
export * from './workflows/transcode-watermark'
export * from './activities/transcode'
export * from './activities/watermark'
@@ -0,0 +1,110 @@
import type { WorkflowTask } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { executeActivity, getActivities } from '@shumai/workflow-core'
import { ApplicationFailure } from '@temporalio/workflow'
import { getWorkerQueueAndStartTask, completeTask, failTask } from './common'
export async function transcodeWatermarkWorkflow(task: WorkflowTask): Promise<void> {
let workerQueue = ''
const watermarkConfigId = task.payload?.watermark?.watermarkConfigId
const shareLinkId = task.payload?.watermark?.shareLinkId
if (!watermarkConfigId) {
throw ApplicationFailure.create({
message: 'watermarkConfigId is required in task payload',
nonRetryable: true,
})
}
try {
workerQueue = await getWorkerQueueAndStartTask(task)
const {
initWatermarkFileActivity,
waitForWatermarkFileActivity,
transcodeWatermarkMediaActivity,
completeWatermarkFileActivity,
} = getActivities()
const initResult = await executeActivity(workerQueue, initWatermarkFileActivity, {
assetId: task.assetId,
watermarkConfigId,
})
if (initResult.action === 'completed') {
if (shareLinkId) {
await executeActivity(workerQueue, completeWatermarkFileActivity, {
assetId: task.assetId,
watermarkConfigId,
status: 'completed',
shareLinkId,
})
}
await completeTask(workerQueue, task.id)
return
}
if (initResult.action === 'failed') {
throw ApplicationFailure.create({
message: 'Watermark file generation failed in another task',
nonRetryable: true,
})
}
if (initResult.action === 'processing') {
const waitResult = await executeActivity(workerQueue, waitForWatermarkFileActivity, {
assetId: task.assetId,
watermarkConfigId,
})
if (waitResult.status === 'completed') {
if (shareLinkId) {
await executeActivity(workerQueue, completeWatermarkFileActivity, {
assetId: task.assetId,
watermarkConfigId,
status: 'completed',
shareLinkId,
})
}
await completeTask(workerQueue, task.id)
return
}
throw ApplicationFailure.create({
message: 'Watermark file generation failed in in-flight task',
nonRetryable: true,
})
}
const mediaInfo = await executeActivity(workerQueue, transcodeWatermarkMediaActivity, {
assetId: task.assetId,
watermarkConfigId,
})
await executeActivity(workerQueue, completeWatermarkFileActivity, {
assetId: task.assetId,
watermarkConfigId,
mediaInfo,
status: 'completed',
shareLinkId,
})
await completeTask(workerQueue, task.id)
} catch (err) {
if (workerQueue && watermarkConfigId) {
const { completeWatermarkFileActivity } = getActivities()
try {
await executeActivity(workerQueue, completeWatermarkFileActivity, {
assetId: task.assetId,
watermarkConfigId,
status: 'failed',
shareLinkId,
})
} catch (e) {
console.error('Failed to update watermark file status to failed:', e)
}
}
await failTask(workerQueue, task.id, err)
throw err
}
}
@@ -5,6 +5,7 @@ import { transcodePdfWorkflow } from './transcode-pdf'
import { renderPdfPagesWorkflow } from './render-pdf-pages'
import { takeVideoScreenshotsWorkflow } from './take-video-screenshots'
import { overlayImageAnnotationWorkflow } from './overlay-image-annotation'
import { transcodeWatermarkWorkflow } from './transcode-watermark'
/**
* @deprecated Legacy monolithic transcode workflow. Prefer using focused workflows:
@@ -13,6 +14,9 @@ import { overlayImageAnnotationWorkflow } from './overlay-image-annotation'
*/
export async function transcodeMedia(task: WorkflowTask): Promise<void> {
const payload = task.payload
if (payload?.watermark || task.type === 'transcode_watermark') {
return transcodeWatermarkWorkflow(task)
}
if (payload?.pdfPages) {
return renderPdfPagesWorkflow(task)
}
@@ -42,5 +46,6 @@ export * from './transcode-pdf'
export * from './render-pdf-pages'
export * from './take-video-screenshots'
export * from './overlay-image-annotation'
export * from './transcode-watermark'
export * from './common'
export * from './transcode-utils'