Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat: ship the media function, its image and its publish path

kashorin7a5b4d1064b5
diff --git a/package.json b/package.json
index 91c4824b..ac356656 100644
--- a/package.json
+++ b/package.json
@@ -8,12 +8,13 @@
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs",
- "test": "node --import tsx --test 'packages/*/test/**/*.test.ts' 'test/**/*.test.ts' 'tools/*.test.mjs'",
+ "test": "node --import tsx --test 'packages/*/test/**/*.test.ts' 'services/*/test/**/*.test.ts' 'test/**/*.test.ts' 'tools/*.test.mjs'",
"test:whisperx-service": "uv run --project services/whisperx --frozen python -m unittest discover -s services/whisperx/tests -p 'test_*.py'",
"test:image-opencv": "SVML_OPENCV_TESTS=1 SVML_OPENCV_PYTHON=services/image-opencv/.venv/bin/python node --import tsx --test packages/provider-image-opencv-local/test/provider.test.ts",
"smoke:kie": "node --import tsx packages/provider-kie/test/live-smoke.ts",
"narratage": "node --import tsx packages/video-cli/src/cli.ts",
- "svml": "node --import tsx packages/video-cli/src/cli.ts"
+ "svml": "node --import tsx packages/video-cli/src/cli.ts",
+ "build:media-lambda": "pnpm --filter @narratage/media-lambda build"
},
"engines": {
"node": ">=22"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 198ca5bb..7077dcd2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1732,6 +1732,25 @@ importers:
specifier: workspace:*
version: link:../protocol
+ services/media-lambda:
+ dependencies:
+ '@narratage/artifact-store-s3':
+ specifier: workspace:*
+ version: link:../../packages/artifact-store-s3
+ '@narratage/media-execution':
+ specifier: workspace:*
+ version: link:../../packages/media-execution
+ '@narratage/protocol':
+ specifier: workspace:*
+ version: link:../../packages/protocol
+ '@narratage/provider-media-aws-lambda':
+ specifier: workspace:*
+ version: link:../../packages/provider-media-aws-lambda
+ devDependencies:
+ esbuild:
+ specifier: ^0.25.0
+ version: 0.25.12
+
packages:
'@algolia/[email protected]':
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 924b55f4..b935844d 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,2 +1,3 @@
packages:
- packages/*
+ - services/media-lambda
diff --git a/services/media-lambda/Dockerfile b/services/media-lambda/Dockerfile
new file mode 100644
index 00000000..c75f2426
--- /dev/null
+++ b/services/media-lambda/Dockerfile
@@ -0,0 +1,16 @@
+# FFmpeg is pinned by digest-bearing tag and then asserted, because a mutable
+# upstream tag must never quietly change what a Build computes.
+FROM mwader/static-ffmpeg:8.0.1 AS ffmpeg
+
+FROM public.ecr.aws/lambda/nodejs:20
+COPY --from=ffmpeg /ffmpeg /opt/bin/ffmpeg
+COPY --from=ffmpeg /ffprobe /opt/bin/ffprobe
+RUN /opt/bin/ffmpeg -version | head -1 | grep -q 'ffmpeg version 8.0.1' \
+ && /opt/bin/ffprobe -version | head -1 | grep -q 'ffprobe version 8.0.1'
+
+ENV FFMPEG_PATH=/opt/bin/ffmpeg \
+ FFPROBE_PATH=/opt/bin/ffprobe \
+ NODE_ENV=production
+
+COPY index.mjs ${LAMBDA_TASK_ROOT}/index.mjs
+CMD ["index.handler"]
diff --git a/services/media-lambda/README.md b/services/media-lambda/README.md
new file mode 100644
index 00000000..21da20b1
--- /dev/null
+++ b/services/media-lambda/README.md
@@ -0,0 +1,61 @@
+# Narratage media function
+
+The five media Needs — inspect, normalize, speech-evidence projection, timeline
+audio and mux — executed in AWS Lambda instead of on the machine running the
+Build. This is deployment state, not an author-importable SVML package.
+
+It owns no media logic. `@narratage/media-execution` holds the ffmpeg argv and
+the frame arithmetic, and the same code answers a local Build through
+`@narratage/provider-media-local`. Only two things are particular to this
+deployment: where the bytes live, and which ffmpeg binary the image carries.
+
+## What it requires, and why
+
+**An S3 ArtifactStore, shared with the function.** A synchronous Lambda
+invocation carries a few megabytes; a programme does not fit. So media never
+travels in the payload — the request names the bucket the Artifacts already
+occupy, and the function reads and writes there using the same
+content-addressed key rule as `@narratage/artifact-store-s3`. A Provider
+configured against a different bucket fails on the first result, naming the
+Artifact it cannot read.
+
+**An execution role** that can read and write the Artifact prefix in that
+bucket, and write CloudWatch Logs. Nothing else.
+
+## Deploying it
+
+```bash
+export AWS_REGION=us-east-1
+export AWS_ACCOUNT_ID=123456789012
+export NARRATAGE_MEDIA_BUCKET=your-artifact-bucket
+./publish.sh
+```
+
+`publish.sh` bundles the handler, asserts the FFmpeg version inside the image,
+pushes to ECR under an immutable `bundle-<sha256>` tag, creates or updates the
+function, publishes a **version**, and prints the Runtime Profile entry to
+paste. Overridable: `NARRATAGE_MEDIA_REPOSITORY`, `_FUNCTION`, `_ROLE`,
+`_MEMORY` (3008), `_TIMEOUT` (900), `_EPHEMERAL` (8192).
+
+The printed ARN ends in `:<version>`. The Provider refuses an unqualified ARN:
+a bare function name is whatever was deployed last, and two Builds of one Run
+Source could then execute different code while recording the same Endpoint
+identity.
+
+## Checking it before you depend on it
+
+```bash
+pnpm narratage doctor svml.runtime.json
+```
+
+## Tests
+
+The handler is tested against real ffmpeg over an in-memory bucket, so the
+whole chain except AWS itself runs in `pnpm test`. What that does **not** cover
+is the deployed image, the role's permissions and the account's limits; those
+are only proven by publishing once and running a Build.
+
+```bash
+pnpm test # includes services/media-lambda/test
+pnpm build:media-lambda # bundle only, no AWS
+```
diff --git a/services/media-lambda/build.mjs b/services/media-lambda/build.mjs
new file mode 100755
index 00000000..4a0245a2
--- /dev/null
+++ b/services/media-lambda/build.mjs
@@ -0,0 +1,35 @@
+#!/usr/bin/env node
+// Bundles the handler to one ESM file, so the image carries no node_modules
+// and its content hash is a function of the source alone.
+import { mkdir, writeFile } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { build } from "esbuild";
+
+const root = dirname(fileURLToPath(import.meta.url));
+const out = join(root, "build");
+await mkdir(out, { recursive: true });
+
+const result = await build({
+ entryPoints: [join(root, "src/handler.ts")],
+ outfile: join(out, "index.mjs"),
+ bundle: true,
+ platform: "node",
+ target: "node20",
+ format: "esm",
+ // The AWS SDK is bundled rather than taken from the runtime, so the image
+ // pins the same client version the tests ran against.
+ banner: { js: "import{createRequire}from'node:module';const require=createRequire(import.meta.url);" },
+ metafile: true,
+ logLevel: "info",
+});
+if (result.errors.length > 0) process.exit(1);
+
+const { readFile } = await import("node:fs/promises");
+const bundle = await readFile(join(out, "index.mjs"));
+const dockerfile = await readFile(join(root, "Dockerfile"));
+const hash = createHash("sha256").update(bundle).update(dockerfile).digest("hex");
+await writeFile(join(out, "Dockerfile"), dockerfile);
+await writeFile(join(out, "bundle-hash.txt"), `${hash}\n`);
+process.stdout.write(`${JSON.stringify({ bundleHash: hash, bytes: bundle.byteLength }, null, 2)}\n`);
diff --git a/services/media-lambda/build/Dockerfile b/services/media-lambda/build/Dockerfile
new file mode 100644
index 00000000..c75f2426
--- /dev/null
+++ b/services/media-lambda/build/Dockerfile
@@ -0,0 +1,16 @@
+# FFmpeg is pinned by digest-bearing tag and then asserted, because a mutable
+# upstream tag must never quietly change what a Build computes.
+FROM mwader/static-ffmpeg:8.0.1 AS ffmpeg
+
+FROM public.ecr.aws/lambda/nodejs:20
+COPY --from=ffmpeg /ffmpeg /opt/bin/ffmpeg
+COPY --from=ffmpeg /ffprobe /opt/bin/ffprobe
+RUN /opt/bin/ffmpeg -version | head -1 | grep -q 'ffmpeg version 8.0.1' \
+ && /opt/bin/ffprobe -version | head -1 | grep -q 'ffprobe version 8.0.1'
+
+ENV FFMPEG_PATH=/opt/bin/ffmpeg \
+ FFPROBE_PATH=/opt/bin/ffprobe \
+ NODE_ENV=production
+
+COPY index.mjs ${LAMBDA_TASK_ROOT}/index.mjs
+CMD ["index.handler"]
diff --git a/services/media-lambda/package.json b/services/media-lambda/package.json
new file mode 100644
index 00000000..de2731a2
--- /dev/null
+++ b/services/media-lambda/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@narratage/media-lambda",
+ "version": "0.0.0-dev",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/handler.ts"
+ },
+ "dependencies": {
+ "@narratage/artifact-store-s3": "workspace:*",
+ "@narratage/media-execution": "workspace:*",
+ "@narratage/protocol": "workspace:*",
+ "@narratage/provider-media-aws-lambda": "workspace:*"
+ },
+ "scripts": {
+ "build": "node build.mjs"
+ },
+ "devDependencies": {
+ "esbuild": "^0.25.0"
+ }
+}
diff --git a/services/media-lambda/publish.sh b/services/media-lambda/publish.sh
new file mode 100755
index 00000000..242453ac
--- /dev/null
+++ b/services/media-lambda/publish.sh
@@ -0,0 +1,86 @@
+#!/usr/bin/env bash
+# Build, push and publish one immutable version of the media function.
+#
+# Every value below is read from the environment with no default that could
+# reach someone else's account. Run it once per deployment; the ARN it prints
+# is what a Runtime Profile names.
+set -euo pipefail
+
+: "${AWS_REGION:?set AWS_REGION, e.g. us-east-1}"
+: "${AWS_ACCOUNT_ID:?set AWS_ACCOUNT_ID, your 12-digit account id}"
+: "${NARRATAGE_MEDIA_BUCKET:?set NARRATAGE_MEDIA_BUCKET, the ArtifactStore bucket the function shares}"
+REPOSITORY="${NARRATAGE_MEDIA_REPOSITORY:-narratage-media}"
+FUNCTION="${NARRATAGE_MEDIA_FUNCTION:-narratage-media}"
+ROLE="${NARRATAGE_MEDIA_ROLE:-NarratageMediaExecution}"
+MEMORY="${NARRATAGE_MEDIA_MEMORY:-3008}"
+TIMEOUT="${NARRATAGE_MEDIA_TIMEOUT:-900}"
+EPHEMERAL="${NARRATAGE_MEDIA_EPHEMERAL:-8192}"
+
+here="$(cd "$(dirname "$0")" && pwd)"
+registry="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
+
+echo "==> bundling"
+(cd "$here" && node build.mjs >/dev/null)
+hash="$(cat "$here/build/bundle-hash.txt")"
+tag="bundle-${hash}"
+echo " bundle ${hash}"
+
+echo "==> ensuring the ECR repository exists with immutable tags"
+aws ecr describe-repositories --region "$AWS_REGION" --repository-names "$REPOSITORY" >/dev/null 2>&1 \
+ || aws ecr create-repository --region "$AWS_REGION" --repository-name "$REPOSITORY" \
+ --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true >/dev/null
+
+echo "==> building and pushing ${registry}/${REPOSITORY}:${tag}"
+aws ecr get-login-password --region "$AWS_REGION" \
+ | docker login --username AWS --password-stdin "$registry" >/dev/null
+# Lambda runs x86_64 here; the image must match whatever --architectures says.
+docker buildx build --platform linux/amd64 --provenance=false \
+ -t "${registry}/${REPOSITORY}:${tag}" "$here/build" --push
+
+digest="$(aws ecr describe-images --region "$AWS_REGION" --repository-name "$REPOSITORY" \
+ --image-ids imageTag="$tag" --query 'imageDetails[0].imageDigest' --output text)"
+image="${registry}/${REPOSITORY}@${digest}"
+echo " image ${digest}"
+
+echo "==> creating or updating the function"
+if aws lambda get-function --region "$AWS_REGION" --function-name "$FUNCTION" >/dev/null 2>&1; then
+ aws lambda update-function-code --region "$AWS_REGION" --function-name "$FUNCTION" \
+ --image-uri "$image" >/dev/null
+ aws lambda wait function-updated --region "$AWS_REGION" --function-name "$FUNCTION"
+ aws lambda update-function-configuration --region "$AWS_REGION" --function-name "$FUNCTION" \
+ --memory-size "$MEMORY" --timeout "$TIMEOUT" \
+ --ephemeral-storage "Size=${EPHEMERAL}" \
+ --environment "Variables={NARRATAGE_MEDIA_BUNDLE_HASH=${hash}}" >/dev/null
+ aws lambda wait function-updated --region "$AWS_REGION" --function-name "$FUNCTION"
+else
+ aws lambda create-function --region "$AWS_REGION" --function-name "$FUNCTION" \
+ --package-type Image --code "ImageUri=${image}" \
+ --role "arn:aws:iam::${AWS_ACCOUNT_ID}:role/${ROLE}" \
+ --architectures x86_64 --memory-size "$MEMORY" --timeout "$TIMEOUT" \
+ --ephemeral-storage "Size=${EPHEMERAL}" \
+ --environment "Variables={NARRATAGE_MEDIA_BUNDLE_HASH=${hash}}" >/dev/null
+ aws lambda wait function-active --region "$AWS_REGION" --function-name "$FUNCTION"
+fi
+
+# A version, not $LATEST. The Provider refuses an unqualified ARN, because a
+# bare name is whatever was deployed last and two Builds of one Run Source
+# could then execute different code under one Endpoint identity.
+version="$(aws lambda publish-version --region "$AWS_REGION" --function-name "$FUNCTION" \
+ --description "bundle ${hash}" --query 'Version' --output text)"
+arn="arn:aws:lambda:${AWS_REGION}:${AWS_ACCOUNT_ID}:function:${FUNCTION}:${version}"
+
+cat <<JSON
+
+Published. Add this to the endpoints of your Runtime Profile:
+
+ {
+ "use": "@narratage/provider-media-aws-lambda",
+ "instance": "media.aws-lambda",
+ "lane": "media",
+ "config": {
+ "functionArn": "${arn}",
+ "bucket": "${NARRATAGE_MEDIA_BUCKET}"
+ }
+ }
+
+JSON
diff --git a/services/media-lambda/src/handler.ts b/services/media-lambda/src/handler.ts
new file mode 100644
index 00000000..90e098f3
--- /dev/null
+++ b/services/media-lambda/src/handler.ts
@@ -0,0 +1,137 @@
+import { s3ArtifactKey } from "@narratage/artifact-store-s3";
+import { AwsS3ObjectClient } from "@narratage/artifact-store-s3";
+import type { S3ObjectClient } from "@narratage/artifact-store-s3";
+import {
+ executeInspectMedia,
+ executeMuxProgramMedia,
+ executeNormalizeMedia,
+ executeProjectSpeechEvidenceAudio,
+ executeRenderTimelineAudio,
+} from "@narratage/media-execution";
+import type { MediaExecutionEnvironment, MediaOperationResult } from "@narratage/media-execution";
+import { createHash } from "node:crypto";
+import type { BlobRef, CanonicalValue, Digest } from "@narratage/protocol";
+import {
+ MEDIA_LAMBDA_RESPONSE,
+ parseMediaLambdaRequest,
+} from "@narratage/provider-media-aws-lambda";
+import type { MediaLambdaArtifactLocation, MediaLambdaOperation } from "@narratage/provider-media-aws-lambda";
+
+/**
+ * The whole function.
+ *
+ * It owns no media logic: `@narratage/media-execution` holds the ffmpeg argv
+ * and the frame arithmetic, and the same code answers a local Build. What is
+ * particular to this deployment is only where the bytes live and which ffmpeg
+ * binary the image carries.
+ */
+const OPERATIONS: Record<
+ MediaLambdaOperation,
+ (env: MediaExecutionEnvironment, constraints: CanonicalValue) => Promise<MediaOperationResult>
+> = {
+ "inspect": executeInspectMedia,
+ "normalize": executeNormalizeMedia,
+ "project-speech-evidence-audio": executeProjectSpeechEvidenceAudio,
+ "render-audio": executeRenderTimelineAudio,
+ "mux": executeMuxProgramMedia,
+};
+
+const FFMPEG_PATH = process.env.FFMPEG_PATH ?? "/opt/bin/ffmpeg";
+const FFPROBE_PATH = process.env.FFPROBE_PATH ?? "/opt/bin/ffprobe";
+
+function positiveInteger(value: string | undefined, fallback: number): number {
+ if (value === undefined) return fallback;
+ const parsed = Number.parseInt(value, 10);
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`${value} is not a positive integer`);
+ return parsed;
+}
+
+/**
+ * The bucket, addressed by the same content-addressing rule the ArtifactStore
+ * uses. Writes are conditional, so two functions racing on identical bytes
+ * agree rather than conflict.
+ */
+function gateway(location: MediaLambdaArtifactLocation, client: S3ObjectClient) {
+ return {
+ async get(source: BlobRef): Promise<Uint8Array | undefined> {
+ return await client.get({ Bucket: location.bucket, Key: s3ArtifactKey(location.prefix, source.digest) });
+ },
+ async put(bytes: Uint8Array, mediaType: string): Promise<BlobRef> {
+ const copy = Uint8Array.from(bytes);
+ const digest = `sha256:${createHash("sha256").update(copy).digest("hex")}` as Digest;
+ try {
+ await client.put({
+ Bucket: location.bucket,
+ Key: s3ArtifactKey(location.prefix, digest),
+ Body: copy,
+ ContentLength: copy.byteLength,
+ ContentType: mediaType,
+ IfNoneMatch: "*",
+ Metadata: { "svml-digest": digest, "svml-size": String(copy.byteLength) },
+ });
+ } catch (error) {
+ const status = (error as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode;
+ // 412: these exact bytes are already stored. Under content addressing
+ // that is agreement, not conflict.
+ if (status !== 412) throw error;
+ }
+ return { kind: "blob", digest, size: copy.byteLength, mediaType };
+ },
+ };
+}
+
+function failure(operation: MediaLambdaOperation, error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ return {
+ contract: MEDIA_LAMBDA_RESPONSE,
+ operation,
+ ok: false as const,
+ code: "MEDIA_OPERATION_FAILED",
+ message,
+ };
+}
+
+export type MediaLambdaHandlerOptions = {
+ /** Injection point for tests, MinIO and specially configured trusted AWS clients. */
+ readonly client?: S3ObjectClient;
+ readonly ffmpegPath?: string;
+ readonly ffprobePath?: string;
+};
+
+/**
+ * The handler, with its S3 client and binaries open to substitution. The
+ * deployed entry point below closes them over the image's own defaults; a test
+ * can supply an in-memory bucket and run the real ffmpeg.
+ */
+export function createMediaLambdaHandler(options: MediaLambdaHandlerOptions = {}) {
+ return async function handle(event: unknown): Promise<unknown> {
+ let operation: MediaLambdaOperation = "inspect";
+ try {
+ const request = parseMediaLambdaRequest(event);
+ operation = request.operation;
+ const env: MediaExecutionEnvironment = {
+ artifacts: gateway(request.artifacts, options.client ?? new AwsS3ObjectClient({})),
+ ffmpegPath: options.ffmpegPath ?? FFMPEG_PATH,
+ ffprobePath: options.ffprobePath ?? FFPROBE_PATH,
+ processTimeoutMs: positiveInteger(process.env.SVML_MEDIA_TIMEOUT_MS, 14 * 60_000),
+ maxProbeOutputBytes: positiveInteger(process.env.SVML_MEDIA_MAX_PROBE_BYTES, 256 * 1024 * 1024),
+ label: "media.aws-lambda",
+ };
+ const result = await OPERATIONS[operation](env, request.constraints);
+ return {
+ contract: MEDIA_LAMBDA_RESPONSE,
+ operation,
+ ok: true as const,
+ value: result.value,
+ metadata: result.metadata,
+ };
+ } catch (error) {
+ // Never thrown: the transport will not copy a failed function's payload
+ // into its error, so a throw would reach the Build as "Unhandled".
+ return failure(operation, error);
+ }
+ };
+}
+
+/** The image's entry point. */
+export const handler = createMediaLambdaHandler();
diff --git a/services/media-lambda/test/handler.test.ts b/services/media-lambda/test/handler.test.ts
new file mode 100644
index 00000000..ff42d6b7
--- /dev/null
+++ b/services/media-lambda/test/handler.test.ts
@@ -0,0 +1,104 @@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { createHash } from "node:crypto";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { promisify } from "node:util";
+
+import { s3ArtifactKey } from "@narratage/artifact-store-s3";
+import type { S3ObjectClient } from "@narratage/artifact-store-s3";
+import type { Digest } from "@narratage/protocol";
+
+import { createMediaLambdaHandler } from "../src/handler.js";
+
+const run = promisify(execFile);
+
+/** The bucket, in memory. Conditional writes behave as S3's do. */
+class Bucket implements S3ObjectClient {
+ readonly values = new Map<string, Uint8Array>();
+ async put(input: Parameters<S3ObjectClient["put"]>[0]): Promise<void> {
+ if (input.IfNoneMatch === "*" && this.values.has(input.Key!)) {
+ throw { $metadata: { httpStatusCode: 412 } };
+ }
+ this.values.set(input.Key!, Uint8Array.from(input.Body as Uint8Array));
+ }
+ async get(input: Parameters<S3ObjectClient["get"]>[0]): Promise<Uint8Array | undefined> {
+ const value = this.values.get(input.Key!);
+ return value === undefined ? undefined : Uint8Array.from(value);
+ }
+}
+
+async function ffmpegAvailable(): Promise<boolean> {
+ try {
+ await run("ffmpeg", ["-version"]);
+ await run("ffprobe", ["-version"]);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+test("the function answers a real Need with real media, over a bucket it addresses like the store does",
+ { skip: (await ffmpegAvailable()) ? false : "ffmpeg and ffprobe are not on PATH" },
+ async () => {
+ const work = await mkdtemp(join(tmpdir(), "svml-media-lambda-"));
+ try {
+ // One second of real audio, so ffprobe has something true to report.
+ const path = join(work, "source.wav");
+ await run("ffmpeg", ["-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=1",
+ "-c:a", "pcm_s16le", "-ar", "48000", "-ac", "2", path]);
+ const bytes = await readFile(path);
+ const digest = `sha256:${createHash("sha256").update(bytes).digest("hex")}` as Digest;
+
+ const bucket = new Bucket();
+ // Placed at the key the ArtifactStore would have used — the shared law.
+ bucket.values.set(s3ArtifactKey("svml", digest), Uint8Array.from(bytes));
+
+ const handle = createMediaLambdaHandler({ client: bucket, ffmpegPath: "ffmpeg", ffprobePath: "ffprobe" });
+ const reply = await handle({
+ contract: "svml.media-lambda-request@1",
+ operation: "inspect",
+ artifacts: { bucket: "fixture", prefix: "svml" },
+ constraints: {
+ contract: "svml.inspect-media-request@1",
+ source: { kind: "blob", digest, size: bytes.byteLength, mediaType: "audio/wav" },
+ },
+ }) as Record<string, unknown>;
+
+ assert.equal(reply.ok, true, `the function failed: ${JSON.stringify(reply)}`);
+ assert.equal(reply.operation, "inspect");
+ const value = reply.value as { contract: string; streams: { kind: string; sampleRate: number }[] };
+ assert.equal(value.contract, "svml.media-inspection@1");
+ assert.equal(value.streams.length, 1);
+ assert.equal(value.streams[0]!.kind, "audio");
+ assert.equal(value.streams[0]!.sampleRate, 48_000);
+ assert.deepEqual(reply.metadata, { operation: "inspect", provider: "media.aws-lambda" });
+ } finally {
+ await rm(work, { recursive: true, force: true });
+ }
+ });
+
+test("a source the bucket does not hold is a typed failure, never a throw", async () => {
+ const handle = createMediaLambdaHandler({ client: new Bucket() });
+ const reply = await handle({
+ contract: "svml.media-lambda-request@1",
+ operation: "inspect",
+ artifacts: { bucket: "fixture" },
+ constraints: {
+ contract: "svml.inspect-media-request@1",
+ source: { kind: "blob", digest: `sha256:${"0".repeat(64)}`, size: 1, mediaType: "audio/wav" },
+ },
+ }) as Record<string, unknown>;
+ assert.equal(reply.ok, false);
+ assert.equal(reply.code, "MEDIA_OPERATION_FAILED");
+ assert.match(String(reply.message), /is unavailable/u);
+});
+
+test("an envelope from another contract is refused before any media is touched", async () => {
+ const handle = createMediaLambdaHandler({ client: new Bucket() });
+ const reply = await handle({ contract: "svml.media-lambda-request@0" }) as Record<string, unknown>;
+ assert.equal(reply.ok, false);
+ assert.match(String(reply.message), /contract must be svml\.media-lambda-request@1/u);
+});
diff --git a/tsconfig.json b/tsconfig.json
index 4ec9a164..77f03c41 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -221,7 +221,8 @@
}
},
"include": [
- "packages/**/*.ts"
+ "packages/**/*.ts",
+ "services/media-lambda/src/**/*.ts"
],
"exclude": [
"dist",