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: fulfil the media Needs through AWS Lambda

kashorin9a4974954182
diff --git a/packages/artifact-store-s3/src/index.ts b/packages/artifact-store-s3/src/index.ts
index 10bb9ede..0913a590 100644
--- a/packages/artifact-store-s3/src/index.ts
+++ b/packages/artifact-store-s3/src/index.ts
@@ -1,10 +1,9 @@
-export {
- AwsS3ObjectClient,
-} from "./client.js";
-export type { S3ObjectClient } from "./client.js";
+export { AwsS3ObjectClient } from "./client.js";
+export type { S3ListPage, S3ObjectClient } from "./client.js";
export {
S3ArtifactStore,
createS3ArtifactStorePackage,
+ s3ArtifactKey,
s3ArtifactStoreImplementationDigest,
s3ArtifactStoreModuleRef,
} from "./store.js";
diff --git a/packages/artifact-store-s3/src/store.ts b/packages/artifact-store-s3/src/store.ts
index 414d007b..743eba84 100644
--- a/packages/artifact-store-s3/src/store.ts
+++ b/packages/artifact-store-s3/src/store.ts
@@ -17,6 +17,22 @@ export const s3ArtifactStoreImplementationDigest = digestOf(
"@narratage/artifact-store-s3/artifact-store@1",
);
+/**
+ * Where an Artifact lives in a bucket, given its digest.
+ *
+ * Exported because a remote worker that reads and writes the same bucket must
+ * address objects identically. Two statements of this rule would be two
+ * different stores wearing one bucket name.
+ */
+export function s3ArtifactKey(prefix: string | undefined, digest: Digest): string {
+ if (!isDigest(digest)) throw new Error("Artifact digest is invalid");
+ const [algorithm, hex] = digest.split(":");
+ if (algorithm !== "sha256" || hex === undefined) throw new Error(`unsupported Artifact digest ${digest}`);
+ const normalized = normalizePrefix(prefix);
+ const relative = `${algorithm}/${hex.slice(0, 2)}/${hex}`;
+ return normalized.length === 0 ? relative : `${normalized}/${relative}`;
+}
+
type S3Location = {
readonly bucket: string;
readonly prefix?: string;
@@ -114,11 +130,7 @@ export class S3ArtifactStore implements ArtifactStore {
}
key(digest: Digest): string {
- if (!isDigest(digest)) throw new Error("Artifact digest is invalid");
- const [algorithm, hex] = digest.split(":");
- if (algorithm !== "sha256" || hex === undefined) throw new Error(`unsupported Artifact digest ${digest}`);
- const relative = `${algorithm}/${hex.slice(0, 2)}/${hex}`;
- return this.#prefix.length === 0 ? relative : `${this.#prefix}/${relative}`;
+ return s3ArtifactKey(this.#prefix, digest);
}
async put(bytes: Uint8Array, mediaType: string): Promise<BlobRef> {
diff --git a/packages/provider-media-aws-lambda/package.json b/packages/provider-media-aws-lambda/package.json
new file mode 100644
index 00000000..e504ea9d
--- /dev/null
+++ b/packages/provider-media-aws-lambda/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@narratage/provider-media-aws-lambda",
+ "version": "0.0.0-dev",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "svml": {
+ "activation": "./src/activation.ts"
+ },
+ "dependencies": {
+ "@narratage/endpoint-kit": "workspace:*",
+ "@narratage/media": "workspace:*",
+ "@narratage/media-execution": "workspace:*",
+ "@narratage/media-pipeline": "workspace:*",
+ "@narratage/protocol": "workspace:*",
+ "@narratage/runtime-adapter": "workspace:*",
+ "@narratage/speech": "workspace:*",
+ "@narratage/transport": "workspace:*",
+ "@narratage/transport-aws-lambda": "workspace:*"
+ },
+ "devDependencies": {
+ "@narratage/driver-node": "workspace:*"
+ }
+}
diff --git a/packages/provider-media-aws-lambda/src/activation.ts b/packages/provider-media-aws-lambda/src/activation.ts
new file mode 100644
index 00000000..f599d1fe
--- /dev/null
+++ b/packages/provider-media-aws-lambda/src/activation.ts
@@ -0,0 +1,73 @@
+import {
+ createRuntimeEndpointAdapterFacet,
+ runtimeConfigExact,
+ runtimeConfigObject,
+ runtimeConfigPositiveInteger,
+ runtimeConfigString,
+} from "@narratage/runtime-adapter";
+
+import { createAwsLambdaMediaProvider } from "./provider.js";
+
+const awsLambdaMediaRuntimeAdapter = createRuntimeEndpointAdapterFacet({
+ use: "@narratage/provider-media-aws-lambda",
+ create(context) {
+ const config = runtimeConfigObject(context.config, "AWS Lambda media");
+ runtimeConfigExact(config, [
+ "functionArn", "bucket", "prefix", "region", "defaultConcurrency",
+ ], "AWS Lambda media");
+ const functionArn = runtimeConfigString(config.functionArn, "AWS Lambda functionArn");
+ if (functionArn === undefined) throw new Error("AWS Lambda functionArn is required");
+ const bucket = runtimeConfigString(config.bucket, "AWS Lambda bucket");
+ if (bucket === undefined) {
+ throw new Error(
+ "AWS Lambda media bucket is required: the function reads sources and writes results in the"
+ + " ArtifactStore's own bucket, because a synchronous invocation cannot carry media",
+ );
+ }
+ return createAwsLambdaMediaProvider({
+ instance: context.instance,
+ ...(context.lane === undefined ? {} : { lane: context.lane }),
+ functionArn,
+ bucket,
+ ...(runtimeConfigString(config.prefix, "AWS Lambda prefix") === undefined
+ ? {} : { prefix: config.prefix as string }),
+ ...(runtimeConfigString(config.region, "AWS Lambda region") === undefined
+ ? {} : { region: config.region as string }),
+ ...(runtimeConfigPositiveInteger(config.defaultConcurrency, "AWS Lambda defaultConcurrency") === undefined
+ ? {} : { defaultConcurrency: config.defaultConcurrency as number }),
+ });
+ },
+ /**
+ * The ARN shape is checked without calling AWS, so `doctor` answers offline.
+ * Whether the function exists and which image it carries is a live question,
+ * asked by `narratage services status` against a configured deployment.
+ */
+ doctor(context) {
+ const config = runtimeConfigObject(context.config, "AWS Lambda media");
+ const functionArn = runtimeConfigString(config.functionArn, "AWS Lambda functionArn");
+ if (functionArn === undefined) return [];
+ try {
+ createAwsLambdaMediaProvider({
+ functionArn,
+ bucket: runtimeConfigString(config.bucket, "AWS Lambda bucket") ?? "unset",
+ invoker: { invoke: async () => ({}) },
+ });
+ return [];
+ } catch (error) {
+ return [{
+ severity: "error" as const,
+ code: "ENDPOINT_TARGET_INVALID",
+ message: error instanceof Error ? error.message : String(error),
+ subject: context.instance,
+ }];
+ }
+ },
+});
+
+export const svmlPackage = {
+ format: "svml.node-package@1" as const,
+ name: "@narratage/provider-media-aws-lambda",
+ hostFacets: [awsLambdaMediaRuntimeAdapter],
+};
+
+export default svmlPackage;
diff --git a/packages/provider-media-aws-lambda/src/contract.ts b/packages/provider-media-aws-lambda/src/contract.ts
new file mode 100644
index 00000000..689b6fc5
--- /dev/null
+++ b/packages/provider-media-aws-lambda/src/contract.ts
@@ -0,0 +1,142 @@
+import { canonicalize } from "@narratage/protocol";
+import type { CanonicalValue } from "@narratage/protocol";
+
+/**
+ * The envelope between the Endpoint and the function it invokes.
+ *
+ * Both sides parse it. The Endpoint parses because a function is a deployed
+ * artifact that may be older than the caller; the function parses because an
+ * invocation is an untrusted input even when the account is trusted. Neither
+ * side treats the other's output as already valid.
+ */
+export const MEDIA_LAMBDA_REQUEST = "svml.media-lambda-request@1";
+export const MEDIA_LAMBDA_RESPONSE = "svml.media-lambda-response@1";
+
+export const mediaLambdaOperations = [
+ "inspect",
+ "normalize",
+ "project-speech-evidence-audio",
+ "render-audio",
+ "mux",
+] as const;
+
+export type MediaLambdaOperation = (typeof mediaLambdaOperations)[number];
+
+/**
+ * The bucket the function reads sources from and writes results to.
+ *
+ * A synchronous invocation carries at most a few megabytes, so media never
+ * travels in the payload — only the location it already occupies. This is why
+ * the AWS media Provider requires an S3 ArtifactStore rather than merely
+ * preferring one.
+ */
+export type MediaLambdaArtifactLocation = {
+ readonly bucket: string;
+ readonly prefix?: string;
+};
+
+export type MediaLambdaRequest = {
+ readonly contract: typeof MEDIA_LAMBDA_REQUEST;
+ readonly operation: MediaLambdaOperation;
+ readonly artifacts: MediaLambdaArtifactLocation;
+ /** The Need's constraints, verbatim. The function validates them itself. */
+ readonly constraints: CanonicalValue;
+};
+
+export type MediaLambdaResponse =
+ | {
+ readonly contract: typeof MEDIA_LAMBDA_RESPONSE;
+ readonly operation: MediaLambdaOperation;
+ readonly ok: true;
+ readonly value: CanonicalValue;
+ readonly metadata: CanonicalValue;
+ }
+ | {
+ readonly contract: typeof MEDIA_LAMBDA_RESPONSE;
+ readonly operation: MediaLambdaOperation;
+ readonly ok: false;
+ readonly code: string;
+ readonly message: string;
+ };
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+function object(value: unknown, subject: string): Record<string, unknown> {
+ assert(value !== null && typeof value === "object" && !Array.isArray(value), `${subject} must be an object`);
+ return value as Record<string, unknown>;
+}
+
+function nonEmptyString(value: unknown, subject: string): string {
+ assert(typeof value === "string" && value.trim().length > 0, `${subject} must be a non-empty string`);
+ return value;
+}
+
+function operation(value: unknown, subject: string): MediaLambdaOperation {
+ assert(typeof value === "string" && (mediaLambdaOperations as readonly string[]).includes(value),
+ `${subject} must be one of ${mediaLambdaOperations.join(", ")}`);
+ return value as MediaLambdaOperation;
+}
+
+export function sealMediaLambdaRequest(request: MediaLambdaRequest): CanonicalValue {
+ parseMediaLambdaRequest(request);
+ return canonicalize(request as unknown as CanonicalValue);
+}
+
+/** Used by the function on every invocation. */
+export function parseMediaLambdaRequest(value: unknown): MediaLambdaRequest {
+ const item = object(value, "MediaLambdaRequest");
+ assert(item.contract === MEDIA_LAMBDA_REQUEST,
+ `MediaLambdaRequest contract must be ${MEDIA_LAMBDA_REQUEST}`);
+ const artifacts = object(item.artifacts, "MediaLambdaRequest.artifacts");
+ const prefix = artifacts.prefix;
+ assert(prefix === undefined || typeof prefix === "string",
+ "MediaLambdaRequest.artifacts.prefix must be a string when present");
+ assert(item.constraints !== null && typeof item.constraints === "object",
+ "MediaLambdaRequest.constraints must be an object");
+ return {
+ contract: MEDIA_LAMBDA_REQUEST,
+ operation: operation(item.operation, "MediaLambdaRequest.operation"),
+ artifacts: {
+ bucket: nonEmptyString(artifacts.bucket, "MediaLambdaRequest.artifacts.bucket"),
+ ...(prefix === undefined || prefix.length === 0 ? {} : { prefix }),
+ },
+ constraints: item.constraints as CanonicalValue,
+ };
+}
+
+/**
+ * Used by the Endpoint on every reply.
+ *
+ * Failures arrive here rather than as a Lambda FunctionError, because the
+ * transport deliberately refuses to copy a failed function's payload into its
+ * error — that payload may carry deployment detail. A function that only threw
+ * would reach the Endpoint as the word "Unhandled".
+ */
+export function parseMediaLambdaResponse(value: unknown): MediaLambdaResponse {
+ const item = object(value, "MediaLambdaResponse");
+ assert(item.contract === MEDIA_LAMBDA_RESPONSE,
+ `MediaLambdaResponse contract must be ${MEDIA_LAMBDA_RESPONSE}`);
+ const named = operation(item.operation, "MediaLambdaResponse.operation");
+ if (item.ok === false) {
+ return {
+ contract: MEDIA_LAMBDA_RESPONSE,
+ operation: named,
+ ok: false,
+ code: nonEmptyString(item.code, "MediaLambdaResponse.code"),
+ message: nonEmptyString(item.message, "MediaLambdaResponse.message"),
+ };
+ }
+ assert(item.ok === true, "MediaLambdaResponse.ok must be a boolean");
+ assert(item.value !== null && typeof item.value === "object", "MediaLambdaResponse.value must be an object");
+ assert(item.metadata !== null && typeof item.metadata === "object",
+ "MediaLambdaResponse.metadata must be an object");
+ return {
+ contract: MEDIA_LAMBDA_RESPONSE,
+ operation: named,
+ ok: true,
+ value: item.value as CanonicalValue,
+ metadata: item.metadata as CanonicalValue,
+ };
+}
diff --git a/packages/provider-media-aws-lambda/src/index.ts b/packages/provider-media-aws-lambda/src/index.ts
new file mode 100644
index 00000000..a9274244
--- /dev/null
+++ b/packages/provider-media-aws-lambda/src/index.ts
@@ -0,0 +1,15 @@
+export {
+ awsLambdaMediaProviderImplementationDigest,
+ awsLambdaMediaProviderModuleRef,
+ createAwsLambdaMediaProvider,
+} from "./provider.js";
+export {
+ MEDIA_LAMBDA_REQUEST,
+ MEDIA_LAMBDA_RESPONSE,
+ mediaLambdaOperations,
+ parseMediaLambdaRequest,
+ parseMediaLambdaResponse,
+ sealMediaLambdaRequest,
+} from "./contract.js";
+export type * from "./contract.js";
+export type { CreateAwsLambdaMediaProviderOptions } from "./provider.js";
diff --git a/packages/provider-media-aws-lambda/src/provider.ts b/packages/provider-media-aws-lambda/src/provider.ts
new file mode 100644
index 00000000..e6877900
--- /dev/null
+++ b/packages/provider-media-aws-lambda/src/provider.ts
@@ -0,0 +1,169 @@
+import { mediaTypes } from "@narratage/media";
+import { mediaNeedHasContract, mediaOperationContracts } from "@narratage/media-execution";
+import { mediaPipelineCapabilities } from "@narratage/media-pipeline";
+import { canonicalize, digestOf } from "@narratage/protocol";
+import type { BlobRef, CanonicalValue } from "@narratage/protocol";
+import { speechTypes } from "@narratage/speech";
+import { defineEndpointPackage } from "@narratage/endpoint-kit";
+import type { EndpointFulfillment, EndpointInvocationContext } from "@narratage/endpoint-kit";
+import { AwsLambdaJsonInvoker } from "@narratage/transport-aws-lambda";
+import type { JsonInvoker } from "@narratage/transport";
+
+import {
+ MEDIA_LAMBDA_REQUEST,
+ parseMediaLambdaResponse,
+ sealMediaLambdaRequest,
+} from "./contract.js";
+import type { MediaLambdaOperation } from "./contract.js";
+
+export const awsLambdaMediaProviderModuleRef = {
+ name: "@narratage/provider-media-aws-lambda",
+ version: "0.0.0-dev",
+} as const;
+export const awsLambdaMediaProviderImplementationDigest =
+ digestOf("@narratage/provider-media-aws-lambda/media@1");
+
+/** `arn:aws:lambda:<region>:<account>:function:<name>:<version|alias>` */
+const QUALIFIED_ARN =
+ /^arn:aws:lambda:([a-z0-9-]+):\d{12}:function:[A-Za-z0-9-_]+:(\$LATEST|[A-Za-z0-9-_]+)$/u;
+
+export type CreateAwsLambdaMediaProviderOptions = {
+ readonly instance?: string;
+ readonly lane?: string;
+ /** Must name a version or alias. See the assertion below for why. */
+ readonly functionArn: string;
+ readonly bucket: string;
+ readonly prefix?: string;
+ readonly region?: string;
+ readonly defaultConcurrency?: number;
+ /** Injection point for tests and specially configured trusted AWS clients. */
+ readonly invoker?: JsonInvoker;
+};
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+function isBlobRef(value: unknown): value is BlobRef {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ && (value as Record<string, unknown>).kind === "blob"
+ && typeof (value as Record<string, unknown>).digest === "string";
+}
+
+/** Every Artifact the function claims to have written, at any depth of the result. */
+function producedArtifacts(value: unknown, found: BlobRef[] = []): readonly BlobRef[] {
+ if (isBlobRef(value)) found.push(value);
+ else if (Array.isArray(value)) for (const item of value) producedArtifacts(item, found);
+ else if (value !== null && typeof value === "object") {
+ for (const item of Object.values(value)) producedArtifacts(item, found);
+ }
+ return found;
+}
+
+export function createAwsLambdaMediaProvider(config: CreateAwsLambdaMediaProviderOptions) {
+ // A function name without a version is whatever was deployed most recently.
+ // Two Builds of one Run Source could then be executed by different code while
+ // recording the same Endpoint identity, which is the one thing a BuildPlan
+ // must never allow.
+ const arn = QUALIFIED_ARN.exec(config.functionArn);
+ assert(arn !== null,
+ `Lambda functionArn must name a version or alias, as arn:aws:lambda:<region>:<account>:function:<name>:<version>; got ${config.functionArn}`);
+ const region = config.region ?? arn[1]!;
+ assert(region === arn[1],
+ `Lambda region ${region} differs from the region in its ARN (${arn[1]})`);
+ assert(config.bucket.trim().length > 0, "Lambda media Provider requires the ArtifactStore bucket");
+
+ const configuration = {
+ functionArn: config.functionArn,
+ region,
+ bucket: config.bucket,
+ ...(config.prefix === undefined || config.prefix.length === 0 ? {} : { prefix: config.prefix }),
+ };
+ const invoker = config.invoker ?? new AwsLambdaJsonInvoker({
+ functionName: config.functionArn,
+ region,
+ });
+
+ const operation = (name: MediaLambdaOperation) =>
+ async (context: EndpointInvocationContext): Promise<EndpointFulfillment> => {
+ const reply = parseMediaLambdaResponse(await invoker.invoke(sealMediaLambdaRequest({
+ contract: MEDIA_LAMBDA_REQUEST,
+ operation: name,
+ artifacts: {
+ bucket: config.bucket,
+ ...(config.prefix === undefined || config.prefix.length === 0 ? {} : { prefix: config.prefix }),
+ },
+ constraints: context.need.constraints,
+ })));
+ if (!reply.ok) throw new Error(`AWS media ${name} failed (${reply.code}): ${reply.message}`);
+
+ // The function wrote its results straight into the bucket, so nothing was
+ // uploaded here. Reading each one back through this Build's own
+ // ArtifactStore is what proves the two were ever pointed at the same
+ // place: a Provider configured against a different bucket fails here,
+ // naming the Artifact, instead of yielding a Record that cannot be read.
+ for (const artifact of producedArtifacts(reply.value)) {
+ assert(await context.artifacts.has(artifact.digest),
+ `AWS media ${name} reported Artifact ${artifact.digest}, which this Build's ArtifactStore cannot read`
+ + ` — the Provider's bucket and the ArtifactStore's bucket are probably not the same`);
+ }
+ return {
+ value: { kind: "inline", value: reply.value },
+ conformance: "exact",
+ delivery: "executed",
+ metadata: reply.metadata,
+ };
+ };
+
+ return defineEndpointPackage({
+ module: awsLambdaMediaProviderModuleRef,
+ facet: "media",
+ instance: config.instance ?? "media.aws-lambda",
+ ...(config.lane === undefined ? {} : { lane: config.lane }),
+ implementation: {
+ locator: "@narratage/provider-media-aws-lambda/media",
+ digest: awsLambdaMediaProviderImplementationDigest,
+ },
+ permissions: ["network:aws:lambda", "network:aws:s3"],
+ configuration: canonicalize(configuration as unknown as CanonicalValue),
+ defaultConcurrency: config.defaultConcurrency ?? 8,
+ capabilities: [
+ {
+ lifecycle: "immediate" as const,
+ capability: mediaPipelineCapabilities.inspect,
+ returns: mediaTypes.inspection,
+ supports: (need) => mediaNeedHasContract(need.constraints, mediaOperationContracts.inspect),
+ handler: operation("inspect"),
+ },
+ {
+ lifecycle: "immediate" as const,
+ capability: mediaPipelineCapabilities.normalize,
+ returns: mediaTypes.synchronized,
+ supports: (need) => mediaNeedHasContract(need.constraints, mediaOperationContracts.normalize),
+ handler: operation("normalize"),
+ },
+ {
+ lifecycle: "immediate" as const,
+ capability: mediaPipelineCapabilities.projectSpeechEvidenceAudio,
+ returns: speechTypes.evidenceAudio,
+ supports: (need) =>
+ mediaNeedHasContract(need.constraints, mediaOperationContracts.projectSpeechEvidenceAudio),
+ handler: operation("project-speech-evidence-audio"),
+ },
+ {
+ lifecycle: "immediate" as const,
+ capability: mediaPipelineCapabilities.renderAudio,
+ returns: mediaTypes.timelineAudio,
+ supports: (need) => mediaNeedHasContract(need.constraints, mediaOperationContracts.renderAudio),
+ handler: operation("render-audio"),
+ },
+ {
+ lifecycle: "immediate" as const,
+ capability: mediaPipelineCapabilities.mux,
+ returns: mediaTypes.muxed,
+ supports: (need) => mediaNeedHasContract(need.constraints, mediaOperationContracts.mux),
+ handler: operation("mux"),
+ },
+ ],
+ });
+}
diff --git a/packages/provider-media-aws-lambda/test/provider.test.ts b/packages/provider-media-aws-lambda/test/provider.test.ts
new file mode 100644
index 00000000..1cd8cf3d
--- /dev/null
+++ b/packages/provider-media-aws-lambda/test/provider.test.ts
@@ -0,0 +1,151 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { MemoryArtifactStore } from "@narratage/driver-node";
+import { canonicalize, digestOf } from "@narratage/protocol";
+import type { CanonicalValue } from "@narratage/protocol";
+import type { ImmediateEndpointHandler } from "@narratage/endpoint-kit";
+import type { JsonInvoker } from "@narratage/transport";
+
+import {
+ createAwsLambdaMediaProvider,
+ parseMediaLambdaRequest,
+ parseMediaLambdaResponse,
+} from "@narratage/provider-media-aws-lambda";
+
+const ARN = "arn:aws:lambda:us-east-1:123456789012:function:narratage-media:7";
+
+function recordingInvoker(reply: (request: CanonicalValue) => CanonicalValue) {
+ const seen: CanonicalValue[] = [];
+ const invoker: JsonInvoker = {
+ invoke: async (request) => {
+ seen.push(request);
+ return reply(request);
+ },
+ };
+ return { invoker, seen };
+}
+
+const inspectNeed = {
+ contract: "svml.inspect-media-request@1",
+ source: { kind: "blob", digest: digestOf("source"), size: 4, mediaType: "video/mp4" },
+} as unknown as CanonicalValue;
+
+/** Installs the Provider into a registrar that keeps the handlers, as the Runtime does. */
+async function endpointFor(invoker: JsonInvoker, options: { bucket?: string } = {}) {
+ const provider = createAwsLambdaMediaProvider({
+ functionArn: ARN,
+ bucket: options.bucket ?? "team-artifacts",
+ prefix: "svml",
+ invoker,
+ });
+ const handlers = new Map<string, ImmediateEndpointHandler>();
+ await provider.install({
+ registerImmediateEndpoint: (
+ _id: string,
+ capability: { name: string },
+ _returns: unknown,
+ handler: ImmediateEndpointHandler,
+ ) => {
+ handlers.set(capability.name, handler);
+ },
+ registerRecoverableEndpoint: () => {
+ throw new Error("the AWS media Provider registers no recoverable endpoint");
+ },
+ } as never);
+ const handler = handlers.get("inspect-media");
+ assert.ok(handler, "the Provider offers media inspection");
+ return { handler };
+}
+
+test("an unqualified function ARN is refused, because two Builds could then run different code", () => {
+ assert.throws(
+ () => createAwsLambdaMediaProvider({
+ functionArn: "arn:aws:lambda:us-east-1:123456789012:function:narratage-media",
+ bucket: "team-artifacts",
+ }),
+ /must name a version or alias/u,
+ );
+ assert.throws(
+ () => createAwsLambdaMediaProvider({ functionArn: ARN, bucket: "team-artifacts", region: "eu-west-1" }),
+ /differs from the region in its ARN/u,
+ );
+});
+
+test("the Provider sends the Need verbatim with the bucket the function should use", async () => {
+ const store = new MemoryArtifactStore();
+ const artifact = await store.put(new TextEncoder().encode("out!"), "video/mp4");
+ const { invoker, seen } = recordingInvoker(() => canonicalize({
+ contract: "svml.media-lambda-response@1",
+ operation: "inspect",
+ ok: true,
+ value: { contract: "svml.media-inspection@1", artifact },
+ metadata: { provider: "media.aws-lambda" },
+ } as unknown as CanonicalValue));
+
+ const capability = await endpointFor(invoker);
+ const outcome = await capability.handler({
+ need: { constraints: inspectNeed },
+ artifacts: store,
+ credentials: {},
+ } as never);
+
+ const request = parseMediaLambdaRequest(seen[0]);
+ assert.equal(request.operation, "inspect");
+ assert.deepEqual(request.artifacts, { bucket: "team-artifacts", prefix: "svml" });
+ assert.deepEqual(request.constraints, canonicalize(inspectNeed));
+ assert.equal((outcome as { conformance: string }).conformance, "exact");
+});
+
+test("a Provider aimed at another bucket fails naming the Artifact, not later with an unreadable Record", async () => {
+ const store = new MemoryArtifactStore();
+ const stranger = digestOf("an artifact this Build's store never received");
+ const { invoker } = recordingInvoker(() => canonicalize({
+ contract: "svml.media-lambda-response@1",
+ operation: "inspect",
+ ok: true,
+ value: {
+ contract: "svml.media-inspection@1",
+ artifact: { kind: "blob", digest: stranger, size: 1, mediaType: "video/mp4" },
+ },
+ metadata: {},
+ } as unknown as CanonicalValue));
+
+ await assert.rejects(
+ async () => await (await endpointFor(invoker)).handler({
+ need: { constraints: inspectNeed }, artifacts: store, credentials: {},
+ } as never),
+ (error: Error) => {
+ assert.match(error.message, new RegExp(stranger, "u"));
+ assert.match(error.message, /bucket and the ArtifactStore's bucket are probably not the same/u);
+ return true;
+ },
+ );
+});
+
+test("a typed failure reaches the Build with its code, since the transport withholds the payload", async () => {
+ const { invoker } = recordingInvoker(() => canonicalize({
+ contract: "svml.media-lambda-response@1",
+ operation: "inspect",
+ ok: false,
+ code: "MEDIA_SOURCE_UNAVAILABLE",
+ message: "source sha256:… is absent from bucket team-artifacts",
+ } as unknown as CanonicalValue));
+
+ await assert.rejects(
+ async () => await (await endpointFor(invoker)).handler({
+ need: { constraints: inspectNeed }, artifacts: new MemoryArtifactStore(), credentials: {},
+ } as never),
+ /MEDIA_SOURCE_UNAVAILABLE.*absent from bucket/su,
+ );
+});
+
+test("a reply that is not this contract is refused rather than half-read", () => {
+ assert.throws(() => parseMediaLambdaResponse({ contract: "svml.media-lambda-response@0", operation: "inspect" }),
+ /contract must be svml\.media-lambda-response@1/u);
+ assert.throws(() => parseMediaLambdaResponse({ contract: "svml.media-lambda-response@1", operation: "transcode" }),
+ /operation must be one of/u);
+ assert.throws(() => parseMediaLambdaRequest({
+ contract: "svml.media-lambda-request@1", operation: "mux", artifacts: {}, constraints: {},
+ }), /artifacts\.bucket must be a non-empty string/u);
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 25a275fb..198ca5bb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1067,6 +1067,40 @@ importers:
specifier: workspace:*
version: link:../validation
+ packages/provider-media-aws-lambda:
+ dependencies:
+ '@narratage/endpoint-kit':
+ specifier: workspace:*
+ version: link:../endpoint-kit
+ '@narratage/media':
+ specifier: workspace:*
+ version: link:../media
+ '@narratage/media-execution':
+ specifier: workspace:*
+ version: link:../media-execution
+ '@narratage/media-pipeline':
+ specifier: workspace:*
+ version: link:../media-pipeline
+ '@narratage/protocol':
+ specifier: workspace:*
+ version: link:../protocol
+ '@narratage/runtime-adapter':
+ specifier: workspace:*
+ version: link:../runtime-adapter
+ '@narratage/speech':
+ specifier: workspace:*
+ version: link:../speech
+ '@narratage/transport':
+ specifier: workspace:*
+ version: link:../transport
+ '@narratage/transport-aws-lambda':
+ specifier: workspace:*
+ version: link:../transport-aws-lambda
+ devDependencies:
+ '@narratage/driver-node':
+ specifier: workspace:*
+ version: link:../driver-node
+
packages/provider-media-local:
dependencies:
'@narratage/endpoint-kit':
diff --git a/tsconfig.json b/tsconfig.json
index 4132a108..4ec9a164 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -145,6 +145,7 @@
"@narratage/media-pipeline": [
"packages/media-pipeline/src/index.ts"
],
+ "@narratage/provider-media-aws-lambda": ["packages/provider-media-aws-lambda/src/index.ts"],
"@narratage/provider-media-local": [
"packages/provider-media-local/src/index.ts"
],