Files
shumai/packages/core/src/watermark/watermark.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

585 lines
18 KiB
TypeScript

import {
prisma,
WorkflowTaskStatus,
WorkflowTaskType,
WatermarkStatus,
WatermarkFileStatus,
WatermarkConfig,
WatermarkTemplate,
} from '@shumai/db'
import type { Prisma } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import {
WatermarkConfigSpec,
WatermarkConfigInfo,
WatermarkTemplateInfo,
ShareLinkInfo,
} from '@shumai/dtos'
import { computeWatermarkConfigHash } from '@shumai/core/src/watermark/watermark-hash'
import { s3Service } from '@shumai/core/src/s3/s3'
import {
ShareLinkNotFoundError,
ShareLinkWatermarkProcessingError,
} from '@shumai/core/src/share/errors'
import { shareService } from '@shumai/core/src/share/share'
import { logger } from '@shumai/core/src/logger'
// Union of the global client and interactive-transaction client, which share the
// same delegate shapes for the models used by this service.
type WatermarkDbClient = Prisma.TransactionClient | typeof prisma
export class WatermarkService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async upsertConfig(config: WatermarkConfigSpec) {
return this.upsertConfigWithClient(this.prismaClient, config)
}
private async upsertConfigWithClient(client: WatermarkDbClient, config: WatermarkConfigSpec) {
const hash = computeWatermarkConfigHash(config)
// Upsert keyed on the unique hash so concurrent enables of the same config
// cannot race into a unique-constraint violation.
return client.watermarkConfig.upsert({
where: { hash },
update: {},
create: {
hash,
config: config as PrismaJson.WatermarkConfigSpec,
},
})
}
// ----------------------------------------------------------------------
// Watermark Template CRUD
// ----------------------------------------------------------------------
async createTemplate(
teamId: string | null,
name: string,
config: WatermarkConfigSpec,
): Promise<WatermarkTemplateInfo> {
const tpl = await this.prismaClient.watermarkTemplate.create({
data: {
name,
config: config as PrismaJson.WatermarkConfigSpec,
teamId,
},
})
return await this.toWatermarkTemplateInfo(tpl)
}
async updateTemplate(
templateId: string,
name?: string,
config?: WatermarkConfigSpec,
): Promise<WatermarkTemplateInfo> {
const existing = await this.prismaClient.watermarkTemplate.findUnique({
where: { id: templateId },
})
if (!existing) {
throw new Error('Watermark template not found')
}
const tpl = await this.prismaClient.watermarkTemplate.update({
where: { id: templateId },
data: {
name: name ?? undefined,
config: config ? (config as PrismaJson.WatermarkConfigSpec) : undefined,
},
})
return await this.toWatermarkTemplateInfo(tpl)
}
async deleteTemplate(templateId: string): Promise<void> {
const existing = await this.prismaClient.watermarkTemplate.findUnique({
where: { id: templateId },
})
if (!existing) {
throw new Error('Watermark template not found')
}
await this.prismaClient.watermarkTemplate.delete({
where: { id: templateId },
})
}
async listTemplates(teamIds?: string | string[] | null): Promise<WatermarkTemplateInfo[]> {
const where = teamIds
? Array.isArray(teamIds)
? { teamId: { in: teamIds } }
: { teamId: teamIds }
: undefined
const tpls = await this.prismaClient.watermarkTemplate.findMany({
where,
// ULIDs are time-sortable; ordering by id desc is the project convention
orderBy: { id: 'desc' },
})
return await Promise.all(tpls.map((t) => this.toWatermarkTemplateInfo(t)))
}
async getTemplate(templateId: string): Promise<WatermarkTemplateInfo> {
const tpl = await this.prismaClient.watermarkTemplate.findUnique({
where: { id: templateId },
})
if (!tpl) {
throw new Error('Watermark template not found')
}
return await this.toWatermarkTemplateInfo(tpl)
}
// ----------------------------------------------------------------------
// ShareLink Watermark Management
// ----------------------------------------------------------------------
async updateShareLinkWatermark(
shareLinkId: string,
enabled: boolean,
config?: WatermarkConfigSpec,
): Promise<ShareLinkInfo> {
return await this.prismaClient.$transaction(async (tx) => {
// Lock the sharelink record SELECT FOR UPDATE
const lockedRows = await tx.$queryRaw<
{
id: string
watermarkStatus: WatermarkStatus
watermarkConfigId: string | null
}[]
>`SELECT id, watermark_status AS "watermarkStatus", watermark_config_id AS "watermarkConfigId" FROM share_links WHERE id = ${shareLinkId} FOR UPDATE`
if (lockedRows.length === 0) {
throw new ShareLinkNotFoundError('Share link not found')
}
const currentStatus = lockedRows[0].watermarkStatus
if (currentStatus === WatermarkStatus.processing) {
throw new ShareLinkWatermarkProcessingError(
'Watermark transcoding is currently in progress',
)
}
if (!enabled) {
await tx.shareLink.update({
where: { id: shareLinkId },
data: {
watermarkConfigId: null,
watermarkStatus: WatermarkStatus.disabled,
},
})
// Read back through the transaction client: the global client runs on a
// different pooled connection and cannot see uncommitted changes.
return await shareService.getShareLink(shareLinkId, tx)
}
if (!config || !config.blocks || config.blocks.length === 0) {
throw new Error('Watermark configuration is required when enabling watermark')
}
// Upsert watermark config based on hash
const watermarkConfig = await this.upsertConfigWithClient(tx, config)
await tx.shareLink.update({
where: { id: shareLinkId },
data: {
watermarkConfigId: watermarkConfig.id,
watermarkStatus: WatermarkStatus.processing,
},
})
// Dispatch transcode tasks for all video/image assets in the sharelink
await this.triggerWatermarkTranscodeForShareLink(shareLinkId, watermarkConfig.id, tx)
return await shareService.getShareLink(shareLinkId, tx)
})
}
async getShareLinkWatermark(shareLinkId: string): Promise<{
watermarkStatus: WatermarkStatus
watermarkConfig: WatermarkConfigInfo | null
}> {
const shareLink = await this.prismaClient.shareLink.findUnique({
where: { id: shareLinkId },
include: { watermarkConfig: true },
})
if (!shareLink) {
throw new ShareLinkNotFoundError('Share link not found')
}
return {
watermarkStatus: shareLink.watermarkStatus,
watermarkConfig: shareLink.watermarkConfig
? await this.toWatermarkConfigInfo(shareLink.watermarkConfig)
: null,
}
}
/**
* Finds all media file asset IDs (videos and images) contained in the sharelink,
* including files within symlinked folders, and enqueues transcode workflow tasks.
*/
async triggerWatermarkTranscodeForShareLink(
shareLinkId: string,
watermarkConfigId: string,
txClient?: WatermarkDbClient,
): Promise<number> {
const client = txClient || this.prismaClient
const shareLink = await client.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) return 0
const targetMediaAssets = await this.getMediaAssetIdsInShareLink(shareLink.rootFolderId, client)
if (targetMediaAssets.length === 0) {
// If no media assets in sharelink, mark sharelink watermark as ready immediately
await client.shareLink.update({
where: { id: shareLinkId },
data: { watermarkStatus: WatermarkStatus.ready },
})
return 0
}
let dispatchedCount = 0
for (const assetId of targetMediaAssets) {
// Deliberately one create() per task: the @shumai/db client extension that
// submits tasks to the workflow engine only hooks `workflowTask.create`,
// not `createMany`.
await client.workflowTask.create({
data: {
assetId,
type: WorkflowTaskType.transcode_watermark,
status: WorkflowTaskStatus.pending,
projectId: shareLink.projectId,
payload: {
projectId: shareLink.projectId,
watermark: {
watermarkConfigId,
shareLinkId,
},
},
},
})
dispatchedCount++
}
return dispatchedCount
}
/**
* Recursively resolves real media file asset IDs (video and image) under a sharelink root folder.
* Walks the tree level-by-level (batched queries) and follows symlinks at any depth.
*/
async getMediaAssetIdsInShareLink(
rootFolderId: string,
txClient?: WatermarkDbClient,
): Promise<string[]> {
const client = txClient || this.prismaClient
// Fetch symlinks directly under root folder; these point to the shared targets
const symlinks = await client.asset.findMany({
where: {
parentId: rootFolderId,
type: 'symlink',
isDeleted: false,
},
select: { targetId: true },
})
const queue = symlinks.map((s) => s.targetId).filter((id): id is string => !!id)
if (queue.length === 0) return []
const mediaAssetIds: string[] = []
const visited = new Set<string>()
while (queue.length > 0) {
const frontier = queue.splice(0)
const assets = await client.asset.findMany({
where: { id: { in: frontier } },
select: {
id: true,
type: true,
mediaType: true,
media: true,
isDeleted: true,
targetId: true,
},
})
const folderIds: string[] = []
const next: string[] = []
for (const asset of assets) {
if (visited.has(asset.id)) continue
visited.add(asset.id)
if (asset.isDeleted) continue
if (asset.type === 'file') {
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
const proxyType = mediaInfo?.proxyType
const isVideo = proxyType === 'video' || asset.mediaType?.startsWith('video/')
const isImage = proxyType === 'image' || asset.mediaType?.startsWith('image/')
if (isVideo || isImage) {
mediaAssetIds.push(asset.id)
}
} else if (asset.type === 'folder') {
folderIds.push(asset.id)
} else if (asset.type === 'symlink' && asset.targetId) {
// Resolve nested symlinks (e.g. folders that contain their own symlinks)
next.push(asset.targetId)
}
}
if (folderIds.length > 0) {
const children = await client.asset.findMany({
where: { parentId: { in: folderIds }, isDeleted: false },
select: { id: true },
})
next.push(...children.map((c) => c.id))
}
queue.push(...next)
}
return mediaAssetIds
}
/**
* Checks if all required media assets in a sharelink have completed watermark transcodes.
* If all are completed, sets ShareLink.watermarkStatus to 'ready'.
* If any failed, sets ShareLink.watermarkStatus to 'failed'.
*/
async checkAndUpdateShareLinkStatus(shareLinkId: string): Promise<WatermarkStatus> {
const shareLink = await this.prismaClient.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink || !shareLink.watermarkConfigId) {
return WatermarkStatus.disabled
}
const watermarkConfigId = shareLink.watermarkConfigId
const mediaAssetIds = await this.getMediaAssetIdsInShareLink(shareLink.rootFolderId)
if (mediaAssetIds.length === 0) {
await this.prismaClient.shareLink.update({
where: { id: shareLinkId },
data: { watermarkStatus: WatermarkStatus.ready },
})
return WatermarkStatus.ready
}
const watermarkFiles = await this.prismaClient.watermarkFile.findMany({
where: {
assetId: { in: mediaAssetIds },
watermarkConfigId,
},
})
const statusMap = new Map(watermarkFiles.map((wf) => [wf.assetId, wf.status]))
let allCompleted = true
let anyFailed = false
for (const assetId of mediaAssetIds) {
const status = statusMap.get(assetId)
if (status === WatermarkFileStatus.failed) {
anyFailed = true
allCompleted = false
break
}
if (status !== WatermarkFileStatus.completed) {
allCompleted = false
}
}
let newStatus: WatermarkStatus
if (anyFailed) {
newStatus = WatermarkStatus.failed
} else if (allCompleted) {
newStatus = WatermarkStatus.ready
} else {
newStatus = WatermarkStatus.processing
}
if (newStatus !== shareLink.watermarkStatus) {
await this.prismaClient.shareLink.update({
where: { id: shareLinkId },
data: { watermarkStatus: newStatus },
})
}
return newStatus
}
// ----------------------------------------------------------------------
// Background Async Garbage Collection
// ----------------------------------------------------------------------
/**
* Background task to prune orphan WatermarkConfig records and delete their storage files.
* Runs as part of background cleanup.
*/
async purgeOrphanWatermarkConfigs(): Promise<number> {
const bucket = process.env.S3_BUCKET || 'shumai'
// 1. Find orphan configs with 0 sharelinks attached and no in-flight watermark
// tasks, using FOR UPDATE SKIP LOCKED. Configs with pending/processing tasks
// must not be purged, or the running activities would fail with FK violations.
const orphanConfigs = await this.prismaClient.$queryRaw<{ id: string }[]>`
SELECT wc.id FROM watermark_configs wc
WHERE NOT EXISTS (SELECT 1 FROM share_links sl WHERE sl.watermark_config_id = wc.id)
AND NOT EXISTS (
SELECT 1 FROM workflow_tasks wt
WHERE wt.type = 'transcode_watermark'
AND wt.status IN ('pending', 'processing')
AND wt.payload->'watermark'->>'watermarkConfigId' = wc.id
)
LIMIT 20
FOR UPDATE SKIP LOCKED
`
if (orphanConfigs.length === 0) return 0
let purgedCount = 0
for (const config of orphanConfigs) {
try {
// Fetch all watermark files for this config
const watermarkFiles = await this.prismaClient.watermarkFile.findMany({
where: { watermarkConfigId: config.id },
})
// Delete proxy files from S3
for (const wf of watermarkFiles) {
const media = wf.media
if (media) {
const keysToDelete: string[] = []
if (Array.isArray(media.videoTranscodes)) {
for (const vt of media.videoTranscodes) {
if (vt.key) keysToDelete.push(vt.key)
}
}
if (Array.isArray(media.imageTranscodes)) {
for (const it of media.imageTranscodes) {
if (it.key) keysToDelete.push(it.key)
}
}
if (media.videoPreview?.key) keysToDelete.push(media.videoPreview.key)
if (media.thumbnail?.key) keysToDelete.push(media.thumbnail.key)
for (const key of keysToDelete) {
try {
await s3Service.deleteObject(bucket, key)
} catch (s3Err) {
logger.warn({ key, err: s3Err }, 'Failed to delete watermark proxy file from S3')
}
}
}
}
// Delete WatermarkFiles and WatermarkConfig in DB
await this.prismaClient.$transaction(async (tx) => {
await tx.watermarkFile.deleteMany({
where: { watermarkConfigId: config.id },
})
await tx.watermarkConfig.delete({
where: { id: config.id },
})
})
purgedCount++
logger.info({ configId: config.id }, 'Purged orphan watermark config and proxy files')
} catch (err) {
logger.error({ configId: config.id, err }, 'Failed to purge orphan watermark config')
}
}
return purgedCount
}
/**
* Fetches completed watermark media entries for a list of asset IDs under a specific watermark config.
* Returns a map of assetId -> PrismaJson.MediaInfo.
*/
async getCompletedWatermarkMediaMap(
assetIds: string[],
watermarkConfigId: string,
): Promise<Map<string, PrismaJson.MediaInfo>> {
if (assetIds.length === 0) return new Map()
const watermarkFiles = await prisma.watermarkFile.findMany({
where: {
assetId: { in: assetIds },
watermarkConfigId,
status: 'completed',
},
})
const map = new Map<string, PrismaJson.MediaInfo>()
for (const wf of watermarkFiles) {
if (wf.media) {
map.set(wf.assetId, wf.media as PrismaJson.MediaInfo)
}
}
return map
}
/**
* Enriches image blocks in a watermark config with accessible presigned URLs for WebUI rendering.
*/
async enrichWatermarkConfigWithPresignedUrls(
config: WatermarkConfigSpec,
): Promise<WatermarkConfigSpec> {
if (!config || !config.blocks || config.blocks.length === 0) return config
const bucket = process.env.S3_BUCKET || 'shumai'
const enrichedBlocks = await Promise.all(
config.blocks.map(async (block) => {
if (block.type === 'image' && block.imageAssetKey) {
try {
const url = await s3Service.presign(bucket, block.imageAssetKey, 'GET')
return { ...block, imageAssetUrl: url }
} catch (err) {
logger.warn({ key: block.imageAssetKey, err }, 'Failed to presign watermark image key')
}
}
return block
}),
)
return { ...config, blocks: enrichedBlocks }
}
// ----------------------------------------------------------------------
// DTO Mappers
// ----------------------------------------------------------------------
private async toWatermarkTemplateInfo(t: WatermarkTemplate): Promise<WatermarkTemplateInfo> {
const config = await this.enrichWatermarkConfigWithPresignedUrls(
t.config as WatermarkConfigSpec,
)
return {
id: t.id,
name: t.name,
config,
teamId: t.teamId,
createdAt: t.createdAt.toISOString(),
updatedAt: t.updatedAt.toISOString(),
}
}
private async toWatermarkConfigInfo(c: WatermarkConfig): Promise<WatermarkConfigInfo> {
const config = await this.enrichWatermarkConfigWithPresignedUrls(
c.config as WatermarkConfigSpec,
)
return {
id: c.id,
config,
hash: c.hash,
createdAt: c.createdAt.toISOString(),
updatedAt: c.updatedAt.toISOString(),
}
}
}
export const watermarkService = new WatermarkService()