Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion .github/workflows/lambda-arm64-image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,14 @@ jobs:
reply=$(curl -sS --retry 30 --retry-all-errors --retry-delay 1 \
-d '{}' http://localhost:9001/2015-03-31/functions/function/invocations)
docker logs hf-smoke
echo "$reply"
jq 'del(.textPng)' <<<"$reply"
jq -e '.arch == "arm64" and .screenshotBytes > 0 and (.ffmpeg | startswith("ffmpeg version 7.0.2"))' <<<"$reply"
mkdir text && jq -S .fonts <<<"$reply" >text/fonts.json && jq -r .textPng <<<"$reply" | base64 -d >text/text.png
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: text-arm64
path: text/
retention-days: 7
- name: The Lambda runtime loads the handler
run: |
docker run -d --name hf-video -p 9000:8080 hf-video:ci
Expand All @@ -139,3 +145,46 @@ jobs:
docker logs hf-video
echo "$reply"
grep -q 'no recognised Action' <<<"$reply"
# The x86 function: the handler ZIP on the same base, running its @sparticuz/chromium.
x86-text:
name: x86 text render
needs: handler-zip
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: handler-zip
path: artifacts
- name: The handler ZIP renders the text page under the Lambda runtime
run: |
unzip -q artifacts/handler.zip -d task
cp packages/aws-lambda/image/smoke-video.mjs task/
base=$(sed -n 's/^ARG BASE=//p' packages/aws-lambda/image/Dockerfile)
docker run -d --name hf-x86 --platform linux/amd64 -p 9002:8080 -v "$PWD/task:/var/task:ro" \
"$base" smoke-video.handler
reply=$(curl -sS --retry 30 --retry-all-errors --retry-delay 1 \
-d '{}' http://localhost:9002/2015-03-31/functions/function/invocations)
docker logs hf-x86
jq 'del(.textPng)' <<<"$reply"
jq -e '.arch == "x64" and .screenshotBytes > 0' <<<"$reply"
mkdir text && jq -S .fonts <<<"$reply" >text/fonts.json && jq -r .textPng <<<"$reply" | base64 -d >text/text.png
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: text-x86
path: text/
retention-days: 7

# --video-arch picks which of the two renders a stack's frames, so each line must resolve to the same fonts on both.
text-compare:
name: Text fonts match across arches
needs: [image, x86-text]
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
pattern: text-*
- run: cat text-arm64/fonts.json && diff text-x86/fonts.json text-arm64/fonts.json
50 changes: 50 additions & 0 deletions .github/workflows/lambda-handler-zip.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: Lambda handler ZIP

permissions:
contents: read

# The x86 handler ZIP sits close to its unzipped-size gate, and the handler bundles the producer, engine and core,
# so a change there can push it over. Build it on those PRs, so that fails before merge, not in the release job.
on:
pull_request:
paths:
- "packages/aws-lambda/**"
- "packages/producer/src/**"
- "packages/engine/src/**"
- "packages/core/src/**"
- "packages/parsers/src/**"
- "bun.lock"
- ".github/workflows/lambda-handler-zip.yml"

concurrency:
group: lambda-handler-zip-${{ github.ref }}
cancel-in-progress: true

jobs:
changes:
name: Detect changes
runs-on: ubuntu-latest
timeout-minutes: 4
outputs:
release_only: ${{ steps.release.outputs.release_only }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
- name: Find a release-only diff
id: release
uses: ./.github/actions/release-only-diff

handler-zip:
name: Handler ZIP size
needs: changes
# A release PR changes versions and notes only; a failed change detection must not skip the build.
if: ${{ !cancelled() && needs.changes.outputs.release_only != 'true' }}
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
- run: bun install --frozen-lockfile
- run: bun run build
- run: bun run --cwd packages/aws-lambda build:zip
1 change: 1 addition & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion docs/packages/aws-lambda.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ The Lambda adapter wraps the distributed producer primitives behind one dispatch

All three phases must fit the configured per-invocation Lambda timeout, at most 15 minutes, and the function's temporary storage. Smaller chunks can reduce each worker's extraction and rendering work, but do not divide video extraction that still happens in Plan. See [long-video planning limits](/deploy/aws-lambda#long-video-planning-times-out) for FFmpeg frame-stall timeouts and how to split jobs that cannot fit.

The x86 handler ZIP uses `@sparticuz/chromium` by default, with a build-time fallback for bundling `chrome-headless-shell` directly when needed. The arm64 video image runs Chrome for Testing's linux-arm64 `chrome-headless-shell`.
The x86 handler ZIP uses `@sparticuz/chromium`; a `chrome-headless-shell` ZIP is over Lambda's 250 MiB unzipped limit. The arm64 video image runs Chrome for Testing's linux-arm64 `chrome-headless-shell`, with `@sparticuz/chromium`'s fonts so text resolves as on x86.

### Page network restriction

Expand Down
4 changes: 2 additions & 2 deletions docs/packages/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3070,8 +3070,8 @@ deploy:
| `--profile` | `AWS_PROFILE` | AWS profile name |
| `--concurrency` | none | Lambda reserved concurrency. Without it, a new stack reserves none and each render runs up to 90% of the account's unreserved concurrency; a redeploy keeps the stack's current reservation; `none` removes it |
| `--memory` | `10240` | Lambda memory in MB |
| `--chrome-source` | `sparticuz` | `sparticuz` or `chrome-headless-shell` |
| `--video-arch` | `arm64` | `arm64` runs the plan and the chunks on an arm64 container-image function, pushed to an ECR repository named `<stack>-video`; audio and assemble stay on x86. The image runs its own `chrome-headless-shell`; the handler ZIP it is built from needs `sparticuz`. `x86_64` runs everything on the x86 function |
| `--chrome-source` | `sparticuz` | `sparticuz`. `chrome-headless-shell` is refused: it does not fit a ZIP function, and the arm64 video image already runs it |
| `--video-arch` | `arm64` | `arm64` runs the plan and the chunks on an arm64 container-image function, pushed to an ECR repository named `<stack>-video`; audio and assemble stay on x86. The image runs its own `chrome-headless-shell`. `x86_64` runs everything on the x86 function |
| `--skip-build` | off | Reuse the existing `handler.zip` |
| `--no-warm` | warm | Skip the one warm-up call to the video function after deploy, which loads its container image so the first render is not the one that waits for it |

Expand Down
2 changes: 1 addition & 1 deletion examples/aws-lambda/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ with `--profile <name>` or `AWS_PROFILE=<name>`.
| `LambdaMemoryMb` | `10240` | Lambda memory; Lambda allocates CPU proportionally. 10 GB recommended for 1080p. |
| `LambdaTimeoutSec` | `900` | Per-invocation timeout. 15 min is Lambda's hard ceiling. |
| `ReservedConcurrency` | `-1` | Hard cap on simultaneous Lambda invocations. `-1` = unreserved. Set to e.g. `50` to bound cost. |
| `ChromeSource` | `sparticuz` | Must match the `--source=` flag passed to `build-zip.ts`. |
| `ChromeSource` | `sparticuz` | Must match the `--source=` flag passed to `build-zip.ts`; a shell ZIP is over Lambda's limit. |
| `ChunkInvocationAlarmThreshold` | `1000` | CloudWatch alarm threshold (RenderChunk invocations per hour). |

## Cleanup
Expand Down
5 changes: 3 additions & 2 deletions examples/aws-lambda/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ Parameters:
Description: >-
Which Chrome runtime the bundled ZIP was built with. Must match the
`--source=` flag passed to `build-zip.ts`. The handler reads this
via the HYPERFRAMES_LAMBDA_CHROME_SOURCE env var at boot. The arm64
video image always runs its own chrome-headless-shell.
via the HYPERFRAMES_LAMBDA_CHROME_SOURCE env var at boot. A
chrome-headless-shell ZIP is over Lambda's unzipped limit today; the
arm64 video image always runs its own chrome-headless-shell.
ChunkInvocationAlarmThreshold:
Type: Number
Expand Down
29 changes: 19 additions & 10 deletions packages/aws-lambda/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,10 @@ when `sites/<id>/files.json` is missing, the render uses that site's

The package supports two Chromium sources:

| Source | Default | Size | When to pick it |
| ------------------------------- | ------- | ------------------ | --------------------------------------------------------------------------------------------------------------------- |
| `@sparticuz/chromium` | yes | ~70 MiB compressed | Lambda. Decompresses into `/tmp` at runtime; the rest of the ecosystem already uses it for headless-Chrome-in-Lambda. |
| Bundled `chrome-headless-shell` | no | ~296 MB | Fallback. Used if `@sparticuz/chromium` ever drops `HeadlessExperimental.beginFrame` support. |
| Source | Default | Size | When to pick it |
| ------------------------------- | ------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `@sparticuz/chromium` | yes | ~70 MiB compressed | Lambda. Decompresses into `/tmp` at runtime; the rest of the ecosystem already uses it for headless-Chrome-in-Lambda. |
| Bundled `chrome-headless-shell` | no | ~296 MB | Does not fit a ZIP function today. Kept for the case where `@sparticuz/chromium` drops `HeadlessExperimental.beginFrame`. |

Pick the source at build time:

Expand All @@ -105,14 +105,19 @@ bun run --cwd packages/aws-lambda build:zip -- --source=chrome-headless-shell
The handler reads `HYPERFRAMES_LAMBDA_CHROME_SOURCE` at boot, and for
`chrome-headless-shell` the executable from `HYPERFRAMES_LAMBDA_CHROME_PATH`.
`examples/aws-lambda/template.yaml` and the CDK construct set both from the
Chrome source. The build stages the whole shell folder (the executable needs
its ICU data and `.pak` files beside it), which is over Lambda's 250 MiB
unzipped limit for a ZIP function, so the x86 ZIP ships `@sparticuz/chromium`.
Chrome source. The build stages the repo's pinned shell build, and only when
its folder matches the pinned digest. It stages the whole folder (the
executable needs its ICU data and `.pak` files beside it), which is over
Lambda's 250 MiB unzipped limit for a ZIP function, so the build fails its
size gate and the x86 ZIP ships `@sparticuz/chromium`. `hyperframes lambda
deploy` refuses `--chrome-source chrome-headless-shell` for the same reason.

The arm64 video image (`image/Dockerfile`, `video` target) does not use
`@sparticuz/chromium`: it installs Chrome for Testing's linux-arm64
`chrome-headless-shell` folder, pinned by version and sha256, with the shared
libraries and fonts it needs, and sets both env vars itself.
libraries it needs, and sets both env vars itself. It keeps `@sparticuz/chromium`'s
fonts and `fonts.conf` from the handler ZIP, so text resolves to the same fonts as
on the x86 function; CI compares the two on a mixed-script page.

## BeginFrame regression guard

Expand All @@ -130,7 +135,9 @@ bun run --cwd packages/aws-lambda probe:beginframe:docker
The probe boots `@sparticuz/chromium` inside
`public.ecr.aws/lambda/nodejs:22` and asserts CDP `beginFrame` with
`screenshot: true` returns a PNG buffer. Exit code 0 = green; non-zero =
fall back to bundling chrome-headless-shell directly via `--source=chrome-headless-shell`.
`@sparticuz/chromium` lost BeginFrame. `--source=chrome-headless-shell` does
not fit a ZIP function, so that function would move to a container image like
the arm64 video function.

## Building the ZIP

Expand All @@ -150,7 +157,9 @@ designed to extract cleanly into Lambda's `/var/task/`.
- Unzipped ≤ 248 MiB (in-house budget; Lambda hard ceiling is 250 MiB unzipped — AWS docs label this "250 MB" but use binary mebibytes)
- Zipped ≤ 150 MiB (in-house budget; Lambda has no hard zipped cap for S3-deployed functions)

CI fails the PR if either is exceeded.
The sparticuz ZIP is about 1.5 MiB under the unzipped budget, and the handler
bundles the producer, engine and core. So the `Lambda handler ZIP` workflow
builds it on every PR that touches them, and fails the PR if either is exceeded.

## Running tests

Expand Down
10 changes: 6 additions & 4 deletions packages/aws-lambda/image/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,17 @@ COPY --from=check /check.txt /hf-media-check.txt
# The video function. /var/task comes from scripts/stage-arm64-image.ts as the `task` build context:
# docker buildx build --platform linux/arm64 --target video --build-context task=<out>/task packages/aws-lambda/image
# Its Chrome is Chrome for Testing's linux-arm64 chrome-headless-shell, the whole folder: the executable
# alone finds no ICU data or .pak resources. The base has none of the shared libraries the shell links
# and no fonts, so they come from the base's own repository; this RUN needs an arm64 host or emulation.
# alone finds no ICU data or .pak resources. The base has none of the shared libraries the shell links, so
# they come from the base's own repository; this RUN needs an arm64 host or emulation. Its fonts are the
# x86 function's: stage-arm64-image.ts unpacks @sparticuz/chromium's fonts and fonts.conf into /var/task/fonts.
# Bump the version and the archive's sha256 together, with the rest of the repo's pins.
FROM ${BASE} AS video
ARG CHROME_HEADLESS_SHELL_VERSION=158.0.8127.36
ARG CHROME_HEADLESS_SHELL_SHA256=176ee5c55486c22de43128871189061365ea28e881fc96016fd18e7cb59437c8
COPY fetch.sh /fetch.sh
RUN . /fetch.sh && retry microdnf install -y --nodocs --setopt=install_weak_deps=0 --releasever=2023.12.20260914 \
alsa-lib at-spi2-atk at-spi2-core atk dbus-libs expat fontconfig libX11 libXcomposite libXdamage \
libXext libXfixes libXrandr libxcb libxkbcommon liberation-fonts mesa-libgbm nspr nss nss-util \
libXext libXfixes libXrandr libxcb libxkbcommon mesa-libgbm nspr nss nss-util \
systemd-libs unzip && \
curl -fsSL --retry 5 --retry-all-errors --retry-delay 3 --connect-timeout 20 --max-time 600 -o /tmp/chs.zip \
"https://storage.googleapis.com/chrome-for-testing-public/${CHROME_HEADLESS_SHELL_VERSION}/linux-arm64/chrome-headless-shell-linux-arm64.zip" && \
Expand All @@ -57,6 +58,7 @@ RUN . /fetch.sh && retry microdnf install -y --nodocs --setopt=install_weak_deps
/opt/chrome-headless-shell-linux-arm64/chrome-headless-shell --version | grep -F "${CHROME_HEADLESS_SHELL_VERSION}"
# src/chromium.ts launches this executable.
ENV HYPERFRAMES_LAMBDA_CHROME_SOURCE=chrome-headless-shell \
HYPERFRAMES_LAMBDA_CHROME_PATH=/opt/chrome-headless-shell-linux-arm64/chrome-headless-shell
HYPERFRAMES_LAMBDA_CHROME_PATH=/opt/chrome-headless-shell-linux-arm64/chrome-headless-shell \
FONTCONFIG_PATH=/var/task/fonts
COPY --from=task / /var/task/
CMD ["handler.handler"]
61 changes: 54 additions & 7 deletions packages/aws-lambda/image/smoke-video.mjs
Original file line number Diff line number Diff line change
@@ -1,27 +1,74 @@
// A handler mounted into the video image and invoked through its own Lambda bootstrap, which sets
// AWS_EXECUTION_ENV as Lambda does: the bundled ffmpeg answers and the image's chrome-headless-shell
// renders, found where src/chromium.ts finds it and launched with the engine's Lambda flags.
// A handler mounted into a Lambda Node 22 image and invoked through its own Lambda bootstrap, which sets
// AWS_EXECUTION_ENV as Lambda does. In the arm64 video image it runs the image's chrome-headless-shell, found
// where src/chromium.ts finds it; in the x86 base over the unzipped handler ZIP, @sparticuz/chromium.
// It reports the platform fonts each line of a mixed-script page renders with, so the two can be compared.
import { execFileSync } from "node:child_process";
import puppeteer from "puppeteer-core";

const LINES = {
latin: "sans-serif|Quick brown fox ÀÉÎÕÜ ß œ",
serif: "serif|Quick brown fox ÀÉÎÕÜ ß œ",
mono: "monospace|Quick brown fox 0123456789",
greekCyrillic: "sans-serif|Ελληνικά Кириллица",
cjk: "sans-serif|漢字 かな カナ 한국어",
arabic: "sans-serif|العربية",
emoji: "sans-serif|😀 🎬 ✅",
};

const textPage = Object.entries(LINES)
.map(([id, line]) => {
const [family, text] = line.split("|");
return `<p id="${id}" style="font:24px ${family};margin:4px">${text}</p>`;
})
.join("");

async function launch() {
if (process.env.HYPERFRAMES_LAMBDA_CHROME_PATH) {
return puppeteer.launch({
executablePath: process.env.HYPERFRAMES_LAMBDA_CHROME_PATH,
args: ["--no-sandbox", "--disable-setuid-sandbox", "--no-zygote", "--disable-dev-shm-usage"],
});
}
const { default: chromium } = await import("@sparticuz/chromium");
return puppeteer.launch({ executablePath: await chromium.executablePath(), args: chromium.args });
}

async function platformFonts(page) {
const cdp = await page.createCDPSession();
await cdp.send("DOM.enable");
await cdp.send("CSS.enable");
const { root } = await cdp.send("DOM.getDocument", { depth: -1 });
const fonts = {};
for (const id of Object.keys(LINES)) {
const { nodeId } = await cdp.send("DOM.querySelector", {
nodeId: root.nodeId,
selector: `#${id}`,
});
const { fonts: used } = await cdp.send("CSS.getPlatformFontsForNode", { nodeId });
fonts[id] = used.map((font) => `${font.familyName}:${font.glyphCount}`).sort();
}
return fonts;
}

export const handler = async () => {
const ffmpeg = execFileSync("/var/task/bin/ffmpeg", ["-hide_banner", "-version"], {
encoding: "utf-8",
}).split("\n")[0];
const browser = await puppeteer.launch({
executablePath: process.env.HYPERFRAMES_LAMBDA_CHROME_PATH,
args: ["--no-sandbox", "--disable-setuid-sandbox", "--no-zygote", "--disable-dev-shm-usage"],
});
const browser = await launch();
try {
const page = await browser.newPage();
await page.setContent("<div style='width:64px;height:64px;background:#0a0'></div>");
const shot = await page.screenshot({ clip: { x: 0, y: 0, width: 64, height: 64 } });
await page.setViewport({ width: 640, height: 360 });
await page.setContent(textPage);
return {
executionEnv: process.env.AWS_EXECUTION_ENV,
arch: process.arch,
ffmpeg,
chrome: await browser.version(),
screenshotBytes: shot.length,
fonts: await platformFonts(page),
textPng: Buffer.from(await page.screenshot()).toString("base64"),
};
} finally {
await browser.close();
Expand Down
1 change: 1 addition & 0 deletions packages/aws-lambda/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"tar": "^7.5.22"
},
"devDependencies": {
"@hyperframes/engine": "workspace:*",
"@types/node": "^25.0.10",
"@types/tar": "^6.1.13",
"aws-cdk-lib": "^2.130.0",
Expand Down
Loading
Loading