import type { FastifyInstance } from 'fastify'; import { EngineError, EngineErrorCode, type DocumentManifest, type CustomMetadataPatch, type MetadataPatch, } from '@embedpdf/engine-core/runtime'; import { CustomMetadataPatchSchema, decodeMetadataToken, MetadataPatchSchema, type DocResourceId, } from '@embedpdf/engine-core/wire'; import { requireLayerCapability, requireLayerDocAccessOnly, requireLayerResource, } from '../app/jwt-plugin'; import type { DocumentService, OpenContext } from '../services/DocumentService'; import type { LayerService, LayerWriteContext } from '../services/LayerService'; import { abortSignalOf, parseOrInvalidArg, parseTokenOrInvalidArg, readAtPins, setImmutableCache, setNoStore, type SchemaLike, } from './_helpers'; import { requireSharedDocRead } from './_planeGuard'; interface MetadataRouteDeps { service: DocumentService; layerService: LayerService; } /** * One half of the Info dict. The standard fields live at `/metadata`, the * custom keys at `/metadata/custom`; both share the `metadataVersion` pointer * and the same gates (`doc.open` to read, `doc.metadata.modify` to write). */ interface InfoDictHalf { segment: 'metadata' | 'metadata/custom'; docResource: DocResourceId; layerResource: DocResourceId; read: ( ctx: OpenContext, docId: string, layerName: string | undefined, signal: AbortSignal, ) => Promise; write: ( ctx: LayerWriteContext, input: { docId: string; layerName: string; body: unknown }, signal: AbortSignal, ) => Promise; } export async function registerMetadataRoutes( app: FastifyInstance, deps: MetadataRouteDeps, ): Promise { const { service, layerService } = deps; const halves: InfoDictHalf[] = [ { segment: 'metadata', docResource: 'metadata', layerResource: 'layer-metadata', read: (ctx, docId, layerName, signal) => service.readLayerMetadata(ctx, docId, layerName, signal), write: (ctx, { docId, layerName, body }, signal) => { const patch = parseOrInvalidArg( MetadataPatchSchema as unknown as SchemaLike, body, 'request body', ); return layerService.updateMetadata(ctx, { docId, layerName, patch }, signal); }, }, { segment: 'metadata/custom', docResource: 'metadata-custom', layerResource: 'layer-metadata-custom', read: (ctx, docId, layerName, signal) => service.readLayerCustomMetadata(ctx, docId, layerName, signal), write: (ctx, { docId, layerName, body }, signal) => { const patch = parseOrInvalidArg( CustomMetadataPatchSchema as unknown as SchemaLike, body, 'request body', ); return layerService.updateCustomMetadata(ctx, { docId, layerName, patch }, signal); }, }, ]; for (const half of halves) { // Plane-scoped doc-level read: served from the base worker session while // the caller's layer inherits the metadata plane. app.get(`/v1/docs/:docId/${half.segment}@:token`, async (req, reply) => { const { docId, token } = req.params as { docId: string; token: string }; const ctx = await requireSharedDocRead(req, service, docId, half.docResource, ['metadata']); const requested = parseTokenOrInvalidArg(decodeMetadataToken, token, 'metadataVersion token'); const body = await readAtPins({ documentService: service, reply, docId, layerName: undefined, assertCurrent: async () => assertMetadataCurrent(requested, await service.getManifest(ctx, docId)), read: () => half.read(ctx, docId, undefined, abortSignalOf(reply)), token: { kind: 'metadata', pin: requested.pin }, }); setImmutableCache(reply); return body; }); app.get(`/v1/docs/:docId/layers/:layerName/${half.segment}@:token`, async (req, reply) => { const { docId, layerName, token } = req.params as { docId: string; layerName: string; token: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await service.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource(req, docId, layerName, half.layerResource, permissionFlags); const requested = parseTokenOrInvalidArg(decodeMetadataToken, token, 'metadataVersion token'); const body = await readAtPins({ documentService: service, reply, docId, layerName, assertCurrent: async () => assertMetadataCurrent(requested, await service.getLayerManifest(ctx, docId, layerName)), read: () => half.read(ctx, docId, layerName, abortSignalOf(reply)), token: { kind: 'metadata', pin: requested.pin }, }); setImmutableCache(reply); return body; }); app.get(`/v1/docs/:docId/layers/:layerName/${half.segment}`, async (req, reply) => { const { docId, layerName } = req.params as { docId: string; layerName: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await service.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource(req, docId, layerName, half.layerResource, permissionFlags); const body = await half.read(ctx, docId, layerName, abortSignalOf(reply)); setNoStore(reply); return body; }); app.post(`/v1/docs/:docId/layers/:layerName/${half.segment}`, async (req, reply) => { const { docId, layerName } = req.params as { docId: string; layerName: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await service.getEffectivePermissionFlags( accessCtx, docId, layerName, ); // A certification that allows no changes forbids this one too. const protection = await service.getProtection(accessCtx, docId, layerName); const ctx = requireLayerCapability( req, docId, layerName, 'doc.metadata.modify', permissionFlags, protection, ); setNoStore(reply); return half.write(ctx, { docId, layerName, body: req.body }, abortSignalOf(reply)); }); } } /** A pinned read answers only at the manifest's current `metadataVersion`; a stale one is a 404. */ function assertMetadataCurrent( requested: { metadataVersion: number }, manifest: DocumentManifest, ): void { if (requested.metadataVersion === manifest.metadataVersion) return; throw new EngineError( EngineErrorCode.NotFound, `metadata version ${requested.metadataVersion} no longer current (current=${manifest.metadataVersion})`, ); }