@hyperframes/gcp-cloud-run 0.7.110 → 0.7.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -4
- package/dist/events.d.ts +10 -10
- package/dist/events.d.ts.map +1 -1
- package/dist/index.js +15 -14
- package/dist/index.js.map +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/renderToCloudRun.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +14 -13
- package/dist/server.js.map +2 -2
- package/package.json +2 -2
- package/terraform/smoke-safety.test.ts +2 -2
- package/terraform/workflow.test.ts +2 -2
- package/terraform/workflow.yaml +3 -3
package/dist/server.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/server.ts", "../src/chromium.ts", "../src/formatExtension.ts", "../src/gcsTransport.ts", "../src/gcsPlanV2Publisher.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Cloud Run request handler for HyperFrames distributed rendering.\n *\n * One container image, three roles. Cloud Workflows POSTs a JSON body with\n * an `Action` field; the handler unwraps any `Payload`/`Input` envelope,\n * primes the runtime (Chrome path), and forwards to the matching OSS\n * primitive from `@hyperframes/producer/distributed`.\n *\n * Everything heavy \u2014 capture, encode, audio mix \u2014 happens inside the OSS\n * primitives. The handler is thin glue: parse body \u2192 GCS download \u2192 call\n * primitive \u2192 GCS upload \u2192 return small JSON result.\n *\n * `dispatch()` is the testable core (inject `storage` + `primitives`); the\n * Hono app at the bottom is the HTTP shell the Dockerfile runs. The shape\n * deliberately tracks `@hyperframes/aws-lambda`'s `handler.ts` so the two\n * adapters stay easy to diff.\n */\n\nimport { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, extname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { serve } from \"@hono/node-server\";\nimport { Storage } from \"@google-cloud/storage\";\nimport { Hono } from \"hono\";\nimport {\n assemble,\n type AssembleResult,\n type ChunkRenderer,\n type ChunkResult,\n type DistributedRenderConfig,\n listPlanV2ArtifactsForTarget,\n materializePlanV2Target,\n plan,\n isPlanAudioArtifactPath,\n PLAN_AUDIO_RELATIVE_PATH,\n resolvePlanAudioPath,\n planV2WithPublisher,\n type PlanResult,\n type PlanV2Artifact,\n type PlanV2Manifest,\n type PlanV2MaterializationTarget,\n readPlanV2Manifest,\n renderChunk,\n} from \"@hyperframes/producer/distributed\";\nimport { resolveChromeExecutablePath } from \"./chromium.js\";\nimport type {\n AssembleEvent,\n AssembleResultBody,\n CloudRunAction,\n CloudRunEvent,\n CloudRunResult,\n PlanEvent,\n PlanResultBody,\n RenderChunkEvent,\n RenderChunkResultBody,\n} from \"./events.js\";\nimport { type DistributedFormat, formatExtension } from \"./formatExtension.js\";\nimport {\n downloadGcsObjectToFile,\n downloadGcsObjectToFileVerified,\n parseGcsUri,\n tarDirectory,\n untarDirectory,\n uploadFileToGcs,\n} from \"./gcsTransport.js\";\nimport { GcsPlanV2ArtifactPublisher } from \"./gcsPlanV2Publisher.js\";\n\n/**\n * Lazily-constructed Storage client. Cached at module scope so warm\n * container instances reuse the underlying HTTP keep-alive pool across\n * requests.\n */\nlet cachedStorage: Storage | null = null;\nfunction getStorage(): Storage {\n if (cachedStorage) return cachedStorage;\n cachedStorage = new Storage();\n return cachedStorage;\n}\n\n/**\n * Optional injection points used by the handler's unit tests. Production\n * callers leave these unset; the real OSS primitives are used. Tests inject\n * `storage` and `primitives` directly rather than mutating module state.\n */\nexport interface HandlerDeps {\n storage?: Storage;\n primitives?: {\n plan: typeof plan;\n planV2WithPublisher?: typeof planV2WithPublisher;\n renderChunk: ChunkRenderer;\n assemble: typeof assemble;\n };\n /** Override the per-request workdir root (defaults to the OS tmpdir). */\n tmpRoot?: string;\n /** Skip Chrome resolution (used by dispatch tests that mock renderChunk). */\n skipChromeResolution?: boolean;\n}\n\n/**\n * Dispatch a single render request. Cloud Workflows (or a direct caller)\n * sometimes wraps the body in `{ Payload: ... }` or `{ Input: ... }`; unwrap\n * until we hit a discriminated event.\n */\n// fallow-ignore-next-line complexity\nexport async function dispatch(event: CloudRunEvent, deps?: HandlerDeps): Promise<CloudRunResult> {\n const unwrapped = unwrapEvent(event);\n validatePlanProtocolShape(unwrapped);\n validateEventGcsUris(unwrapped);\n logEvent({ event: \"handler_start\", action: unwrapped.Action, input: summarizeEvent(unwrapped) });\n try {\n switch (unwrapped.Action) {\n case \"plan\":\n return await handlePlan(unwrapped, deps);\n case \"renderChunk\":\n return await handleRenderChunk(unwrapped, deps);\n case \"assemble\":\n return await handleAssemble(unwrapped, deps);\n default: {\n // Compile-time exhaustiveness: a new CloudRunAction member trips\n // the `never` assignment before the runtime error is reachable.\n const _exhaustive: never = unwrapped;\n throw new Error(\n `[handler] unknown Action: ${JSON.stringify(\n (_exhaustive as { Action?: string }).Action,\n )}. Expected one of \"plan\", \"renderChunk\", \"assemble\".`,\n );\n }\n }\n } catch (err) {\n normalizeTerminalErrorName(err);\n logEvent({\n event: \"handler_error\",\n action: unwrapped.Action,\n input: summarizeEvent(unwrapped),\n message: err instanceof Error ? err.message : String(err),\n name: err instanceof Error ? err.name : undefined,\n });\n throw err;\n }\n}\n\n// This is the single fail-closed boundary for the wire union. Keeping all\n// forbidden locator combinations together makes mixed-protocol input auditable.\n// fallow-ignore-next-line complexity\nfunction validatePlanProtocolShape(event: PlanEvent | RenderChunkEvent | AssembleEvent): void {\n const raw = event as unknown as Record<string, unknown>;\n const protocol = raw.PlanProtocol;\n if (protocol !== undefined && protocol !== \"v1\" && protocol !== \"v2\") {\n const error = new Error(\n `[handler] unsupported PlanProtocol ${JSON.stringify(protocol)}; expected \"v1\", \"v2\", or absent`,\n );\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n if (event.Action === \"plan\") return;\n\n const hasV1Locator = typeof raw.PlanGcsUri === \"string\";\n const hasV2Manifest = typeof raw.PlanV2ManifestGcsUri === \"string\";\n const hasV2Prefix = typeof raw.PlanV2ArtifactGcsPrefix === \"string\";\n const valid =\n protocol === \"v2\"\n ? !hasV1Locator && hasV2Manifest && hasV2Prefix\n : hasV1Locator && !hasV2Manifest && !hasV2Prefix;\n if (!valid) {\n const error = new Error(\n `[handler] ${protocol === \"v2\" ? \"v2\" : \"v1\"} ${event.Action} event has mixed or missing plan locators`,\n );\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n if (protocol === \"v2\" && event.Action === \"assemble\" && event.AudioGcsUri !== null) {\n const error = new Error(\"[handler] v2 assemble audio must be materialized from the manifest\");\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n}\n\n/** Normalize producer error codes to the stable HTTP/workflow discriminator. */\n// The explicit mapping is the public Cloud Workflows retry contract.\n// fallow-ignore-next-line complexity\nfunction normalizeTerminalErrorName(error: unknown): void {\n if (!error || typeof error !== \"object\") return;\n const candidate = error as { code?: unknown; name?: string };\n if (\n candidate.code === \"PLAN_PROTOCOL_UNSUPPORTED\" ||\n candidate.code === \"PLAN_TOO_LARGE\" ||\n candidate.code === \"PLAN_V2_INTEGRITY_UNRECOVERABLE\" ||\n candidate.code === \"FONT_FETCH_FAILED\" ||\n candidate.code === \"FONT_FETCH_UNAVAILABLE\" ||\n candidate.code === \"VIDEO_SOURCE_UNRENDERABLE\" ||\n candidate.code === \"VIDEO_EXTRACTION_FAILED\" ||\n candidate.code === \"INVALID_VIDEO_METADATA\"\n ) {\n candidate.name = candidate.code;\n }\n}\n\n// At most `{Payload: {Input: ...}}` is expected; 4 levels is 2\u00D7 headroom\n// and prevents infinite loops on malformed input.\nconst MAX_ENVELOPE_DEPTH = 4;\n\n// fallow-ignore-next-line complexity\nexport function unwrapEvent(event: CloudRunEvent): PlanEvent | RenderChunkEvent | AssembleEvent {\n let cursor: CloudRunEvent = event;\n for (let i = 0; i < MAX_ENVELOPE_DEPTH; i++) {\n if (cursor && typeof cursor === \"object\") {\n const obj = cursor as Record<string, unknown>;\n if (typeof obj.Action === \"string\" && isCloudRunAction(obj.Action)) {\n return cursor as PlanEvent | RenderChunkEvent | AssembleEvent;\n }\n if (\"Payload\" in obj) {\n cursor = obj.Payload as CloudRunEvent;\n continue;\n }\n if (\"Input\" in obj) {\n cursor = obj.Input as CloudRunEvent;\n continue;\n }\n }\n break;\n }\n throw new Error(\n `[handler] body has no recognised Action; unwrapped ${MAX_ENVELOPE_DEPTH} levels of Payload/Input without finding one.`,\n );\n}\n\nfunction isCloudRunAction(value: string): value is CloudRunAction {\n return value === \"plan\" || value === \"renderChunk\" || value === \"assemble\";\n}\n\n/**\n * Emit a single JSON line to stdout. Cloud Logging ingests each stdout line\n * as a structured `jsonPayload` entry, so Logs Explorer can filter on\n * `jsonPayload.event=\"handler_start\"` and project specific fields when\n * triaging without attaching a debugger.\n */\nfunction logEvent(payload: Record<string, unknown>): void {\n console.log(JSON.stringify(payload));\n}\n\n/**\n * Compact, non-PII summary of an event for logging. The full body can\n * include the entire project config; we only emit the routable fields\n * needed to triage a failure from Cloud Logging.\n */\n// Keep event variants together so Cloud Logging has one redaction boundary.\n// fallow-ignore-next-line complexity\nfunction summarizeEvent(\n event: PlanEvent | RenderChunkEvent | AssembleEvent,\n): Record<string, unknown> {\n switch (event.Action) {\n case \"plan\":\n return {\n projectGcsUri: event.ProjectGcsUri,\n planOutputGcsPrefix: event.PlanOutputGcsPrefix,\n planProtocol: event.PlanProtocol ?? \"v1\",\n format: event.Config.format,\n fps: event.Config.fps,\n };\n case \"renderChunk\":\n return {\n planProtocol: event.PlanProtocol ?? \"v1\",\n ...(event.PlanProtocol === \"v2\"\n ? { planV2ManifestGcsUri: event.PlanV2ManifestGcsUri }\n : { planGcsUri: event.PlanGcsUri }),\n chunkIndex: event.ChunkIndex,\n format: event.Format,\n };\n case \"assemble\":\n return {\n planProtocol: event.PlanProtocol ?? \"v1\",\n ...(event.PlanProtocol === \"v2\"\n ? { planV2ManifestGcsUri: event.PlanV2ManifestGcsUri }\n : { planGcsUri: event.PlanGcsUri }),\n chunkCount: event.ChunkGcsUris.length,\n hasAudio: event.AudioGcsUri !== null,\n outputGcsUri: event.OutputGcsUri,\n format: event.Format,\n };\n }\n}\n\n/**\n * Point the engine at the in-image Chrome binary. The OSS engine resolves\n * Chrome via `PRODUCER_HEADLESS_SHELL_PATH` first; set it once per instance\n * before invoking any browser-touching primitive. ffmpeg is on the image's\n * PATH (apt-installed by the Dockerfile), so nothing to prime there.\n */\nfunction primeChrome(deps?: HandlerDeps): void {\n if (deps?.skipChromeResolution) return;\n if (process.env.PRODUCER_HEADLESS_SHELL_PATH) return;\n process.env.PRODUCER_HEADLESS_SHELL_PATH = resolveChromeExecutablePath();\n}\n\n// \u2500\u2500 Plan \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// fallow-ignore-next-line complexity\nasync function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise<PlanResultBody> {\n if (event.PlanProtocol === \"v2\") {\n return handlePlanV2(event, deps);\n }\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.plan ?? plan;\n\n // The producer's probe stage launches Chromium whenever the composition\n // needs a runtime duration probe or has unresolved sub-compositions, so\n // plan has to resolve Chrome the same way renderChunk does.\n primeChrome(deps);\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-plan-\"));\n const projectArchive = join(work, \"project.tar.gz\");\n const projectDir = join(work, \"project\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadGcsObjectToFile(storage, event.ProjectGcsUri, projectArchive);\n await untarDirectory(projectArchive, projectDir);\n\n const config: DistributedRenderConfig = {\n ...event.Config,\n };\n const result: PlanResult = await primitive(projectDir, config, planDir);\n\n // Upload the planDir as a single tarball. The workflow cannot pass a\n // directory-shaped artifact between steps; we serialize and rely on the\n // consumer (renderChunk / assemble) to untar. The audio artifact lives inside\n // planDir, so it already rides along in this tarball \u2014 every consumer\n // (including assemble) gets it from the untar. We deliberately do NOT\n // upload a separate audio object: it would duplicate the bytes on every\n // plan upload and be re-downloaded + overwritten by assemble. `AudioGcsUri`\n // stays in the result shape for wire compatibility but is null.\n const planTar = join(work, \"plan.tar.gz\");\n await tarDirectory(planDir, planTar);\n const planTarUri = `${trimTrailingSlash(event.PlanOutputGcsPrefix)}/plan.tar.gz`;\n const audioPath = join(planDir, PLAN_AUDIO_RELATIVE_PATH);\n const hasAudio = existsSync(audioPath) && statSync(audioPath).size > 0;\n await uploadFileToGcs(storage, planTar, planTarUri, \"application/gzip\");\n\n return {\n Action: \"plan\",\n PlanGcsUri: planTarUri,\n PlanHash: result.planHash,\n ChunkCount: result.chunkCount,\n TotalFrames: result.totalFrames,\n Fps: result.fps,\n Width: result.width,\n Height: result.height,\n Format: result.format,\n HasAudio: hasAudio,\n AudioGcsUri: null,\n FfmpegVersion: result.ffmpegVersion,\n ProducerVersion: result.producerVersion,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n/**\n * Publish immutable v2 artifacts directly to GCS, with the manifest as the\n * final commit point. Planner-local paths never cross a worker boundary.\n */\n// fallow-ignore-next-line complexity\nasync function handlePlanV2(\n event: Extract<PlanEvent, { PlanProtocol: \"v2\" }>,\n deps?: HandlerDeps,\n): Promise<Extract<PlanResultBody, { PlanProtocol: \"v2\" }>> {\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.planV2WithPublisher ?? planV2WithPublisher;\n primeChrome(deps);\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-plan-v2-\"));\n const projectArchive = join(work, \"project.tar.gz\");\n const projectDir = join(work, \"project\");\n try {\n await downloadGcsObjectToFile(storage, event.ProjectGcsUri, projectArchive);\n await untarDirectory(projectArchive, projectDir);\n const publisher = new GcsPlanV2ArtifactPublisher({\n storage,\n planOutputGcsPrefix: event.PlanOutputGcsPrefix,\n temporaryRoot: work,\n });\n const manifest: PlanV2Manifest = await primitive(projectDir, { ...event.Config }, publisher, {\n stagingParentDir: work,\n });\n\n return {\n Action: \"plan\",\n PlanProtocol: \"v2\",\n PlanV2ManifestGcsUri: publisher.manifestUri,\n PlanV2ArtifactGcsPrefix: publisher.artifactPrefix,\n PlanHash: manifest.planHash,\n ChunkCount: manifest.chunkCount,\n TotalFrames: manifest.totalFrames,\n Fps: manifest.fps,\n Width: manifest.width,\n Height: manifest.height,\n Format: manifest.format,\n HasAudio: manifest.artifacts.some((artifact) => isPlanAudioArtifactPath(artifact.path)),\n AudioGcsUri: null,\n FfmpegVersion: manifest.ffmpegVersion,\n ProducerVersion: manifest.producerVersion,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// \u2500\u2500 RenderChunk \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// fallow-ignore-next-line complexity\nasync function handleRenderChunk(\n event: RenderChunkEvent,\n deps?: HandlerDeps,\n): Promise<RenderChunkResultBody> {\n if (event.PlanProtocol === \"v2\") {\n return handleRenderChunkV2(event, deps);\n }\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.renderChunk ?? renderChunk;\n\n primeChrome(deps);\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-chunk-\"));\n const planTar = join(work, \"plan.tar.gz\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadGcsObjectToFile(storage, event.PlanGcsUri, planTar);\n await untarDirectory(planTar, planDir);\n\n // Verify the plan's hash matches what the workflow told us to render.\n // The producer's renderChunk re-checks internally (defense-in-depth),\n // but doing it here at the handler boundary lets us fail before paying\n // the Chrome-launch + render cost on a misrouted chunk. Throws a typed\n // PLAN_HASH_MISMATCH the workflow can route as non-retryable.\n verifyPlanHash(planDir, event.PlanHash);\n\n const chunkOutputBase = join(\n work,\n event.Format === \"png-sequence\"\n ? `chunk-${pad(event.ChunkIndex)}`\n : `chunk-${pad(event.ChunkIndex)}${formatExtension(event.Format)}`,\n );\n\n const result: ChunkResult = await primitive(planDir, event.ChunkIndex, chunkOutputBase);\n\n const chunkUri = await uploadChunkOutput(\n storage,\n result,\n event.ChunkOutputGcsPrefix,\n event.ChunkIndex,\n );\n\n return {\n Action: \"renderChunk\",\n ChunkGcsUri: chunkUri,\n ChunkIndex: event.ChunkIndex,\n Sha256: result.sha256,\n FramesEncoded: result.framesEncoded,\n CaptureMode: result.captureMode,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n/** Materialize only this chunk's verified v2 dependencies before rendering. */\n// fallow-ignore-next-line complexity\nasync function handleRenderChunkV2(\n event: Extract<RenderChunkEvent, { PlanProtocol: \"v2\" }>,\n deps?: HandlerDeps,\n): Promise<RenderChunkResultBody> {\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.renderChunk ?? renderChunk;\n primeChrome(deps);\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-chunk-v2-\"));\n try {\n const planDir = await downloadAndMaterializePlanV2(\n storage,\n event,\n { role: \"chunk\", chunkIndex: event.ChunkIndex },\n work,\n );\n const chunkOutputBase = join(\n work,\n event.Format === \"png-sequence\"\n ? `chunk-${pad(event.ChunkIndex)}`\n : `chunk-${pad(event.ChunkIndex)}${formatExtension(event.Format)}`,\n );\n const result = await primitive(planDir, event.ChunkIndex, chunkOutputBase);\n const chunkUri = await uploadChunkOutput(\n storage,\n result,\n event.ChunkOutputGcsPrefix,\n event.ChunkIndex,\n );\n return {\n Action: \"renderChunk\",\n ChunkGcsUri: chunkUri,\n ChunkIndex: event.ChunkIndex,\n Sha256: result.sha256,\n FramesEncoded: result.framesEncoded,\n CaptureMode: result.captureMode,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\nasync function uploadChunkOutput(\n storage: Storage,\n result: ChunkResult,\n prefix: string,\n chunkIndex: number,\n): Promise<string> {\n const trimmed = trimTrailingSlash(prefix);\n if (result.outputKind === \"file\") {\n const ext = extname(result.outputPath);\n const uri = `${trimmed}/chunks/${pad(chunkIndex)}${ext}`;\n await uploadFileToGcs(storage, result.outputPath, uri);\n return uri;\n }\n // frame-dir: upload as a tarball so a single GCS object represents the\n // chunk. Assemble's png-sequence path expects a directory per chunk; it\n // untars on its end.\n const tarball = `${result.outputPath}.tar.gz`;\n await tarDirectory(result.outputPath, tarball);\n const uri = `${trimmed}/chunks/${pad(chunkIndex)}.tar.gz`;\n await uploadFileToGcs(storage, tarball, uri, \"application/gzip\");\n return uri;\n}\n\n// \u2500\u2500 Assemble \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// fallow-ignore-next-line complexity\nasync function handleAssemble(\n event: AssembleEvent,\n deps?: HandlerDeps,\n): Promise<AssembleResultBody> {\n if (event.PlanProtocol === \"v2\") {\n return handleAssembleV2(event, deps);\n }\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.assemble ?? assemble;\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-assemble-\"));\n const planTar = join(work, \"plan.tar.gz\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadGcsObjectToFile(storage, event.PlanGcsUri, planTar);\n await untarDirectory(planTar, planDir);\n\n const chunkPaths = await downloadChunkObjects(storage, event.ChunkGcsUris, work, event.Format);\n\n // Audio rides inside the plan tarball, so it's already on disk after the\n // untar above \u2014 no separate download. Fall back to a supplied AudioGcsUri\n // only for backward compatibility with an older Plan that uploaded it\n // standalone.\n let audioPath: string | null = null;\n const planAudio = resolvePlanAudioPath(planDir) ?? join(planDir, PLAN_AUDIO_RELATIVE_PATH);\n if (existsSync(planAudio) && statSync(planAudio).size > 0) {\n audioPath = planAudio;\n } else if (event.AudioGcsUri) {\n audioPath = planAudio;\n await downloadGcsObjectToFile(storage, event.AudioGcsUri, audioPath);\n }\n\n const finalOutput =\n event.Format === \"png-sequence\"\n ? join(work, \"output-frames\")\n : join(work, `output${formatExtension(event.Format)}`);\n\n const result: AssembleResult = await primitive(planDir, chunkPaths, audioPath, finalOutput, {\n cfr: event.Cfr === true,\n });\n\n if (event.Format === \"png-sequence\") {\n const tarball = `${finalOutput}.tar.gz`;\n await tarDirectory(finalOutput, tarball);\n await uploadFileToGcs(storage, tarball, event.OutputGcsUri, \"application/gzip\");\n } else {\n await uploadFileToGcs(storage, finalOutput, event.OutputGcsUri);\n }\n\n return {\n Action: \"assemble\",\n OutputGcsUri: event.OutputGcsUri,\n FramesEncoded: result.framesEncoded,\n FileSize: result.fileSize,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n/**\n * Materialize the assembler target. Audio is declared assembler-only by the\n * v2 manifest and therefore is never downloaded by chunk workers.\n */\n// fallow-ignore-next-line complexity\nasync function handleAssembleV2(\n event: Extract<AssembleEvent, { PlanProtocol: \"v2\" }>,\n deps?: HandlerDeps,\n): Promise<AssembleResultBody> {\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.assemble ?? assemble;\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-assemble-v2-\"));\n try {\n const planDir = await downloadAndMaterializePlanV2(storage, event, { role: \"assembler\" }, work);\n const audioPath = resolvePlanAudioPath(planDir);\n const chunkPaths = await downloadChunkObjects(storage, event.ChunkGcsUris, work, event.Format);\n const finalOutput =\n event.Format === \"png-sequence\"\n ? join(work, \"output-frames\")\n : join(work, `output${formatExtension(event.Format)}`);\n const result = await primitive(planDir, chunkPaths, audioPath, finalOutput, {\n cfr: event.Cfr === true,\n });\n if (event.Format === \"png-sequence\") {\n const tarball = `${finalOutput}.tar.gz`;\n await tarDirectory(finalOutput, tarball);\n await uploadFileToGcs(storage, tarball, event.OutputGcsUri, \"application/gzip\");\n } else {\n await uploadFileToGcs(storage, finalOutput, event.OutputGcsUri);\n }\n return {\n Action: \"assemble\",\n OutputGcsUri: event.OutputGcsUri,\n FramesEncoded: result.framesEncoded,\n FileSize: result.fileSize,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\nasync function downloadAndMaterializePlanV2(\n storage: Storage,\n event: {\n PlanV2ManifestGcsUri: string;\n PlanV2ArtifactGcsPrefix: string;\n PlanHash: string;\n },\n target: PlanV2MaterializationTarget,\n work: string,\n): Promise<string> {\n const transportDir = join(work, \"plan-v2\");\n mkdirSync(transportDir, { recursive: true });\n await downloadGcsObjectToFile(\n storage,\n event.PlanV2ManifestGcsUri,\n join(transportDir, \"plan.json\"),\n );\n const manifest = readPlanV2Manifest(transportDir);\n if (manifest.planHash !== event.PlanHash) {\n throwPlanHashMismatch(event.PlanHash, manifest.planHash);\n }\n const artifacts = listPlanV2ArtifactsForTarget(manifest, target);\n const uniqueArtifacts = [\n ...new Map(artifacts.map((artifact) => [artifact.sha256, artifact])).values(),\n ];\n await mapConcurrent(uniqueArtifacts, 16, async (artifact) => {\n await downloadPlanV2Artifact(storage, event.PlanV2ArtifactGcsPrefix, transportDir, artifact);\n });\n const planDir = join(work, \"plan\");\n materializePlanV2Target(transportDir, target, planDir);\n return planDir;\n}\n\nasync function downloadPlanV2Artifact(\n storage: Storage,\n artifactPrefix: string,\n planV2Dir: string,\n artifact: Readonly<PlanV2Artifact>,\n): Promise<void> {\n await downloadGcsObjectToFileVerified(\n storage,\n planV2BlobUri(artifactPrefix, artifact.sha256),\n planV2BlobPath(planV2Dir, artifact.sha256),\n artifact.sha256,\n );\n}\n\nfunction planV2BlobPath(planV2Dir: string, digest: string): string {\n return join(planV2Dir, \"artifacts\", \"sha256\", digest.slice(0, 2), digest);\n}\n\nfunction planV2BlobUri(prefix: string, digest: string): string {\n return `${trimTrailingSlash(prefix)}/${digest.slice(0, 2)}/${digest}`;\n}\n\nfunction throwPlanHashMismatch(expected: string, actual: string): never {\n const error = new Error(\n `PLAN_HASH_MISMATCH: event PlanHash=${expected} did not match v2 manifest planHash=${actual}`,\n );\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n}\n\nasync function mapConcurrent<T>(\n values: readonly T[],\n concurrency: number,\n fn: (value: T) => Promise<void>,\n): Promise<void> {\n let cursor = 0;\n async function worker(): Promise<void> {\n while (cursor < values.length) {\n const index = cursor++;\n await fn(values[index]!);\n }\n }\n const results = await Promise.allSettled(\n Array.from({ length: Math.min(concurrency, values.length) }, () => worker()),\n );\n const failure = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n // Invocation cleanup removes the work directory in `finally`. Drain all\n // sibling downloads before surfacing an error so a late GCS stream cannot\n // keep writing into scratch after another artifact fails verification.\n if (failure) throw failure.reason;\n}\n\nasync function downloadChunkObjects(\n storage: Storage,\n uris: string[],\n workDir: string,\n format: DistributedFormat,\n): Promise<string[]> {\n const chunksDir = join(workDir, \"chunks\");\n mkdirSync(chunksDir, { recursive: true });\n // Each chunk is an independent GCS GET (+ untar for png-sequence). Run\n // them in parallel \u2014 assemble's wall-clock is otherwise dominated by\n // `\u03A3 chunk-download-ms` instead of `max(chunk-download-ms)`. Preserve the\n // input order by writing into a pre-sized array rather than pushing as\n // each task settles.\n const local: string[] = new Array<string>(uris.length);\n await Promise.all(\n uris.map(async (uri, i) => {\n if (!uri) {\n throw new Error(`[handler] chunk URI at index ${i} is empty`);\n }\n const { key } = parseGcsUri(uri);\n const localPath = join(chunksDir, basename(key));\n await downloadGcsObjectToFile(storage, uri, localPath);\n if (format === \"png-sequence\") {\n const dirPath = join(chunksDir, `frames-${pad(i)}`);\n await untarDirectory(localPath, dirPath);\n local[i] = dirPath;\n } else {\n local[i] = localPath;\n }\n }),\n );\n return local;\n}\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Collect every GCS URI that the handler will touch for a given event. */\n// This exhaustive event projection is the bucket-allowlist security boundary.\n// fallow-ignore-next-line complexity\nfunction getEventGcsUris(event: PlanEvent | RenderChunkEvent | AssembleEvent): string[] {\n switch (event.Action) {\n case \"plan\":\n return [event.ProjectGcsUri, event.PlanOutputGcsPrefix];\n case \"renderChunk\":\n return event.PlanProtocol === \"v2\"\n ? [event.PlanV2ManifestGcsUri, event.PlanV2ArtifactGcsPrefix, event.ChunkOutputGcsPrefix]\n : [event.PlanGcsUri, event.ChunkOutputGcsPrefix];\n case \"assemble\":\n return [\n ...(event.PlanProtocol === \"v2\"\n ? [event.PlanV2ManifestGcsUri, event.PlanV2ArtifactGcsPrefix]\n : [event.PlanGcsUri]),\n ...event.ChunkGcsUris,\n event.OutputGcsUri,\n event.AudioGcsUri,\n ].filter((u): u is string => u != null);\n }\n}\n\n/** Emit the \"guard disabled\" warning at most once per instance. */\nlet warnedAllowlistDisabled = false;\n\n/**\n * Verify every GCS URI in the event resolves to the configured render\n * bucket. Throws `GCS_URI_NOT_ALLOWED` (non-retryable) when a URI targets a\n * different bucket, preventing request injection from reading or writing\n * arbitrary GCS data.\n *\n * Opt-out is explicit: set `HYPERFRAMES_RENDER_BUCKET=\"*\"` to disable the\n * guard intentionally. If the env var is simply unset (or empty), the guard\n * is disabled but a warning is logged once so the gap is visible in Cloud\n * Logging \u2014 it shouldn't silently fail open. The Terraform module always\n * wires the bucket name, so the prod path enforces.\n */\n// fallow-ignore-next-line complexity\nfunction validateEventGcsUris(event: PlanEvent | RenderChunkEvent | AssembleEvent): void {\n const allowedBucket = process.env.HYPERFRAMES_RENDER_BUCKET?.trim();\n if (allowedBucket === \"*\") return; // explicit, intentional opt-out\n if (!allowedBucket) {\n if (!warnedAllowlistDisabled) {\n warnedAllowlistDisabled = true;\n logEvent({\n event: \"bucket_allowlist_disabled\",\n level: \"WARNING\",\n message:\n \"HYPERFRAMES_RENDER_BUCKET is unset \u2014 the GCS bucket-allowlist guard is DISABLED. \" +\n 'Set it to the render bucket name to enforce, or to \"*\" to opt out intentionally.',\n });\n }\n return;\n }\n\n for (const uri of getEventGcsUris(event)) {\n const { bucket } = parseGcsUri(uri);\n if (bucket !== allowedBucket) {\n const err = new Error(\n `[handler] GCS_URI_NOT_ALLOWED: URI ${JSON.stringify(uri)} targets bucket \"${bucket}\" but only \"${allowedBucket}\" is permitted`,\n );\n err.name = \"GCS_URI_NOT_ALLOWED\";\n throw err;\n }\n }\n}\n\nfunction pad(n: number): string {\n return n.toString().padStart(4, \"0\");\n}\n\nfunction trimTrailingSlash(prefix: string): string {\n return prefix.endsWith(\"/\") ? prefix.slice(0, -1) : prefix;\n}\n\nfunction cleanupDir(dir: string): void {\n try {\n // Cloud Run re-uses an instance's filesystem across requests; clean up\n // aggressively so we don't leak a chunk-sized footprint between renders\n // (the writable filesystem counts against the instance's memory).\n rmSync(dir, { recursive: true, force: true });\n } catch {\n // Best-effort \u2014 leak is preferable to crashing on the success path.\n }\n}\n\n/**\n * Read the untarred planDir's `plan.json` and assert its `planHash` matches\n * what the workflow event claims. Throws on mismatch with a typed\n * `PLAN_HASH_MISMATCH` error name so the workflow's non-retryable list\n * routes it correctly. Defense-in-depth \u2014 the producer's `renderChunk` does\n * the same check internally \u2014 but performing it here lets us fail before\n * paying the Chrome-launch + per-frame capture cost on a misrouted chunk.\n */\n// fallow-ignore-next-line complexity\nfunction verifyPlanHash(planDir: string, expected: string): void {\n const planJsonPath = join(planDir, \"plan.json\");\n let parsed: { planHash?: unknown };\n try {\n parsed = JSON.parse(readFileSync(planJsonPath, \"utf-8\")) as { planHash?: unknown };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const error = new Error(`PLAN_HASH_MISMATCH: failed to read ${planJsonPath}: ${msg}`);\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n }\n const actual = parsed.planHash;\n if (typeof actual !== \"string\" || actual !== expected) {\n const error = new Error(\n `PLAN_HASH_MISMATCH: event PlanHash=${expected} did not match plan.json planHash=${String(actual)}`,\n );\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n }\n}\n\n// \u2500\u2500 HTTP shell \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Error names the workflow treats as non-retryable. A request that fails\n * with one of these is the caller's fault (bad input, misrouted chunk) and\n * retrying it just burns instance-seconds, so we map them to HTTP 400 while\n * any other failure maps to 500 (which the workflow retry policy backs off\n * and re-attempts). Keep this list in sync with the `retry` predicate in\n * `packages/gcp-cloud-run/terraform/workflow.yaml`.\n */\nconst NON_RETRYABLE_ERROR_NAMES = new Set([\n // Handler-boundary guards.\n \"GCS_URI_NOT_ALLOWED\",\n \"PLAN_HASH_MISMATCH\",\n \"PLAN_ARTIFACT_DIGEST_MISMATCH\",\n \"PLAN_PROTOCOL_UNSUPPORTED\",\n \"PLAN_V2_INTEGRITY_UNRECOVERABLE\",\n \"VIDEO_SOURCE_UNRENDERABLE\",\n \"INVALID_VIDEO_METADATA\",\n \"NOT_MEDIA_PAYLOAD\",\n // Producer error class names (`.name`) + their string code aliases \u2014 the\n // class sets `.name` to the class name but wraps a `code`; cover both so a\n // raw-code throw is caught too. Mirrors the AWS state machine's\n // non-retryable list.\n \"FormatNotSupportedInDistributedError\",\n \"NotMediaPayloadError\",\n \"PlanTooLargeError\",\n \"PlanProtocolUnsupportedError\",\n \"PlanV2IntegrityError\",\n \"RenderChunkValidationError\",\n \"FFMPEG_VERSION_MISMATCH\",\n \"FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED\",\n \"PLAN_TOO_LARGE\",\n \"BROWSER_GPU_NOT_SOFTWARE\",\n \"FONT_FETCH_FAILED\",\n \"ChromeBinaryUnavailableError\",\n]);\n\n/**\n * Build the Hono app. A single `POST /` endpoint dispatches on the body's\n * `Action` field \u2014 the workflow points every step (plan, each renderChunk,\n * assemble) at the same URL and varies only the body. `GET /healthz` backs\n * the Cloud Run startup/liveness probe.\n *\n * `deps` is threaded through so tests can drive the real HTTP surface with\n * an injected Storage double + mocked primitives.\n */\nexport function createApp(deps?: HandlerDeps): Hono {\n const app = new Hono();\n\n app.get(\"/healthz\", (c) => c.json({ status: \"ok\" }));\n\n // fallow-ignore-next-line complexity\n app.post(\"/\", async (c) => {\n let body: CloudRunEvent;\n try {\n body = (await c.req.json()) as CloudRunEvent;\n } catch {\n return c.json({ error: \"BAD_REQUEST\", message: \"request body must be JSON\" }, 400);\n }\n try {\n const result = await dispatch(body, deps);\n return c.json(result, 200);\n } catch (err) {\n const name = err instanceof Error ? err.name : undefined;\n const message = err instanceof Error ? err.message : String(err);\n const status = name && NON_RETRYABLE_ERROR_NAMES.has(name) ? 400 : 500;\n // Surface `error` (the name) as the discriminator the workflow's\n // retry predicate keys off, plus `message` for human triage.\n return c.json({ error: name ?? \"RenderError\", message }, status);\n }\n });\n\n return app;\n}\n\n/** Start the HTTP server. Cloud Run injects `PORT` (default 8080). */\nexport function startServer(): void {\n const port = Number(process.env.PORT ?? 8080);\n const app = createApp();\n serve({ fetch: app.fetch, port }, (info) => {\n logEvent({ event: \"server_listening\", port: info.port });\n });\n}\n\n// Boot when executed directly (the Dockerfile runs `node dist/server.js`),\n// but not when imported by tests or the SDK.\nif (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {\n startServer();\n}\n", "/**\n * Cloud Run Chrome resolver.\n *\n * `renderChunk()` (the only primitive that needs a browser) launches Chrome\n * via the engine's `BrowserManager`. Because Cloud Run runs a container\n * image rather than a size-capped ZIP, the Chrome story is far simpler than\n * the Lambda adapter's: the `Dockerfile` installs `chrome-headless-shell`\n * into the image at a known path and exports `HYPERFRAMES_CHROME_PATH`.\n * The Dockerfile proves that exact executable's full BeginFrame screenshot\n * contract during the image build. There is no runtime decompression-into-\n * /tmp step and no 250 MB packaging ceiling to fight.\n *\n * Resolution order:\n * 1. `PRODUCER_HEADLESS_SHELL_PATH` \u2014 the engine's own override. If a\n * caller (or the Docker image) already set it, honour it untouched.\n * 2. `HYPERFRAMES_CHROME_PATH` \u2014 set by the Dockerfile to the installed\n * `chrome-headless-shell` binary.\n * 3. A small list of conventional install paths, as a last resort for\n * images built outside our Dockerfile.\n *\n * Throws {@link ChromeBinaryUnavailableError} when nothing resolves, so a\n * misconfigured image fails loudly at the first chunk rather than emitting\n * a confusing puppeteer-core \"executablePath must be specified\" assertion.\n */\n\nimport { existsSync } from \"node:fs\";\n\n/**\n * Thrown when the Chrome binary resolver can't produce a usable path. The\n * class name is the workflow's non-retryable error discriminator.\n */\nexport class ChromeBinaryUnavailableError extends Error {\n // Read indirectly via the error envelope / Error.prototype.toString.\n // fallow-ignore-next-line unused-class-member\n override readonly name = \"ChromeBinaryUnavailableError\";\n readonly resolvedPath: string | null;\n constructor(resolvedPath: string | null, hint: string) {\n super(`[chromium] Chrome binary unavailable: ${hint}`);\n this.resolvedPath = resolvedPath;\n }\n}\n\n/**\n * Conventional locations a `chrome-headless-shell` (or full Chrome) binary\n * may live at in a Debian/Ubuntu-based container. Checked only after the\n * two env-var overrides miss.\n */\nconst FALLBACK_CHROME_PATHS = [\n \"/opt/chrome/chrome-headless-shell\",\n \"/usr/bin/chrome-headless-shell\",\n \"/usr/bin/google-chrome\",\n \"/usr/bin/google-chrome-stable\",\n \"/usr/bin/chromium\",\n \"/usr/bin/chromium-browser\",\n];\n\n/**\n * Resolve the absolute path to a Chrome binary suitable for BeginFrame.\n * Pure (no env mutation) so callers decide whether to export the result\n * into `PRODUCER_HEADLESS_SHELL_PATH`.\n */\n// fallow-ignore-next-line complexity\nexport function resolveChromeExecutablePath(): string {\n const fromEngineOverride = process.env.PRODUCER_HEADLESS_SHELL_PATH?.trim();\n if (fromEngineOverride) {\n if (!existsSync(fromEngineOverride)) {\n throw new ChromeBinaryUnavailableError(\n fromEngineOverride,\n `PRODUCER_HEADLESS_SHELL_PATH=${JSON.stringify(fromEngineOverride)} does not exist on disk.`,\n );\n }\n return fromEngineOverride;\n }\n\n const fromImage = process.env.HYPERFRAMES_CHROME_PATH?.trim();\n if (fromImage) {\n if (!existsSync(fromImage)) {\n throw new ChromeBinaryUnavailableError(\n fromImage,\n `HYPERFRAMES_CHROME_PATH=${JSON.stringify(fromImage)} does not exist on disk.`,\n );\n }\n return fromImage;\n }\n\n for (const candidate of FALLBACK_CHROME_PATHS) {\n if (existsSync(candidate)) return candidate;\n }\n\n throw new ChromeBinaryUnavailableError(\n null,\n \"no Chrome binary found. Set HYPERFRAMES_CHROME_PATH (the Dockerfile does this) or \" +\n \"PRODUCER_HEADLESS_SHELL_PATH to the absolute path of a chrome-headless-shell binary. \" +\n `Searched: ${FALLBACK_CHROME_PATHS.join(\", \")}.`,\n );\n}\n", "/**\n * Map a distributed `format` to the file extension the assembled output\n * should carry on disk + in GCS. Shared by `src/server.ts` (chunk +\n * assemble output paths) and `src/sdk/renderToCloudRun.ts` (final\n * output key construction) so the two sides agree on what an mp4\n * looks like vs a png-sequence.\n */\n\nimport type { DistributedFormat } from \"@hyperframes/producer/distributed\";\n\nexport type { DistributedFormat } from \"@hyperframes/producer/distributed\";\n\n// Closed-enum lookup table. TS enforces exhaustiveness via the\n// `Record<DistributedFormat, string>` annotation \u2014 adding a format to\n// `DistributedFormat` without adding the matching key here fails to\n// typecheck, which is the same exhaustiveness guarantee a switch +\n// `_exhaustive: never` arm provides but at lower complexity.\nconst FORMAT_EXTENSIONS: Record<DistributedFormat, string> = {\n mp4: \".mp4\",\n mov: \".mov\",\n webm: \".webm\",\n \"png-sequence\": \"\",\n};\n\nexport function formatExtension(format: DistributedFormat): string {\n return FORMAT_EXTENSIONS[format];\n}\n", "/**\n * Thin GCS transport for the Cloud Run handler.\n *\n * The OSS distributed primitives are pure functions over local file paths;\n * the handler bridges GCS \u2194 the container's writable `/tmp` filesystem on\n * each request. Functions here are intentionally narrow: parse a URI,\n * download an object to a local path, upload a path, tar-pack a planDir,\n * tar-extract a planDir back out.\n *\n * Tar (not zip) for planDir transit:\n * - planDirs contain symlinks (the extract stage materializes them but\n * the compiled/ subtree may include linked assets); tar preserves them,\n * zip does not.\n * - We use the `tar` npm package (pure JS over `node:zlib`) so the\n * archive format doesn't depend on a system `tar`/`unzip` being present\n * in the container image.\n *\n * Apart from the `gs://` scheme and the `@google-cloud/storage` client this\n * is the same shape as `@hyperframes/aws-lambda`'s `s3Transport.ts`.\n */\n\nimport {\n createReadStream,\n createWriteStream,\n existsSync,\n mkdirSync,\n rmSync,\n statSync,\n} from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { dirname } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { Storage } from \"@google-cloud/storage\";\nimport * as tar from \"tar\";\n\n/** Parsed `gs://bucket/key` URI. */\nexport interface GcsLocation {\n bucket: string;\n key: string;\n}\n\n/** Parse `gs://bucket/key/path` \u2192 `{ bucket, key }`. Throws on malformed input. */\n// fallow-ignore-next-line complexity\nexport function parseGcsUri(uri: string): GcsLocation {\n if (!uri.startsWith(\"gs://\")) {\n throw new Error(`[gcsTransport] expected gs:// URI, got: ${JSON.stringify(uri)}`);\n }\n const rest = uri.slice(\"gs://\".length);\n const slash = rest.indexOf(\"/\");\n if (slash === -1) {\n throw new Error(`[gcsTransport] missing key in gs URI: ${JSON.stringify(uri)}`);\n }\n const bucket = rest.slice(0, slash);\n const key = rest.slice(slash + 1);\n if (!bucket || !key) {\n throw new Error(`[gcsTransport] empty bucket or key in gs URI: ${JSON.stringify(uri)}`);\n }\n return { bucket, key };\n}\n\n/** Build `gs://bucket/key` from a location. */\nexport function formatGcsUri(loc: GcsLocation): string {\n return `gs://${loc.bucket}/${loc.key}`;\n}\n\n/** Stream a GCS object to a local file path. */\nexport async function downloadGcsObjectToFile(\n storage: Storage,\n uri: string,\n destPath: string,\n): Promise<void> {\n const { bucket, key } = parseGcsUri(uri);\n mkdirSync(dirname(destPath), { recursive: true });\n const file = storage.bucket(bucket).file(key);\n // `createReadStream` streams the object body; piping into a write stream\n // keeps memory flat for large plan tarballs / chunk files rather than\n // buffering the whole object the way `file.download()` would.\n await pipeline(file.createReadStream(), createWriteStream(destPath));\n}\n\n/** Download and verify an immutable plan-v2 artifact before materialization. */\nexport async function downloadGcsObjectToFileVerified(\n storage: Storage,\n uri: string,\n destPath: string,\n expectedSha256: string,\n): Promise<void> {\n assertSha256(expectedSha256);\n await downloadGcsObjectToFile(storage, uri, destPath);\n const actual = await sha256File(destPath);\n if (actual !== expectedSha256) {\n rmSync(destPath, { force: true });\n const error = new Error(\n `[gcsTransport] PLAN_ARTIFACT_DIGEST_MISMATCH: ${uri} expected ${expectedSha256}, got ${actual}`,\n );\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n }\n}\n\n/**\n * Upload a local file's contents to a GCS URI using a resumable upload.\n * GCS objects have no practical size ceiling for the artifacts this adapter\n * handles (plan tarballs \u2264 2 GB, chunks \u2264 a few hundred MB), so a single\n * upload call works for every case.\n */\nexport async function uploadFileToGcs(\n storage: Storage,\n localPath: string,\n uri: string,\n contentType?: string,\n): Promise<void> {\n if (!existsSync(localPath)) {\n throw new Error(`[gcsTransport] upload source missing: ${localPath}`);\n }\n const { bucket, key } = parseGcsUri(uri);\n await storage.bucket(bucket).upload(localPath, {\n destination: key,\n // `resumable: false` (simple upload) is faster for the small-to-medium\n // objects this adapter moves and avoids the extra round-trip a resumable\n // session start costs; GCS recommends resumable only past ~8 MB but our\n // chunks are reliably above that, so let the client pick by default.\n contentType,\n });\n}\n\n/**\n * Upload one content-addressed plan-v2 artifact exactly once.\n *\n * The zero-generation precondition makes creation atomic. Existing objects\n * are reused only when their immutable digest metadata and byte length agree;\n * a conflict is never overwritten because another render may already consume\n * that object.\n */\nexport async function uploadContentAddressedFileToGcs(\n storage: Storage,\n localPath: string,\n uri: string,\n expectedSha256: string,\n contentType?: string,\n): Promise<\"uploaded\" | \"reused\"> {\n assertSha256(expectedSha256);\n if (!existsSync(localPath)) {\n throw new Error(`[gcsTransport] upload source missing: ${localPath}`);\n }\n const actualSha256 = await sha256File(localPath);\n if (actualSha256 !== expectedSha256) {\n throwDigestMismatch(\n `local artifact ${localPath} expected ${expectedSha256}, got ${actualSha256}`,\n );\n }\n\n const { bucket, key } = parseGcsUri(uri);\n const bucketHandle = storage.bucket(bucket);\n const file = bucketHandle.file(key);\n const size = statSync(localPath).size;\n if (await isReusableContentAddressedObject(file, uri, size, expectedSha256)) {\n return \"reused\";\n }\n\n try {\n await bucketHandle.upload(localPath, {\n destination: key,\n contentType,\n metadata: { metadata: { sha256: expectedSha256 } },\n preconditionOpts: { ifGenerationMatch: 0 },\n });\n return \"uploaded\";\n } catch (error) {\n // A concurrent planner may win the create-only race. Reuse only after\n // verifying that the winning object is exactly the immutable CAS value.\n if (\n isGcsPreconditionFailed(error) &&\n (await isReusableContentAddressedObject(file, uri, size, expectedSha256))\n ) {\n return \"reused\";\n }\n throw error;\n }\n}\n\ninterface GcsFileLike {\n exists(): Promise<[boolean, ...unknown[]]>;\n getMetadata(): Promise<\n [\n {\n size?: string | number;\n metadata?: Record<string, string | number | boolean | null>;\n },\n ...unknown[],\n ]\n >;\n}\n\nasync function isReusableContentAddressedObject(\n file: GcsFileLike,\n uri: string,\n expectedSize: number,\n expectedSha256: string,\n): Promise<boolean> {\n const [exists] = await file.exists();\n if (!exists) return false;\n const [metadata] = await file.getMetadata();\n if (Number(metadata.size) === expectedSize && metadata.metadata?.sha256 === expectedSha256) {\n return true;\n }\n throwDigestMismatch(\n `immutable object ${uri} already exists with different digest metadata or size`,\n );\n}\n\nexport async function sha256File(path: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(path)) {\n hash.update(chunk as Buffer);\n }\n return hash.digest(\"hex\");\n}\n\nfunction assertSha256(value: string): void {\n if (!/^[a-f0-9]{64}$/.test(value)) {\n throw new Error(\n `[gcsTransport] expected lowercase SHA-256 digest, got ${JSON.stringify(value)}`,\n );\n }\n}\n\nfunction throwDigestMismatch(detail: string): never {\n const error = new Error(`[gcsTransport] PLAN_ARTIFACT_DIGEST_MISMATCH: ${detail}`);\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n}\n\nfunction isGcsPreconditionFailed(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n return (error as { code?: unknown }).code === 412;\n}\n\n/**\n * Pack a directory into a `.tar.gz` at `destTarball`. Uses the `tar` npm\n * package (pure JS over `node:zlib`) rather than spawning a system tar\n * binary so the archive format is independent of the container's userland.\n */\nexport async function tarDirectory(sourceDir: string, destTarball: string): Promise<void> {\n if (!existsSync(sourceDir) || !statSync(sourceDir).isDirectory()) {\n throw new Error(`[gcsTransport] tar source must be an existing directory: ${sourceDir}`);\n }\n mkdirSync(dirname(destTarball), { recursive: true });\n await tar.create({ gzip: true, file: destTarball, cwd: sourceDir }, [\".\"]);\n}\n\n/**\n * Extract a `.tar.gz` produced by {@link tarDirectory} into `destDir`.\n * The directory is created (or cleared) before extraction so a retried\n * request doesn't observe stale files from a prior run on the same warm\n * container instance.\n */\nexport async function untarDirectory(tarballPath: string, destDir: string): Promise<void> {\n if (!existsSync(tarballPath)) {\n throw new Error(`[gcsTransport] tarball missing: ${tarballPath}`);\n }\n // Wipe target so a warm container instance's prior planDir doesn't bleed\n // into the new request. Cloud Run re-uses the instance filesystem across\n // requests served by the same instance.\n if (existsSync(destDir)) {\n rmSync(destDir, { recursive: true, force: true });\n }\n mkdirSync(destDir, { recursive: true });\n await tar.extract({ file: tarballPath, cwd: destDir });\n}\n", "// fallow-ignore-file code-duplication\nimport { createHash } from \"node:crypto\";\nimport { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { Storage } from \"@google-cloud/storage\";\nimport {\n PlanV2IntegrityError,\n type PlanV2ArtifactPublisher,\n type PlanV2PublishBlob,\n} from \"@hyperframes/producer/distributed\";\nimport { parseGcsUri, uploadContentAddressedFileToGcs } from \"./gcsTransport.js\";\n\nexport interface GcsPlanV2ArtifactPublisherOptions {\n readonly storage: Storage;\n /** Validated render output prefix from which all v2 object keys are derived. */\n readonly planOutputGcsPrefix: string;\n /** Planner-local scratch parent for the small manifest upload file. */\n readonly temporaryRoot?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction assertSha256(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !/^[a-f0-9]{64}$/.test(value)) {\n throw new PlanV2IntegrityError(`${label} must be a lowercase SHA-256 digest`);\n }\n return value;\n}\n\nfunction manifestDigests(manifestBytes: string): ReadonlySet<string> {\n let value: unknown;\n try {\n value = JSON.parse(manifestBytes);\n } catch {\n throw new PlanV2IntegrityError(\"GCS publisher received invalid manifest JSON\");\n }\n if (!isRecord(value) || !Array.isArray(value.artifacts)) {\n throw new PlanV2IntegrityError(\"GCS publisher manifest requires an artifacts array\");\n }\n return new Set(\n value.artifacts.map((artifact, index) => {\n if (!isRecord(artifact)) {\n throw new PlanV2IntegrityError(`GCS publisher artifacts[${index}] must be an object`);\n }\n return assertSha256(artifact.sha256, `GCS publisher artifacts[${index}].sha256`);\n }),\n );\n}\n\nfunction trimTrailingSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return value.slice(0, end);\n}\n\n/**\n * Manifest-last GCS implementation of the producer's plan-v2 publication seam.\n *\n * Every path remains private to the planner container. Remote workers receive\n * only the manifest URI and artifact prefix and materialize their own target.\n */\nexport class GcsPlanV2ArtifactPublisher implements PlanV2ArtifactPublisher {\n readonly artifactPrefix: string;\n readonly manifestUri: string;\n readonly #storage: Storage;\n readonly #temporaryRoot: string;\n readonly #publishedDigests = new Set<string>();\n #state: \"open\" | \"committed\" | \"aborted\" = \"open\";\n\n constructor(options: Readonly<GcsPlanV2ArtifactPublisherOptions>) {\n const outputPrefix = `${trimTrailingSlash(options.planOutputGcsPrefix)}/v2`;\n parseGcsUri(outputPrefix);\n this.#storage = options.storage;\n this.artifactPrefix = `${outputPrefix}/artifacts/sha256`;\n this.manifestUri = `${outputPrefix}/manifest.json`;\n this.#temporaryRoot = options.temporaryRoot ?? tmpdir();\n mkdirSync(this.#temporaryRoot, { recursive: true });\n }\n\n async putBlob(blob: Readonly<PlanV2PublishBlob>): Promise<void> {\n this.#assertOpen(\"publish a blob\");\n const digest = assertSha256(blob.sha256, \"GCS published blob sha256\");\n const sourceSize = statSync(blob.sourcePath).size;\n if (sourceSize !== blob.sizeBytes) {\n throw new PlanV2IntegrityError(\n `GCS published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`,\n );\n }\n const uri = `${this.artifactPrefix}/${digest.slice(0, 2)}/${digest}`;\n await uploadContentAddressedFileToGcs(this.#storage, blob.sourcePath, uri, digest);\n this.#publishedDigests.add(digest);\n }\n\n async commitManifest(manifestBytes: string): Promise<void> {\n this.#assertOpen(\"commit a manifest\");\n for (const digest of manifestDigests(manifestBytes)) {\n if (!this.#publishedDigests.has(digest)) {\n throw new PlanV2IntegrityError(\n `cannot commit GCS manifest before referenced blob is durable: ${digest}`,\n );\n }\n }\n\n const manifestDigest = createHash(\"sha256\").update(manifestBytes, \"utf8\").digest(\"hex\");\n const stagingDir = mkdtempSync(join(this.#temporaryRoot, \"hf-plan-v2-manifest-\"));\n const manifestPath = join(stagingDir, \"manifest.json\");\n try {\n writeFileSync(manifestPath, manifestBytes, \"utf8\");\n await uploadContentAddressedFileToGcs(\n this.#storage,\n manifestPath,\n this.manifestUri,\n manifestDigest,\n \"application/json\",\n );\n this.#state = \"committed\";\n } finally {\n rmSync(stagingDir, { recursive: true, force: true });\n }\n }\n\n async abort(): Promise<void> {\n if (this.#state === \"open\") this.#state = \"aborted\";\n // Immutable CAS blobs may be shared with or reused by another retry.\n // Unreferenced blobs expire under the bucket's intermediate lifecycle.\n }\n\n #assertOpen(operation: string): void {\n if (this.#state !== \"open\") {\n throw new PlanV2IntegrityError(`cannot ${operation} after publisher is ${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,GAAG,CAAC,SAAS;AAC1C,aAAS,EAAE,OAAO,oBAAoB,MAAM,KAAK,KAAK,CAAC;AAAA,EACzD,CAAC;AACH;AAIA,IAAI,QAAQ,KAAK,CAAC,KAAK,cAAc,YAAY,GAAG,MAAM,QAAQ,KAAK,CAAC,GAAG;AACzE,cAAY;AACd;",
|
|
4
|
+
"sourcesContent": ["/**\n * Cloud Run request handler for HyperFrames distributed rendering.\n *\n * One container image, three roles. Cloud Workflows POSTs a JSON body with\n * an `Action` field; the handler unwraps any `Payload`/`Input` envelope,\n * primes the runtime (Chrome path), and forwards to the matching OSS\n * primitive from `@hyperframes/producer/distributed`.\n *\n * Everything heavy \u2014 capture, encode, audio mix \u2014 happens inside the OSS\n * primitives. The handler is thin glue: parse body \u2192 GCS download \u2192 call\n * primitive \u2192 GCS upload \u2192 return small JSON result.\n *\n * `dispatch()` is the testable core (inject `storage` + `primitives`); the\n * Hono app at the bottom is the HTTP shell the Dockerfile runs. The shape\n * deliberately tracks `@hyperframes/aws-lambda`'s `handler.ts` so the two\n * adapters stay easy to diff.\n */\n\nimport { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, extname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { serve } from \"@hono/node-server\";\nimport { Storage } from \"@google-cloud/storage\";\nimport { Hono } from \"hono\";\nimport {\n assemble,\n type AssembleResult,\n type ChunkRenderer,\n type ChunkResult,\n type DistributedRenderConfig,\n listPlanV2ArtifactsForTarget,\n materializePlanV2Target,\n plan,\n isPlanAudioArtifactPath,\n PLAN_AUDIO_RELATIVE_PATH,\n resolvePlanAudioPath,\n planV2WithPublisher,\n type PlanResult,\n type PlanV2Artifact,\n type PlanV2Manifest,\n type PlanV2MaterializationTarget,\n readPlanV2Manifest,\n renderChunk,\n} from \"@hyperframes/producer/distributed\";\nimport { resolveChromeExecutablePath } from \"./chromium.js\";\nimport type {\n AssembleEvent,\n AssembleV2Event,\n AssembleResultBody,\n CloudRunAction,\n CloudRunEvent,\n CloudRunResult,\n PlanEvent,\n PlanV2Event,\n PlanResultBody,\n RenderChunkEvent,\n RenderChunkV2Event,\n RenderChunkResultBody,\n} from \"./events.js\";\nimport { type DistributedFormat, formatExtension } from \"./formatExtension.js\";\nimport {\n downloadGcsObjectToFile,\n downloadGcsObjectToFileVerified,\n parseGcsUri,\n tarDirectory,\n untarDirectory,\n uploadFileToGcs,\n} from \"./gcsTransport.js\";\nimport { GcsPlanV2ArtifactPublisher } from \"./gcsPlanV2Publisher.js\";\n\n/**\n * Lazily-constructed Storage client. Cached at module scope so warm\n * container instances reuse the underlying HTTP keep-alive pool across\n * requests.\n */\nlet cachedStorage: Storage | null = null;\nfunction getStorage(): Storage {\n if (cachedStorage) return cachedStorage;\n cachedStorage = new Storage();\n return cachedStorage;\n}\n\n/**\n * Optional injection points used by the handler's unit tests. Production\n * callers leave these unset; the real OSS primitives are used. Tests inject\n * `storage` and `primitives` directly rather than mutating module state.\n */\nexport interface HandlerDeps {\n storage?: Storage;\n primitives?: {\n plan: typeof plan;\n planV2WithPublisher?: typeof planV2WithPublisher;\n renderChunk: ChunkRenderer;\n assemble: typeof assemble;\n };\n /** Override the per-request workdir root (defaults to the OS tmpdir). */\n tmpRoot?: string;\n /** Skip Chrome resolution (used by dispatch tests that mock renderChunk). */\n skipChromeResolution?: boolean;\n}\n\n/**\n * Dispatch a single render request. Cloud Workflows (or a direct caller)\n * sometimes wraps the body in `{ Payload: ... }` or `{ Input: ... }`; unwrap\n * until we hit a discriminated event.\n */\n// fallow-ignore-next-line complexity\nexport async function dispatch(event: CloudRunEvent, deps?: HandlerDeps): Promise<CloudRunResult> {\n const unwrapped = unwrapEvent(event);\n validatePlanProtocolShape(unwrapped);\n validateEventGcsUris(unwrapped);\n logEvent({ event: \"handler_start\", action: unwrapped.Action, input: summarizeEvent(unwrapped) });\n try {\n switch (unwrapped.Action) {\n case \"plan\":\n return await handlePlan(unwrapped, deps);\n case \"renderChunk\":\n return await handleRenderChunk(unwrapped, deps);\n case \"assemble\":\n return await handleAssemble(unwrapped, deps);\n default: {\n // Compile-time exhaustiveness: a new CloudRunAction member trips\n // the `never` assignment before the runtime error is reachable.\n const _exhaustive: never = unwrapped;\n throw new Error(\n `[handler] unknown Action: ${JSON.stringify(\n (_exhaustive as { Action?: string }).Action,\n )}. Expected one of \"plan\", \"renderChunk\", \"assemble\".`,\n );\n }\n }\n } catch (err) {\n normalizeTerminalErrorName(err);\n logEvent({\n event: \"handler_error\",\n action: unwrapped.Action,\n input: summarizeEvent(unwrapped),\n message: err instanceof Error ? err.message : String(err),\n name: err instanceof Error ? err.name : undefined,\n });\n throw err;\n }\n}\n\n// This is the single fail-closed boundary for the wire union. Keeping all\n// forbidden locator combinations together makes mixed-protocol input auditable.\n// fallow-ignore-next-line complexity\nfunction validatePlanProtocolShape(event: PlanEvent | RenderChunkEvent | AssembleEvent): void {\n const raw = event as unknown as Record<string, unknown>;\n const protocol = raw.PlanProtocol;\n if (protocol !== undefined && protocol !== \"v1\" && protocol !== \"v2\") {\n const error = new Error(\n `[handler] unsupported PlanProtocol ${JSON.stringify(protocol)}; expected \"v1\", \"v2\", or absent`,\n );\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n if (event.Action === \"plan\") return;\n\n const effectiveProtocol = protocol ?? \"v2\";\n const hasV1Locator = typeof raw.PlanGcsUri === \"string\";\n const hasV2Manifest = typeof raw.PlanV2ManifestGcsUri === \"string\";\n const hasV2Prefix = typeof raw.PlanV2ArtifactGcsPrefix === \"string\";\n const valid =\n effectiveProtocol === \"v2\"\n ? !hasV1Locator && hasV2Manifest && hasV2Prefix\n : hasV1Locator && !hasV2Manifest && !hasV2Prefix;\n if (!valid) {\n const error = new Error(\n `[handler] ${effectiveProtocol} ${event.Action} event has mixed or missing plan locators`,\n );\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n if (effectiveProtocol === \"v2\" && event.Action === \"assemble\" && event.AudioGcsUri !== null) {\n const error = new Error(\"[handler] v2 assemble audio must be materialized from the manifest\");\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n}\n\n/** Normalize producer error codes to the stable HTTP/workflow discriminator. */\n// The explicit mapping is the public Cloud Workflows retry contract.\n// fallow-ignore-next-line complexity\nfunction normalizeTerminalErrorName(error: unknown): void {\n if (!error || typeof error !== \"object\") return;\n const candidate = error as { code?: unknown; name?: string };\n if (\n candidate.code === \"PLAN_PROTOCOL_UNSUPPORTED\" ||\n candidate.code === \"PLAN_TOO_LARGE\" ||\n candidate.code === \"PLAN_V2_INTEGRITY_UNRECOVERABLE\" ||\n candidate.code === \"FONT_FETCH_FAILED\" ||\n candidate.code === \"FONT_FETCH_UNAVAILABLE\" ||\n candidate.code === \"VIDEO_SOURCE_UNRENDERABLE\" ||\n candidate.code === \"VIDEO_EXTRACTION_FAILED\" ||\n candidate.code === \"INVALID_VIDEO_METADATA\"\n ) {\n candidate.name = candidate.code;\n }\n}\n\n// At most `{Payload: {Input: ...}}` is expected; 4 levels is 2\u00D7 headroom\n// and prevents infinite loops on malformed input.\nconst MAX_ENVELOPE_DEPTH = 4;\n\n// fallow-ignore-next-line complexity\nexport function unwrapEvent(event: CloudRunEvent): PlanEvent | RenderChunkEvent | AssembleEvent {\n let cursor: CloudRunEvent = event;\n for (let i = 0; i < MAX_ENVELOPE_DEPTH; i++) {\n if (cursor && typeof cursor === \"object\") {\n const obj = cursor as Record<string, unknown>;\n if (typeof obj.Action === \"string\" && isCloudRunAction(obj.Action)) {\n return cursor as PlanEvent | RenderChunkEvent | AssembleEvent;\n }\n if (\"Payload\" in obj) {\n cursor = obj.Payload as CloudRunEvent;\n continue;\n }\n if (\"Input\" in obj) {\n cursor = obj.Input as CloudRunEvent;\n continue;\n }\n }\n break;\n }\n throw new Error(\n `[handler] body has no recognised Action; unwrapped ${MAX_ENVELOPE_DEPTH} levels of Payload/Input without finding one.`,\n );\n}\n\nfunction isCloudRunAction(value: string): value is CloudRunAction {\n return value === \"plan\" || value === \"renderChunk\" || value === \"assemble\";\n}\n\n/**\n * Emit a single JSON line to stdout. Cloud Logging ingests each stdout line\n * as a structured `jsonPayload` entry, so Logs Explorer can filter on\n * `jsonPayload.event=\"handler_start\"` and project specific fields when\n * triaging without attaching a debugger.\n */\nfunction logEvent(payload: Record<string, unknown>): void {\n console.log(JSON.stringify(payload));\n}\n\n/**\n * Compact, non-PII summary of an event for logging. The full body can\n * include the entire project config; we only emit the routable fields\n * needed to triage a failure from Cloud Logging.\n */\n// Keep event variants together so Cloud Logging has one redaction boundary.\n// fallow-ignore-next-line complexity\nfunction summarizeEvent(\n event: PlanEvent | RenderChunkEvent | AssembleEvent,\n): Record<string, unknown> {\n switch (event.Action) {\n case \"plan\":\n return {\n projectGcsUri: event.ProjectGcsUri,\n planOutputGcsPrefix: event.PlanOutputGcsPrefix,\n planProtocol: event.PlanProtocol ?? \"v2\",\n format: event.Config.format,\n fps: event.Config.fps,\n };\n case \"renderChunk\":\n return {\n planProtocol: event.PlanProtocol ?? \"v2\",\n ...(event.PlanProtocol !== \"v1\"\n ? { planV2ManifestGcsUri: event.PlanV2ManifestGcsUri }\n : { planGcsUri: event.PlanGcsUri }),\n chunkIndex: event.ChunkIndex,\n format: event.Format,\n };\n case \"assemble\":\n return {\n planProtocol: event.PlanProtocol ?? \"v2\",\n ...(event.PlanProtocol !== \"v1\"\n ? { planV2ManifestGcsUri: event.PlanV2ManifestGcsUri }\n : { planGcsUri: event.PlanGcsUri }),\n chunkCount: event.ChunkGcsUris.length,\n hasAudio: event.AudioGcsUri !== null,\n outputGcsUri: event.OutputGcsUri,\n format: event.Format,\n };\n }\n}\n\n/**\n * Point the engine at the in-image Chrome binary. The OSS engine resolves\n * Chrome via `PRODUCER_HEADLESS_SHELL_PATH` first; set it once per instance\n * before invoking any browser-touching primitive. ffmpeg is on the image's\n * PATH (apt-installed by the Dockerfile), so nothing to prime there.\n */\nfunction primeChrome(deps?: HandlerDeps): void {\n if (deps?.skipChromeResolution) return;\n if (process.env.PRODUCER_HEADLESS_SHELL_PATH) return;\n process.env.PRODUCER_HEADLESS_SHELL_PATH = resolveChromeExecutablePath();\n}\n\n// \u2500\u2500 Plan \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// fallow-ignore-next-line complexity\nasync function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise<PlanResultBody> {\n if (event.PlanProtocol !== \"v1\") {\n return handlePlanV2(event, deps);\n }\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.plan ?? plan;\n\n // The producer's probe stage launches Chromium whenever the composition\n // needs a runtime duration probe or has unresolved sub-compositions, so\n // plan has to resolve Chrome the same way renderChunk does.\n primeChrome(deps);\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-plan-\"));\n const projectArchive = join(work, \"project.tar.gz\");\n const projectDir = join(work, \"project\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadGcsObjectToFile(storage, event.ProjectGcsUri, projectArchive);\n await untarDirectory(projectArchive, projectDir);\n\n const config: DistributedRenderConfig = {\n ...event.Config,\n };\n const result: PlanResult = await primitive(projectDir, config, planDir);\n\n // Upload the planDir as a single tarball. The workflow cannot pass a\n // directory-shaped artifact between steps; we serialize and rely on the\n // consumer (renderChunk / assemble) to untar. The audio artifact lives inside\n // planDir, so it already rides along in this tarball \u2014 every consumer\n // (including assemble) gets it from the untar. We deliberately do NOT\n // upload a separate audio object: it would duplicate the bytes on every\n // plan upload and be re-downloaded + overwritten by assemble. `AudioGcsUri`\n // stays in the result shape for wire compatibility but is null.\n const planTar = join(work, \"plan.tar.gz\");\n await tarDirectory(planDir, planTar);\n const planTarUri = `${trimTrailingSlash(event.PlanOutputGcsPrefix)}/plan.tar.gz`;\n const audioPath = join(planDir, PLAN_AUDIO_RELATIVE_PATH);\n const hasAudio = existsSync(audioPath) && statSync(audioPath).size > 0;\n await uploadFileToGcs(storage, planTar, planTarUri, \"application/gzip\");\n\n return {\n Action: \"plan\",\n PlanGcsUri: planTarUri,\n PlanHash: result.planHash,\n ChunkCount: result.chunkCount,\n TotalFrames: result.totalFrames,\n Fps: result.fps,\n Width: result.width,\n Height: result.height,\n Format: result.format,\n HasAudio: hasAudio,\n AudioGcsUri: null,\n FfmpegVersion: result.ffmpegVersion,\n ProducerVersion: result.producerVersion,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n/**\n * Publish immutable v2 artifacts directly to GCS, with the manifest as the\n * final commit point. Planner-local paths never cross a worker boundary.\n */\n// fallow-ignore-next-line complexity\nasync function handlePlanV2(\n event: PlanV2Event,\n deps?: HandlerDeps,\n): Promise<Extract<PlanResultBody, { PlanProtocol: \"v2\" }>> {\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.planV2WithPublisher ?? planV2WithPublisher;\n primeChrome(deps);\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-plan-v2-\"));\n const projectArchive = join(work, \"project.tar.gz\");\n const projectDir = join(work, \"project\");\n try {\n await downloadGcsObjectToFile(storage, event.ProjectGcsUri, projectArchive);\n await untarDirectory(projectArchive, projectDir);\n const publisher = new GcsPlanV2ArtifactPublisher({\n storage,\n planOutputGcsPrefix: event.PlanOutputGcsPrefix,\n temporaryRoot: work,\n });\n const manifest: PlanV2Manifest = await primitive(projectDir, { ...event.Config }, publisher, {\n stagingParentDir: work,\n });\n\n return {\n Action: \"plan\",\n PlanProtocol: \"v2\",\n PlanV2ManifestGcsUri: publisher.manifestUri,\n PlanV2ArtifactGcsPrefix: publisher.artifactPrefix,\n PlanHash: manifest.planHash,\n ChunkCount: manifest.chunkCount,\n TotalFrames: manifest.totalFrames,\n Fps: manifest.fps,\n Width: manifest.width,\n Height: manifest.height,\n Format: manifest.format,\n HasAudio: manifest.artifacts.some((artifact) => isPlanAudioArtifactPath(artifact.path)),\n AudioGcsUri: null,\n FfmpegVersion: manifest.ffmpegVersion,\n ProducerVersion: manifest.producerVersion,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// \u2500\u2500 RenderChunk \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// fallow-ignore-next-line complexity\nasync function handleRenderChunk(\n event: RenderChunkEvent,\n deps?: HandlerDeps,\n): Promise<RenderChunkResultBody> {\n if (event.PlanProtocol !== \"v1\") {\n return handleRenderChunkV2(event, deps);\n }\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.renderChunk ?? renderChunk;\n\n primeChrome(deps);\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-chunk-\"));\n const planTar = join(work, \"plan.tar.gz\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadGcsObjectToFile(storage, event.PlanGcsUri, planTar);\n await untarDirectory(planTar, planDir);\n\n // Verify the plan's hash matches what the workflow told us to render.\n // The producer's renderChunk re-checks internally (defense-in-depth),\n // but doing it here at the handler boundary lets us fail before paying\n // the Chrome-launch + render cost on a misrouted chunk. Throws a typed\n // PLAN_HASH_MISMATCH the workflow can route as non-retryable.\n verifyPlanHash(planDir, event.PlanHash);\n\n const chunkOutputBase = join(\n work,\n event.Format === \"png-sequence\"\n ? `chunk-${pad(event.ChunkIndex)}`\n : `chunk-${pad(event.ChunkIndex)}${formatExtension(event.Format)}`,\n );\n\n const result: ChunkResult = await primitive(planDir, event.ChunkIndex, chunkOutputBase);\n\n const chunkUri = await uploadChunkOutput(\n storage,\n result,\n event.ChunkOutputGcsPrefix,\n event.ChunkIndex,\n );\n\n return {\n Action: \"renderChunk\",\n ChunkGcsUri: chunkUri,\n ChunkIndex: event.ChunkIndex,\n Sha256: result.sha256,\n FramesEncoded: result.framesEncoded,\n CaptureMode: result.captureMode,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n/** Materialize only this chunk's verified v2 dependencies before rendering. */\n// fallow-ignore-next-line complexity\nasync function handleRenderChunkV2(\n event: RenderChunkV2Event,\n deps?: HandlerDeps,\n): Promise<RenderChunkResultBody> {\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.renderChunk ?? renderChunk;\n primeChrome(deps);\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-chunk-v2-\"));\n try {\n const planDir = await downloadAndMaterializePlanV2(\n storage,\n event,\n { role: \"chunk\", chunkIndex: event.ChunkIndex },\n work,\n );\n const chunkOutputBase = join(\n work,\n event.Format === \"png-sequence\"\n ? `chunk-${pad(event.ChunkIndex)}`\n : `chunk-${pad(event.ChunkIndex)}${formatExtension(event.Format)}`,\n );\n const result = await primitive(planDir, event.ChunkIndex, chunkOutputBase);\n const chunkUri = await uploadChunkOutput(\n storage,\n result,\n event.ChunkOutputGcsPrefix,\n event.ChunkIndex,\n );\n return {\n Action: \"renderChunk\",\n ChunkGcsUri: chunkUri,\n ChunkIndex: event.ChunkIndex,\n Sha256: result.sha256,\n FramesEncoded: result.framesEncoded,\n CaptureMode: result.captureMode,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\nasync function uploadChunkOutput(\n storage: Storage,\n result: ChunkResult,\n prefix: string,\n chunkIndex: number,\n): Promise<string> {\n const trimmed = trimTrailingSlash(prefix);\n if (result.outputKind === \"file\") {\n const ext = extname(result.outputPath);\n const uri = `${trimmed}/chunks/${pad(chunkIndex)}${ext}`;\n await uploadFileToGcs(storage, result.outputPath, uri);\n return uri;\n }\n // frame-dir: upload as a tarball so a single GCS object represents the\n // chunk. Assemble's png-sequence path expects a directory per chunk; it\n // untars on its end.\n const tarball = `${result.outputPath}.tar.gz`;\n await tarDirectory(result.outputPath, tarball);\n const uri = `${trimmed}/chunks/${pad(chunkIndex)}.tar.gz`;\n await uploadFileToGcs(storage, tarball, uri, \"application/gzip\");\n return uri;\n}\n\n// \u2500\u2500 Assemble \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// fallow-ignore-next-line complexity\nasync function handleAssemble(\n event: AssembleEvent,\n deps?: HandlerDeps,\n): Promise<AssembleResultBody> {\n if (event.PlanProtocol !== \"v1\") {\n return handleAssembleV2(event, deps);\n }\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.assemble ?? assemble;\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-assemble-\"));\n const planTar = join(work, \"plan.tar.gz\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadGcsObjectToFile(storage, event.PlanGcsUri, planTar);\n await untarDirectory(planTar, planDir);\n\n const chunkPaths = await downloadChunkObjects(storage, event.ChunkGcsUris, work, event.Format);\n\n // Audio rides inside the plan tarball, so it's already on disk after the\n // untar above \u2014 no separate download. Fall back to a supplied AudioGcsUri\n // only for backward compatibility with an older Plan that uploaded it\n // standalone.\n let audioPath: string | null = null;\n const planAudio = resolvePlanAudioPath(planDir) ?? join(planDir, PLAN_AUDIO_RELATIVE_PATH);\n if (existsSync(planAudio) && statSync(planAudio).size > 0) {\n audioPath = planAudio;\n } else if (event.AudioGcsUri) {\n audioPath = planAudio;\n await downloadGcsObjectToFile(storage, event.AudioGcsUri, audioPath);\n }\n\n const finalOutput =\n event.Format === \"png-sequence\"\n ? join(work, \"output-frames\")\n : join(work, `output${formatExtension(event.Format)}`);\n\n const result: AssembleResult = await primitive(planDir, chunkPaths, audioPath, finalOutput, {\n cfr: event.Cfr === true,\n });\n\n if (event.Format === \"png-sequence\") {\n const tarball = `${finalOutput}.tar.gz`;\n await tarDirectory(finalOutput, tarball);\n await uploadFileToGcs(storage, tarball, event.OutputGcsUri, \"application/gzip\");\n } else {\n await uploadFileToGcs(storage, finalOutput, event.OutputGcsUri);\n }\n\n return {\n Action: \"assemble\",\n OutputGcsUri: event.OutputGcsUri,\n FramesEncoded: result.framesEncoded,\n FileSize: result.fileSize,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n/**\n * Materialize the assembler target. Audio is declared assembler-only by the\n * v2 manifest and therefore is never downloaded by chunk workers.\n */\n// fallow-ignore-next-line complexity\nasync function handleAssembleV2(\n event: AssembleV2Event,\n deps?: HandlerDeps,\n): Promise<AssembleResultBody> {\n const started = Date.now();\n const storage = deps?.storage ?? getStorage();\n const primitive = deps?.primitives?.assemble ?? assemble;\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-cr-assemble-v2-\"));\n try {\n const planDir = await downloadAndMaterializePlanV2(storage, event, { role: \"assembler\" }, work);\n const audioPath = resolvePlanAudioPath(planDir);\n const chunkPaths = await downloadChunkObjects(storage, event.ChunkGcsUris, work, event.Format);\n const finalOutput =\n event.Format === \"png-sequence\"\n ? join(work, \"output-frames\")\n : join(work, `output${formatExtension(event.Format)}`);\n const result = await primitive(planDir, chunkPaths, audioPath, finalOutput, {\n cfr: event.Cfr === true,\n });\n if (event.Format === \"png-sequence\") {\n const tarball = `${finalOutput}.tar.gz`;\n await tarDirectory(finalOutput, tarball);\n await uploadFileToGcs(storage, tarball, event.OutputGcsUri, \"application/gzip\");\n } else {\n await uploadFileToGcs(storage, finalOutput, event.OutputGcsUri);\n }\n return {\n Action: \"assemble\",\n OutputGcsUri: event.OutputGcsUri,\n FramesEncoded: result.framesEncoded,\n FileSize: result.fileSize,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\nasync function downloadAndMaterializePlanV2(\n storage: Storage,\n event: {\n PlanV2ManifestGcsUri: string;\n PlanV2ArtifactGcsPrefix: string;\n PlanHash: string;\n },\n target: PlanV2MaterializationTarget,\n work: string,\n): Promise<string> {\n const transportDir = join(work, \"plan-v2\");\n mkdirSync(transportDir, { recursive: true });\n await downloadGcsObjectToFile(\n storage,\n event.PlanV2ManifestGcsUri,\n join(transportDir, \"plan.json\"),\n );\n const manifest = readPlanV2Manifest(transportDir);\n if (manifest.planHash !== event.PlanHash) {\n throwPlanHashMismatch(event.PlanHash, manifest.planHash);\n }\n const artifacts = listPlanV2ArtifactsForTarget(manifest, target);\n const uniqueArtifacts = [\n ...new Map(artifacts.map((artifact) => [artifact.sha256, artifact])).values(),\n ];\n await mapConcurrent(uniqueArtifacts, 16, async (artifact) => {\n await downloadPlanV2Artifact(storage, event.PlanV2ArtifactGcsPrefix, transportDir, artifact);\n });\n const planDir = join(work, \"plan\");\n materializePlanV2Target(transportDir, target, planDir);\n return planDir;\n}\n\nasync function downloadPlanV2Artifact(\n storage: Storage,\n artifactPrefix: string,\n planV2Dir: string,\n artifact: Readonly<PlanV2Artifact>,\n): Promise<void> {\n await downloadGcsObjectToFileVerified(\n storage,\n planV2BlobUri(artifactPrefix, artifact.sha256),\n planV2BlobPath(planV2Dir, artifact.sha256),\n artifact.sha256,\n );\n}\n\nfunction planV2BlobPath(planV2Dir: string, digest: string): string {\n return join(planV2Dir, \"artifacts\", \"sha256\", digest.slice(0, 2), digest);\n}\n\nfunction planV2BlobUri(prefix: string, digest: string): string {\n return `${trimTrailingSlash(prefix)}/${digest.slice(0, 2)}/${digest}`;\n}\n\nfunction throwPlanHashMismatch(expected: string, actual: string): never {\n const error = new Error(\n `PLAN_HASH_MISMATCH: event PlanHash=${expected} did not match v2 manifest planHash=${actual}`,\n );\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n}\n\nasync function mapConcurrent<T>(\n values: readonly T[],\n concurrency: number,\n fn: (value: T) => Promise<void>,\n): Promise<void> {\n let cursor = 0;\n async function worker(): Promise<void> {\n while (cursor < values.length) {\n const index = cursor++;\n await fn(values[index]!);\n }\n }\n const results = await Promise.allSettled(\n Array.from({ length: Math.min(concurrency, values.length) }, () => worker()),\n );\n const failure = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n // Invocation cleanup removes the work directory in `finally`. Drain all\n // sibling downloads before surfacing an error so a late GCS stream cannot\n // keep writing into scratch after another artifact fails verification.\n if (failure) throw failure.reason;\n}\n\nasync function downloadChunkObjects(\n storage: Storage,\n uris: string[],\n workDir: string,\n format: DistributedFormat,\n): Promise<string[]> {\n const chunksDir = join(workDir, \"chunks\");\n mkdirSync(chunksDir, { recursive: true });\n // Each chunk is an independent GCS GET (+ untar for png-sequence). Run\n // them in parallel \u2014 assemble's wall-clock is otherwise dominated by\n // `\u03A3 chunk-download-ms` instead of `max(chunk-download-ms)`. Preserve the\n // input order by writing into a pre-sized array rather than pushing as\n // each task settles.\n const local: string[] = new Array<string>(uris.length);\n await Promise.all(\n uris.map(async (uri, i) => {\n if (!uri) {\n throw new Error(`[handler] chunk URI at index ${i} is empty`);\n }\n const { key } = parseGcsUri(uri);\n const localPath = join(chunksDir, basename(key));\n await downloadGcsObjectToFile(storage, uri, localPath);\n if (format === \"png-sequence\") {\n const dirPath = join(chunksDir, `frames-${pad(i)}`);\n await untarDirectory(localPath, dirPath);\n local[i] = dirPath;\n } else {\n local[i] = localPath;\n }\n }),\n );\n return local;\n}\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Collect every GCS URI that the handler will touch for a given event. */\n// This exhaustive event projection is the bucket-allowlist security boundary.\n// fallow-ignore-next-line complexity\nfunction getEventGcsUris(event: PlanEvent | RenderChunkEvent | AssembleEvent): string[] {\n switch (event.Action) {\n case \"plan\":\n return [event.ProjectGcsUri, event.PlanOutputGcsPrefix];\n case \"renderChunk\":\n return event.PlanProtocol !== \"v1\"\n ? [event.PlanV2ManifestGcsUri, event.PlanV2ArtifactGcsPrefix, event.ChunkOutputGcsPrefix]\n : [event.PlanGcsUri, event.ChunkOutputGcsPrefix];\n case \"assemble\":\n return [\n ...(event.PlanProtocol !== \"v1\"\n ? [event.PlanV2ManifestGcsUri, event.PlanV2ArtifactGcsPrefix]\n : [event.PlanGcsUri]),\n ...event.ChunkGcsUris,\n event.OutputGcsUri,\n event.AudioGcsUri,\n ].filter((u): u is string => u != null);\n }\n}\n\n/** Emit the \"guard disabled\" warning at most once per instance. */\nlet warnedAllowlistDisabled = false;\n\n/**\n * Verify every GCS URI in the event resolves to the configured render\n * bucket. Throws `GCS_URI_NOT_ALLOWED` (non-retryable) when a URI targets a\n * different bucket, preventing request injection from reading or writing\n * arbitrary GCS data.\n *\n * Opt-out is explicit: set `HYPERFRAMES_RENDER_BUCKET=\"*\"` to disable the\n * guard intentionally. If the env var is simply unset (or empty), the guard\n * is disabled but a warning is logged once so the gap is visible in Cloud\n * Logging \u2014 it shouldn't silently fail open. The Terraform module always\n * wires the bucket name, so the prod path enforces.\n */\n// fallow-ignore-next-line complexity\nfunction validateEventGcsUris(event: PlanEvent | RenderChunkEvent | AssembleEvent): void {\n const allowedBucket = process.env.HYPERFRAMES_RENDER_BUCKET?.trim();\n if (allowedBucket === \"*\") return; // explicit, intentional opt-out\n if (!allowedBucket) {\n if (!warnedAllowlistDisabled) {\n warnedAllowlistDisabled = true;\n logEvent({\n event: \"bucket_allowlist_disabled\",\n level: \"WARNING\",\n message:\n \"HYPERFRAMES_RENDER_BUCKET is unset \u2014 the GCS bucket-allowlist guard is DISABLED. \" +\n 'Set it to the render bucket name to enforce, or to \"*\" to opt out intentionally.',\n });\n }\n return;\n }\n\n for (const uri of getEventGcsUris(event)) {\n const { bucket } = parseGcsUri(uri);\n if (bucket !== allowedBucket) {\n const err = new Error(\n `[handler] GCS_URI_NOT_ALLOWED: URI ${JSON.stringify(uri)} targets bucket \"${bucket}\" but only \"${allowedBucket}\" is permitted`,\n );\n err.name = \"GCS_URI_NOT_ALLOWED\";\n throw err;\n }\n }\n}\n\nfunction pad(n: number): string {\n return n.toString().padStart(4, \"0\");\n}\n\nfunction trimTrailingSlash(prefix: string): string {\n return prefix.endsWith(\"/\") ? prefix.slice(0, -1) : prefix;\n}\n\nfunction cleanupDir(dir: string): void {\n try {\n // Cloud Run re-uses an instance's filesystem across requests; clean up\n // aggressively so we don't leak a chunk-sized footprint between renders\n // (the writable filesystem counts against the instance's memory).\n rmSync(dir, { recursive: true, force: true });\n } catch {\n // Best-effort \u2014 leak is preferable to crashing on the success path.\n }\n}\n\n/**\n * Read the untarred planDir's `plan.json` and assert its `planHash` matches\n * what the workflow event claims. Throws on mismatch with a typed\n * `PLAN_HASH_MISMATCH` error name so the workflow's non-retryable list\n * routes it correctly. Defense-in-depth \u2014 the producer's `renderChunk` does\n * the same check internally \u2014 but performing it here lets us fail before\n * paying the Chrome-launch + per-frame capture cost on a misrouted chunk.\n */\n// fallow-ignore-next-line complexity\nfunction verifyPlanHash(planDir: string, expected: string): void {\n const planJsonPath = join(planDir, \"plan.json\");\n let parsed: { planHash?: unknown };\n try {\n parsed = JSON.parse(readFileSync(planJsonPath, \"utf-8\")) as { planHash?: unknown };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const error = new Error(`PLAN_HASH_MISMATCH: failed to read ${planJsonPath}: ${msg}`);\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n }\n const actual = parsed.planHash;\n if (typeof actual !== \"string\" || actual !== expected) {\n const error = new Error(\n `PLAN_HASH_MISMATCH: event PlanHash=${expected} did not match plan.json planHash=${String(actual)}`,\n );\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n }\n}\n\n// \u2500\u2500 HTTP shell \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Error names the workflow treats as non-retryable. A request that fails\n * with one of these is the caller's fault (bad input, misrouted chunk) and\n * retrying it just burns instance-seconds, so we map them to HTTP 400 while\n * any other failure maps to 500 (which the workflow retry policy backs off\n * and re-attempts). Keep this list in sync with the `retry` predicate in\n * `packages/gcp-cloud-run/terraform/workflow.yaml`.\n */\nconst NON_RETRYABLE_ERROR_NAMES = new Set([\n // Handler-boundary guards.\n \"GCS_URI_NOT_ALLOWED\",\n \"PLAN_HASH_MISMATCH\",\n \"PLAN_ARTIFACT_DIGEST_MISMATCH\",\n \"PLAN_PROTOCOL_UNSUPPORTED\",\n \"PLAN_V2_INTEGRITY_UNRECOVERABLE\",\n \"VIDEO_SOURCE_UNRENDERABLE\",\n \"INVALID_VIDEO_METADATA\",\n \"NOT_MEDIA_PAYLOAD\",\n // Producer error class names (`.name`) + their string code aliases \u2014 the\n // class sets `.name` to the class name but wraps a `code`; cover both so a\n // raw-code throw is caught too. Mirrors the AWS state machine's\n // non-retryable list.\n \"FormatNotSupportedInDistributedError\",\n \"NotMediaPayloadError\",\n \"PlanTooLargeError\",\n \"PlanProtocolUnsupportedError\",\n \"PlanV2IntegrityError\",\n \"RenderChunkValidationError\",\n \"FFMPEG_VERSION_MISMATCH\",\n \"FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED\",\n \"PLAN_TOO_LARGE\",\n \"BROWSER_GPU_NOT_SOFTWARE\",\n \"FONT_FETCH_FAILED\",\n \"ChromeBinaryUnavailableError\",\n]);\n\n/**\n * Build the Hono app. A single `POST /` endpoint dispatches on the body's\n * `Action` field \u2014 the workflow points every step (plan, each renderChunk,\n * assemble) at the same URL and varies only the body. `GET /healthz` backs\n * the Cloud Run startup/liveness probe.\n *\n * `deps` is threaded through so tests can drive the real HTTP surface with\n * an injected Storage double + mocked primitives.\n */\nexport function createApp(deps?: HandlerDeps): Hono {\n const app = new Hono();\n\n app.get(\"/healthz\", (c) => c.json({ status: \"ok\" }));\n\n // fallow-ignore-next-line complexity\n app.post(\"/\", async (c) => {\n let body: CloudRunEvent;\n try {\n body = (await c.req.json()) as CloudRunEvent;\n } catch {\n return c.json({ error: \"BAD_REQUEST\", message: \"request body must be JSON\" }, 400);\n }\n try {\n const result = await dispatch(body, deps);\n return c.json(result, 200);\n } catch (err) {\n const name = err instanceof Error ? err.name : undefined;\n const message = err instanceof Error ? err.message : String(err);\n const status = name && NON_RETRYABLE_ERROR_NAMES.has(name) ? 400 : 500;\n // Surface `error` (the name) as the discriminator the workflow's\n // retry predicate keys off, plus `message` for human triage.\n return c.json({ error: name ?? \"RenderError\", message }, status);\n }\n });\n\n return app;\n}\n\n/** Start the HTTP server. Cloud Run injects `PORT` (default 8080). */\nexport function startServer(): void {\n const port = Number(process.env.PORT ?? 8080);\n const app = createApp();\n serve({ fetch: app.fetch, port }, (info) => {\n logEvent({ event: \"server_listening\", port: info.port });\n });\n}\n\n// Boot when executed directly (the Dockerfile runs `node dist/server.js`),\n// but not when imported by tests or the SDK.\nif (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {\n startServer();\n}\n", "/**\n * Cloud Run Chrome resolver.\n *\n * `renderChunk()` (the only primitive that needs a browser) launches Chrome\n * via the engine's `BrowserManager`. Because Cloud Run runs a container\n * image rather than a size-capped ZIP, the Chrome story is far simpler than\n * the Lambda adapter's: the `Dockerfile` installs `chrome-headless-shell`\n * into the image at a known path and exports `HYPERFRAMES_CHROME_PATH`.\n * The Dockerfile proves that exact executable's full BeginFrame screenshot\n * contract during the image build. There is no runtime decompression-into-\n * /tmp step and no 250 MB packaging ceiling to fight.\n *\n * Resolution order:\n * 1. `PRODUCER_HEADLESS_SHELL_PATH` \u2014 the engine's own override. If a\n * caller (or the Docker image) already set it, honour it untouched.\n * 2. `HYPERFRAMES_CHROME_PATH` \u2014 set by the Dockerfile to the installed\n * `chrome-headless-shell` binary.\n * 3. A small list of conventional install paths, as a last resort for\n * images built outside our Dockerfile.\n *\n * Throws {@link ChromeBinaryUnavailableError} when nothing resolves, so a\n * misconfigured image fails loudly at the first chunk rather than emitting\n * a confusing puppeteer-core \"executablePath must be specified\" assertion.\n */\n\nimport { existsSync } from \"node:fs\";\n\n/**\n * Thrown when the Chrome binary resolver can't produce a usable path. The\n * class name is the workflow's non-retryable error discriminator.\n */\nexport class ChromeBinaryUnavailableError extends Error {\n // Read indirectly via the error envelope / Error.prototype.toString.\n // fallow-ignore-next-line unused-class-member\n override readonly name = \"ChromeBinaryUnavailableError\";\n readonly resolvedPath: string | null;\n constructor(resolvedPath: string | null, hint: string) {\n super(`[chromium] Chrome binary unavailable: ${hint}`);\n this.resolvedPath = resolvedPath;\n }\n}\n\n/**\n * Conventional locations a `chrome-headless-shell` (or full Chrome) binary\n * may live at in a Debian/Ubuntu-based container. Checked only after the\n * two env-var overrides miss.\n */\nconst FALLBACK_CHROME_PATHS = [\n \"/opt/chrome/chrome-headless-shell\",\n \"/usr/bin/chrome-headless-shell\",\n \"/usr/bin/google-chrome\",\n \"/usr/bin/google-chrome-stable\",\n \"/usr/bin/chromium\",\n \"/usr/bin/chromium-browser\",\n];\n\n/**\n * Resolve the absolute path to a Chrome binary suitable for BeginFrame.\n * Pure (no env mutation) so callers decide whether to export the result\n * into `PRODUCER_HEADLESS_SHELL_PATH`.\n */\n// fallow-ignore-next-line complexity\nexport function resolveChromeExecutablePath(): string {\n const fromEngineOverride = process.env.PRODUCER_HEADLESS_SHELL_PATH?.trim();\n if (fromEngineOverride) {\n if (!existsSync(fromEngineOverride)) {\n throw new ChromeBinaryUnavailableError(\n fromEngineOverride,\n `PRODUCER_HEADLESS_SHELL_PATH=${JSON.stringify(fromEngineOverride)} does not exist on disk.`,\n );\n }\n return fromEngineOverride;\n }\n\n const fromImage = process.env.HYPERFRAMES_CHROME_PATH?.trim();\n if (fromImage) {\n if (!existsSync(fromImage)) {\n throw new ChromeBinaryUnavailableError(\n fromImage,\n `HYPERFRAMES_CHROME_PATH=${JSON.stringify(fromImage)} does not exist on disk.`,\n );\n }\n return fromImage;\n }\n\n for (const candidate of FALLBACK_CHROME_PATHS) {\n if (existsSync(candidate)) return candidate;\n }\n\n throw new ChromeBinaryUnavailableError(\n null,\n \"no Chrome binary found. Set HYPERFRAMES_CHROME_PATH (the Dockerfile does this) or \" +\n \"PRODUCER_HEADLESS_SHELL_PATH to the absolute path of a chrome-headless-shell binary. \" +\n `Searched: ${FALLBACK_CHROME_PATHS.join(\", \")}.`,\n );\n}\n", "/**\n * Map a distributed `format` to the file extension the assembled output\n * should carry on disk + in GCS. Shared by `src/server.ts` (chunk +\n * assemble output paths) and `src/sdk/renderToCloudRun.ts` (final\n * output key construction) so the two sides agree on what an mp4\n * looks like vs a png-sequence.\n */\n\nimport type { DistributedFormat } from \"@hyperframes/producer/distributed\";\n\nexport type { DistributedFormat } from \"@hyperframes/producer/distributed\";\n\n// Closed-enum lookup table. TS enforces exhaustiveness via the\n// `Record<DistributedFormat, string>` annotation \u2014 adding a format to\n// `DistributedFormat` without adding the matching key here fails to\n// typecheck, which is the same exhaustiveness guarantee a switch +\n// `_exhaustive: never` arm provides but at lower complexity.\nconst FORMAT_EXTENSIONS: Record<DistributedFormat, string> = {\n mp4: \".mp4\",\n mov: \".mov\",\n webm: \".webm\",\n \"png-sequence\": \"\",\n};\n\nexport function formatExtension(format: DistributedFormat): string {\n return FORMAT_EXTENSIONS[format];\n}\n", "/**\n * Thin GCS transport for the Cloud Run handler.\n *\n * The OSS distributed primitives are pure functions over local file paths;\n * the handler bridges GCS \u2194 the container's writable `/tmp` filesystem on\n * each request. Functions here are intentionally narrow: parse a URI,\n * download an object to a local path, upload a path, tar-pack a planDir,\n * tar-extract a planDir back out.\n *\n * Tar (not zip) for planDir transit:\n * - planDirs contain symlinks (the extract stage materializes them but\n * the compiled/ subtree may include linked assets); tar preserves them,\n * zip does not.\n * - We use the `tar` npm package (pure JS over `node:zlib`) so the\n * archive format doesn't depend on a system `tar`/`unzip` being present\n * in the container image.\n *\n * Apart from the `gs://` scheme and the `@google-cloud/storage` client this\n * is the same shape as `@hyperframes/aws-lambda`'s `s3Transport.ts`.\n */\n\nimport {\n createReadStream,\n createWriteStream,\n existsSync,\n mkdirSync,\n rmSync,\n statSync,\n} from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { dirname } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { Storage } from \"@google-cloud/storage\";\nimport * as tar from \"tar\";\n\n/** Parsed `gs://bucket/key` URI. */\nexport interface GcsLocation {\n bucket: string;\n key: string;\n}\n\n/** Parse `gs://bucket/key/path` \u2192 `{ bucket, key }`. Throws on malformed input. */\n// fallow-ignore-next-line complexity\nexport function parseGcsUri(uri: string): GcsLocation {\n if (!uri.startsWith(\"gs://\")) {\n throw new Error(`[gcsTransport] expected gs:// URI, got: ${JSON.stringify(uri)}`);\n }\n const rest = uri.slice(\"gs://\".length);\n const slash = rest.indexOf(\"/\");\n if (slash === -1) {\n throw new Error(`[gcsTransport] missing key in gs URI: ${JSON.stringify(uri)}`);\n }\n const bucket = rest.slice(0, slash);\n const key = rest.slice(slash + 1);\n if (!bucket || !key) {\n throw new Error(`[gcsTransport] empty bucket or key in gs URI: ${JSON.stringify(uri)}`);\n }\n return { bucket, key };\n}\n\n/** Build `gs://bucket/key` from a location. */\nexport function formatGcsUri(loc: GcsLocation): string {\n return `gs://${loc.bucket}/${loc.key}`;\n}\n\n/** Stream a GCS object to a local file path. */\nexport async function downloadGcsObjectToFile(\n storage: Storage,\n uri: string,\n destPath: string,\n): Promise<void> {\n const { bucket, key } = parseGcsUri(uri);\n mkdirSync(dirname(destPath), { recursive: true });\n const file = storage.bucket(bucket).file(key);\n // `createReadStream` streams the object body; piping into a write stream\n // keeps memory flat for large plan tarballs / chunk files rather than\n // buffering the whole object the way `file.download()` would.\n await pipeline(file.createReadStream(), createWriteStream(destPath));\n}\n\n/** Download and verify an immutable plan-v2 artifact before materialization. */\nexport async function downloadGcsObjectToFileVerified(\n storage: Storage,\n uri: string,\n destPath: string,\n expectedSha256: string,\n): Promise<void> {\n assertSha256(expectedSha256);\n await downloadGcsObjectToFile(storage, uri, destPath);\n const actual = await sha256File(destPath);\n if (actual !== expectedSha256) {\n rmSync(destPath, { force: true });\n const error = new Error(\n `[gcsTransport] PLAN_ARTIFACT_DIGEST_MISMATCH: ${uri} expected ${expectedSha256}, got ${actual}`,\n );\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n }\n}\n\n/**\n * Upload a local file's contents to a GCS URI using a resumable upload.\n * GCS objects have no practical size ceiling for the artifacts this adapter\n * handles (plan tarballs \u2264 2 GB, chunks \u2264 a few hundred MB), so a single\n * upload call works for every case.\n */\nexport async function uploadFileToGcs(\n storage: Storage,\n localPath: string,\n uri: string,\n contentType?: string,\n): Promise<void> {\n if (!existsSync(localPath)) {\n throw new Error(`[gcsTransport] upload source missing: ${localPath}`);\n }\n const { bucket, key } = parseGcsUri(uri);\n await storage.bucket(bucket).upload(localPath, {\n destination: key,\n // `resumable: false` (simple upload) is faster for the small-to-medium\n // objects this adapter moves and avoids the extra round-trip a resumable\n // session start costs; GCS recommends resumable only past ~8 MB but our\n // chunks are reliably above that, so let the client pick by default.\n contentType,\n });\n}\n\n/**\n * Upload one content-addressed plan-v2 artifact exactly once.\n *\n * The zero-generation precondition makes creation atomic. Existing objects\n * are reused only when their immutable digest metadata and byte length agree;\n * a conflict is never overwritten because another render may already consume\n * that object.\n */\nexport async function uploadContentAddressedFileToGcs(\n storage: Storage,\n localPath: string,\n uri: string,\n expectedSha256: string,\n contentType?: string,\n): Promise<\"uploaded\" | \"reused\"> {\n assertSha256(expectedSha256);\n if (!existsSync(localPath)) {\n throw new Error(`[gcsTransport] upload source missing: ${localPath}`);\n }\n const actualSha256 = await sha256File(localPath);\n if (actualSha256 !== expectedSha256) {\n throwDigestMismatch(\n `local artifact ${localPath} expected ${expectedSha256}, got ${actualSha256}`,\n );\n }\n\n const { bucket, key } = parseGcsUri(uri);\n const bucketHandle = storage.bucket(bucket);\n const file = bucketHandle.file(key);\n const size = statSync(localPath).size;\n if (await isReusableContentAddressedObject(file, uri, size, expectedSha256)) {\n return \"reused\";\n }\n\n try {\n await bucketHandle.upload(localPath, {\n destination: key,\n contentType,\n metadata: { metadata: { sha256: expectedSha256 } },\n preconditionOpts: { ifGenerationMatch: 0 },\n });\n return \"uploaded\";\n } catch (error) {\n // A concurrent planner may win the create-only race. Reuse only after\n // verifying that the winning object is exactly the immutable CAS value.\n if (\n isGcsPreconditionFailed(error) &&\n (await isReusableContentAddressedObject(file, uri, size, expectedSha256))\n ) {\n return \"reused\";\n }\n throw error;\n }\n}\n\ninterface GcsFileLike {\n exists(): Promise<[boolean, ...unknown[]]>;\n getMetadata(): Promise<\n [\n {\n size?: string | number;\n metadata?: Record<string, string | number | boolean | null>;\n },\n ...unknown[],\n ]\n >;\n}\n\nasync function isReusableContentAddressedObject(\n file: GcsFileLike,\n uri: string,\n expectedSize: number,\n expectedSha256: string,\n): Promise<boolean> {\n const [exists] = await file.exists();\n if (!exists) return false;\n const [metadata] = await file.getMetadata();\n if (Number(metadata.size) === expectedSize && metadata.metadata?.sha256 === expectedSha256) {\n return true;\n }\n throwDigestMismatch(\n `immutable object ${uri} already exists with different digest metadata or size`,\n );\n}\n\nexport async function sha256File(path: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(path)) {\n hash.update(chunk as Buffer);\n }\n return hash.digest(\"hex\");\n}\n\nfunction assertSha256(value: string): void {\n if (!/^[a-f0-9]{64}$/.test(value)) {\n throw new Error(\n `[gcsTransport] expected lowercase SHA-256 digest, got ${JSON.stringify(value)}`,\n );\n }\n}\n\nfunction throwDigestMismatch(detail: string): never {\n const error = new Error(`[gcsTransport] PLAN_ARTIFACT_DIGEST_MISMATCH: ${detail}`);\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n}\n\nfunction isGcsPreconditionFailed(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n return (error as { code?: unknown }).code === 412;\n}\n\n/**\n * Pack a directory into a `.tar.gz` at `destTarball`. Uses the `tar` npm\n * package (pure JS over `node:zlib`) rather than spawning a system tar\n * binary so the archive format is independent of the container's userland.\n */\nexport async function tarDirectory(sourceDir: string, destTarball: string): Promise<void> {\n if (!existsSync(sourceDir) || !statSync(sourceDir).isDirectory()) {\n throw new Error(`[gcsTransport] tar source must be an existing directory: ${sourceDir}`);\n }\n mkdirSync(dirname(destTarball), { recursive: true });\n await tar.create({ gzip: true, file: destTarball, cwd: sourceDir }, [\".\"]);\n}\n\n/**\n * Extract a `.tar.gz` produced by {@link tarDirectory} into `destDir`.\n * The directory is created (or cleared) before extraction so a retried\n * request doesn't observe stale files from a prior run on the same warm\n * container instance.\n */\nexport async function untarDirectory(tarballPath: string, destDir: string): Promise<void> {\n if (!existsSync(tarballPath)) {\n throw new Error(`[gcsTransport] tarball missing: ${tarballPath}`);\n }\n // Wipe target so a warm container instance's prior planDir doesn't bleed\n // into the new request. Cloud Run re-uses the instance filesystem across\n // requests served by the same instance.\n if (existsSync(destDir)) {\n rmSync(destDir, { recursive: true, force: true });\n }\n mkdirSync(destDir, { recursive: true });\n await tar.extract({ file: tarballPath, cwd: destDir });\n}\n", "// fallow-ignore-file code-duplication\nimport { createHash } from \"node:crypto\";\nimport { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { Storage } from \"@google-cloud/storage\";\nimport {\n PlanV2IntegrityError,\n type PlanV2ArtifactPublisher,\n type PlanV2PublishBlob,\n} from \"@hyperframes/producer/distributed\";\nimport { parseGcsUri, uploadContentAddressedFileToGcs } from \"./gcsTransport.js\";\n\nexport interface GcsPlanV2ArtifactPublisherOptions {\n readonly storage: Storage;\n /** Validated render output prefix from which all v2 object keys are derived. */\n readonly planOutputGcsPrefix: string;\n /** Planner-local scratch parent for the small manifest upload file. */\n readonly temporaryRoot?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction assertSha256(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !/^[a-f0-9]{64}$/.test(value)) {\n throw new PlanV2IntegrityError(`${label} must be a lowercase SHA-256 digest`);\n }\n return value;\n}\n\nfunction manifestDigests(manifestBytes: string): ReadonlySet<string> {\n let value: unknown;\n try {\n value = JSON.parse(manifestBytes);\n } catch {\n throw new PlanV2IntegrityError(\"GCS publisher received invalid manifest JSON\");\n }\n if (!isRecord(value) || !Array.isArray(value.artifacts)) {\n throw new PlanV2IntegrityError(\"GCS publisher manifest requires an artifacts array\");\n }\n return new Set(\n value.artifacts.map((artifact, index) => {\n if (!isRecord(artifact)) {\n throw new PlanV2IntegrityError(`GCS publisher artifacts[${index}] must be an object`);\n }\n return assertSha256(artifact.sha256, `GCS publisher artifacts[${index}].sha256`);\n }),\n );\n}\n\nfunction trimTrailingSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return value.slice(0, end);\n}\n\n/**\n * Manifest-last GCS implementation of the producer's plan-v2 publication seam.\n *\n * Every path remains private to the planner container. Remote workers receive\n * only the manifest URI and artifact prefix and materialize their own target.\n */\nexport class GcsPlanV2ArtifactPublisher implements PlanV2ArtifactPublisher {\n readonly artifactPrefix: string;\n readonly manifestUri: string;\n readonly #storage: Storage;\n readonly #temporaryRoot: string;\n readonly #publishedDigests = new Set<string>();\n #state: \"open\" | \"committed\" | \"aborted\" = \"open\";\n\n constructor(options: Readonly<GcsPlanV2ArtifactPublisherOptions>) {\n const outputPrefix = `${trimTrailingSlash(options.planOutputGcsPrefix)}/v2`;\n parseGcsUri(outputPrefix);\n this.#storage = options.storage;\n this.artifactPrefix = `${outputPrefix}/artifacts/sha256`;\n this.manifestUri = `${outputPrefix}/manifest.json`;\n this.#temporaryRoot = options.temporaryRoot ?? tmpdir();\n mkdirSync(this.#temporaryRoot, { recursive: true });\n }\n\n async putBlob(blob: Readonly<PlanV2PublishBlob>): Promise<void> {\n this.#assertOpen(\"publish a blob\");\n const digest = assertSha256(blob.sha256, \"GCS published blob sha256\");\n const sourceSize = statSync(blob.sourcePath).size;\n if (sourceSize !== blob.sizeBytes) {\n throw new PlanV2IntegrityError(\n `GCS published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`,\n );\n }\n const uri = `${this.artifactPrefix}/${digest.slice(0, 2)}/${digest}`;\n await uploadContentAddressedFileToGcs(this.#storage, blob.sourcePath, uri, digest);\n this.#publishedDigests.add(digest);\n }\n\n async commitManifest(manifestBytes: string): Promise<void> {\n this.#assertOpen(\"commit a manifest\");\n for (const digest of manifestDigests(manifestBytes)) {\n if (!this.#publishedDigests.has(digest)) {\n throw new PlanV2IntegrityError(\n `cannot commit GCS manifest before referenced blob is durable: ${digest}`,\n );\n }\n }\n\n const manifestDigest = createHash(\"sha256\").update(manifestBytes, \"utf8\").digest(\"hex\");\n const stagingDir = mkdtempSync(join(this.#temporaryRoot, \"hf-plan-v2-manifest-\"));\n const manifestPath = join(stagingDir, \"manifest.json\");\n try {\n writeFileSync(manifestPath, manifestBytes, \"utf8\");\n await uploadContentAddressedFileToGcs(\n this.#storage,\n manifestPath,\n this.manifestUri,\n manifestDigest,\n \"application/json\",\n );\n this.#state = \"committed\";\n } finally {\n rmSync(stagingDir, { recursive: true, force: true });\n }\n }\n\n async abort(): Promise<void> {\n if (this.#state === \"open\") this.#state = \"aborted\";\n // Immutable CAS blobs may be shared with or reused by another retry.\n // Unreferenced blobs expire under the bucket's intermediate lifecycle.\n }\n\n #assertOpen(operation: string): void {\n if (this.#state !== \"open\") {\n throw new PlanV2IntegrityError(`cannot ${operation} after publisher is ${this.#state}`);\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAkBA,SAAS,cAAAA,aAAY,aAAAC,YAAW,eAAAC,cAAa,cAAc,UAAAC,SAAQ,YAAAC,iBAAgB;AACnF,SAAS,UAAAC,eAAc;AACvB,SAAS,UAAU,SAAS,QAAAC,aAAY;AACxC,SAAS,qBAAqB;AAC9B,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAKA;AAAA,EACA;AAAA,OACK;;;ACnBP,SAAS,kBAAkB;AAMpB,IAAM,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AAI,KAAK;AAErB,MAAI,IAAI,YAAY,CAAC,MAAM,EAAE,KAAK,EAAE,QAAQ,KAAK,CAAC,CAAC;AAGnD,MAAI,KAAK,KAAK,OAAO,MAAM;AACzB,QAAI;AACJ,QAAI;AACF,aAAQ,MAAM,EAAE,IAAI,KAAK;AAAA,IAC3B,QAAQ;AACN,aAAO,EAAE,KAAK,EAAE,OAAO,eAAe,SAAS,4BAA4B,GAAG,GAAG;AAAA,IACnF;AACA,QAAI;AACF,YAAM,SAAS,MAAM,SAAS,MAAM,IAAI;AACxC,aAAO,EAAE,KAAK,QAAQ,GAAG;AAAA,IAC3B,SAAS,KAAK;AACZ,YAAM,OAAO,eAAe,QAAQ,IAAI,OAAO;AAC/C,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,YAAM,SAAS,QAAQ,0BAA0B,IAAI,IAAI,IAAI,MAAM;AAGnE,aAAO,EAAE,KAAK,EAAE,OAAO,QAAQ,eAAe,QAAQ,GAAG,MAAM;AAAA,IACjE;AAAA,EACF,CAAC;AAED,SAAO;AACT;AAGO,SAAS,cAAoB;AAClC,QAAM,OAAO,OAAO,QAAQ,IAAI,QAAQ,IAAI;AAC5C,QAAM,MAAM,UAAU;AACtB,QAAM,EAAE,OAAO,IAAI,OAAO,KAAK,GAAG,CAAC,SAAS;AAC1C,aAAS,EAAE,OAAO,oBAAoB,MAAM,KAAK,KAAK,CAAC;AAAA,EACzD,CAAC;AACH;AAIA,IAAI,QAAQ,KAAK,CAAC,KAAK,cAAc,YAAY,GAAG,MAAM,QAAQ,KAAK,CAAC,GAAG;AACzE,cAAY;AACd;",
|
|
6
6
|
"names": ["existsSync", "mkdirSync", "mkdtempSync", "rmSync", "statSync", "tmpdir", "join", "existsSync", "existsSync", "createHash", "mkdirSync", "rmSync", "statSync", "assertSha256", "mkdirSync", "statSync", "createHash", "rmSync", "mkdtempSync", "join", "tmpdir", "trimTrailingSlash", "existsSync", "statSync", "uri", "mkdirSync", "rmSync"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyperframes/gcp-cloud-run",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.111",
|
|
4
4
|
"description": "Google Cloud Run + Workflows adapter for HyperFrames distributed rendering — request handler, client-side SDK, and Terraform module.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"hono": "^4.6.0",
|
|
46
46
|
"puppeteer-core": "^25.2.1",
|
|
47
47
|
"tar": "^7.4.3",
|
|
48
|
-
"@hyperframes/producer": "^0.7.
|
|
48
|
+
"@hyperframes/producer": "^0.7.111"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@types/node": "^25.0.10",
|
|
@@ -7,8 +7,8 @@ const smoke = readFileSync(smokePath, "utf-8");
|
|
|
7
7
|
const dockerfile = readFileSync(join(import.meta.dir, "../Dockerfile"), "utf-8");
|
|
8
8
|
|
|
9
9
|
describe("GCP smoke ownership and protocol safety", () => {
|
|
10
|
-
it("defaults to
|
|
11
|
-
expect(smoke).toContain('PROTOCOLS="${PROTOCOLS:-
|
|
10
|
+
it("defaults to v2 and retains explicit v1/v2 protocol arguments", () => {
|
|
11
|
+
expect(smoke).toContain('PROTOCOLS="${PROTOCOLS:-v2}"');
|
|
12
12
|
expect(smoke).toContain("--protocols)");
|
|
13
13
|
expect(smoke).toContain("PlanProtocol: $protocol");
|
|
14
14
|
expect(smoke).toContain("decodedFramesEqual");
|
|
@@ -77,8 +77,8 @@ describe("Cloud Workflows plan protocol routing", () => {
|
|
|
77
77
|
expect(source.match(/max_retries: 4/g)).toHaveLength(4);
|
|
78
78
|
});
|
|
79
79
|
|
|
80
|
-
it("
|
|
81
|
-
expect(source).toContain('default(map.get(args, "PlanProtocol"), "
|
|
80
|
+
it("defaults omitted protocol to v2 and rejects unknown protocols before plan", () => {
|
|
81
|
+
expect(source).toContain('default(map.get(args, "PlanProtocol"), "v2")');
|
|
82
82
|
expect(namedStep("selectPlanProtocol")).toMatchObject({
|
|
83
83
|
next: "unsupportedPlanProtocol",
|
|
84
84
|
});
|
package/terraform/workflow.yaml
CHANGED
|
@@ -26,9 +26,9 @@ main:
|
|
|
26
26
|
- planOutputGcsPrefix: ${args.PlanOutputGcsPrefix}
|
|
27
27
|
- outputGcsUri: ${args.OutputGcsUri}
|
|
28
28
|
- config: ${args.Config}
|
|
29
|
-
#
|
|
30
|
-
#
|
|
31
|
-
- planProtocol: ${default(map.get(args, "PlanProtocol"), "
|
|
29
|
+
# Plan v2 is the default. Explicit v1 remains available during the
|
|
30
|
+
# deprecated monolithic-plan compatibility window.
|
|
31
|
+
- planProtocol: ${default(map.get(args, "PlanProtocol"), "v2")}
|
|
32
32
|
|
|
33
33
|
# ── Plan (Activity A) ────────────────────────────────────────────────────
|
|
34
34
|
- selectPlanProtocol:
|