Files
hyperframes/packages/aws-lambda/src/s3Transport.ts
T
James Russo c50f59a53b feat(lambda): add Lambda handler, ZIP bundling, and BeginFrame probe (#878)
* feat(lambda): add Lambda handler, ZIP bundling, and BeginFrame probe

Phase 6 of the distributed rendering plan: AWS Lambda turnkey adoption
(see DISTRIBUTED-RENDERING-PLAN.md §11 Phase 6 + §15).

This PR adds the new packages/aws-lambda/ workspace package that wraps
the OSS plan/renderChunk/assemble primitives in an AWS Lambda handler,
plus a build pipeline that bundles the handler + Chromium runtime +
ffmpeg into a deployable ZIP.

Architecture: ZIP deploy (not Docker image), Chrome via @sparticuz/chromium
with chrome-headless-shell fallback, dispatch on event.Action ∈ {plan,
renderChunk, assemble}.

The load-bearing concern — does @sparticuz/chromium's chrome-headless-shell
build honour CDP HeadlessExperimental.beginFrame? — is pinned by the new
scripts/probe-beginframe.ts regression guard. Probe boots the runtime
inside public.ecr.aws/lambda/nodejs:22, navigates to a static page, and
asserts beginFrame returns a PNG buffer. Verified locally + inside the
Docker container; both pass with hasDamage=true.

Sizes (sparticuz source): unzipped 157 MiB, zipped 99 MiB. Well under
the 240 MiB / 150 MiB in-house gates and the Lambda 250 MiB hard ceiling.

This is part of a stack of 8 PRs (3 in Phase 6a, 5 in Phase 6b); this is
PR 6.1.

* fix(lambda): address PR 878 review feedback

- Verify event.PlanHash against the untarred plan.json at the handler
  boundary before invoking the producer primitive. Throws typed
  PLAN_HASH_MISMATCH on divergence so Step Functions routes it as
  non-retryable; previously the field was schema bloat the handler
  ignored, leaving enforcement entirely inside the producer.
- Standardize on MiB throughout build-zip.ts, verify-zip-size.ts, and
  the README. Lambda's hard ceiling is 250 MiB (AWS docs label "250 MB"
  but use binary mebibytes); previously mixed units made the 248 MiB
  budget look like a ~5 MB margin instead of the 2 MiB it actually is.
- stageChromeHeadlessShell now picks Chrome versions via numeric semver
  comparison instead of lexicographic sort+reverse — the latter would
  silently pick "99.x" over "131.x" once Chrome cached three-digit
  majors that aren't width-aligned.
- Drop _setSparticuzChromiumForTests from the public index barrel.
  Test-only DI seam imported directly from ./chromium.js in tests.
- Replace require("node:fs") inside walkSize() with the top-level fs
  imports — file is ESM and the same module is already imported.

* docs(lambda): drop internal plan-doc refs from package README

* ci(windows): fix bun filter UNION bug excluding producer from Windows tests

`bun run --filter "!a" --filter "!b" test` composes as a UNION (any
package matching either negation runs), not an intersection. Effect:
@hyperframes/producer was still being tested on Windows even though
it's explicitly excluded — its regression harness (Docker + LFS golden
mp4 baselines) is Linux-only and was driving the 32min timeout.

Enumerate the packages we DO want to test instead.
2026-05-16 18:08:47 -04:00

157 lines
5.4 KiB
TypeScript

/**
* Thin S3 transport for the Lambda handler.
*
* The OSS distributed primitives are pure functions over local file paths;
* the Lambda handler bridges S3 ↔ Lambda's `/tmp` filesystem on each
* invocation. Functions here are intentionally narrow: parse a URI, download
* an object to a local path, upload a path/directory, tar-extract a planDir,
* tar-pack a planDir back out.
*
* Tar (not zip) for planDir transit:
* - planDirs contain symlinks (extract stage materializes them but the
* compiled/ subtree may include linked assets); tar preserves them, zip
* does not.
* - We use the `tar` npm package (pure JS over `node:zlib`) — AWS
* Lambda's `nodejs:22` base image ships neither `tar` nor `unzip` in
* `/usr/bin`, so a system-binary tar would ENOENT in the actual
* deployment.
*/
import {
createReadStream,
createWriteStream,
existsSync,
mkdirSync,
readdirSync,
rmSync,
statSync,
} from "node:fs";
import { dirname, join } from "node:path";
import { pipeline } from "node:stream/promises";
import { GetObjectCommand, PutObjectCommand, type S3Client } from "@aws-sdk/client-s3";
import * as tar from "tar";
/** Parsed `s3://bucket/key` URI. */
export interface S3Location {
bucket: string;
key: string;
}
/** Parse `s3://bucket/key/path` → `{ bucket, key }`. Throws on malformed input. */
export function parseS3Uri(uri: string): S3Location {
if (!uri.startsWith("s3://")) {
throw new Error(`[s3Transport] expected s3:// URI, got: ${JSON.stringify(uri)}`);
}
const rest = uri.slice("s3://".length);
const slash = rest.indexOf("/");
if (slash === -1) {
throw new Error(`[s3Transport] missing key in s3 URI: ${JSON.stringify(uri)}`);
}
const bucket = rest.slice(0, slash);
const key = rest.slice(slash + 1);
if (!bucket || !key) {
throw new Error(`[s3Transport] empty bucket or key in s3 URI: ${JSON.stringify(uri)}`);
}
return { bucket, key };
}
/** Build `s3://bucket/key` from a location. */
export function formatS3Uri(loc: S3Location): string {
return `s3://${loc.bucket}/${loc.key}`;
}
/** Stream an S3 object to a local file path. Throws if the body is missing. */
export async function downloadS3ObjectToFile(
client: S3Client,
uri: string,
destPath: string,
): Promise<void> {
const { bucket, key } = parseS3Uri(uri);
const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
const body = response.Body as NodeJS.ReadableStream | undefined;
if (!body) {
throw new Error(`[s3Transport] s3 GetObject returned empty body for ${uri}`);
}
mkdirSync(dirname(destPath), { recursive: true });
await pipeline(body, createWriteStream(destPath));
}
/**
* Upload a local file's contents to an S3 URI using a streaming
* `PutObjectCommand`. PutObject's 5 GB cap comfortably exceeds the
* distributed pipeline's 2 GB planDir limit and the typical
* chunk size (≤ 200 MB), so a single PUT works for every artifact this
* adapter handles.
*/
export async function uploadFileToS3(
client: S3Client,
localPath: string,
uri: string,
contentType?: string,
): Promise<void> {
if (!existsSync(localPath)) {
throw new Error(`[s3Transport] upload source missing: ${localPath}`);
}
const { bucket, key } = parseS3Uri(uri);
const size = statSync(localPath).size;
await client.send(
new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: createReadStream(localPath),
ContentType: contentType,
ContentLength: size,
}),
);
}
/**
* Pack a directory into a `.tar.gz` at `destTarball`. Uses the `tar` npm
* package (pure JS over `node:zlib`) rather than spawning a system tar
* binary — the AWS Lambda Node 22 base image ships a minimal set of
* userland tools and does NOT include `tar` in `/usr/bin`.
*/
export async function tarDirectory(sourceDir: string, destTarball: string): Promise<void> {
if (!existsSync(sourceDir) || !statSync(sourceDir).isDirectory()) {
throw new Error(`[s3Transport] tar source must be an existing directory: ${sourceDir}`);
}
mkdirSync(dirname(destTarball), { recursive: true });
await tar.create({ gzip: true, file: destTarball, cwd: sourceDir }, ["."]);
}
/**
* Extract a `.tar.gz` produced by {@link tarDirectory} into `destDir`.
* The directory is created (or cleared) before extraction so a retried
* invocation doesn't observe stale files from a prior run on the same
* warm Lambda container.
*/
export async function untarDirectory(tarballPath: string, destDir: string): Promise<void> {
if (!existsSync(tarballPath)) {
throw new Error(`[s3Transport] tarball missing: ${tarballPath}`);
}
// Wipe target so the warm container's prior planDir doesn't bleed into
// the new invocation. Lambda re-uses /tmp across invocations on the same
// container.
if (existsSync(destDir)) {
rmSync(destDir, { recursive: true, force: true });
}
mkdirSync(destDir, { recursive: true });
await tar.extract({ file: tarballPath, cwd: destDir });
}
/** List all regular files under a directory, sorted, returned as absolute paths. */
export function listFilesInDirectory(dir: string): string[] {
const out: string[] = [];
function walk(d: string): void {
for (const entry of readdirSync(d, { withFileTypes: true }).sort((a, b) =>
a.name < b.name ? -1 : a.name > b.name ? 1 : 0,
)) {
const full = join(d, entry.name);
if (entry.isDirectory()) walk(full);
else if (entry.isFile()) out.push(full);
}
}
walk(dir);
return out;
}