Skip to content

Commit 5af76b2

Browse files
committed
perf(aws-lambda): small-chunk cloud renders stitch their output in parallel
When every chunk's payload is under S3's 5 MiB part minimum (typical for short 4K chunks), the assemble step could not copy any part server-side and pulled the whole output through one Lambda's network link. Those range-only parts now go to parallel invocations of the warm function that just rendered the chunks, about 32 MiB each and never more at once than the stack's reserved concurrency allows. The output bytes are unchanged.
1 parent 4f0bdfb commit 5af76b2

9 files changed

Lines changed: 416 additions & 28 deletions

File tree

‎examples/aws-lambda/template.yaml‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,9 +170,21 @@ Resources:
170170
TMPDIR: /tmp
171171
HYPERFRAMES_RENDER_BUCKET: !Ref RenderBucket
172172
HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY: !Ref ReservedConcurrency
173+
# Assemble spreads the parts S3 cannot copy across the warm function that ran the chunks.
174+
HYPERFRAMES_STITCH_FUNCTION: !If
175+
- HasVideoFunction
176+
- !Sub "${ProjectName}-video"
177+
- !Sub "${ProjectName}-render"
173178
Policies:
174179
- S3CrudPolicy:
175180
BucketName: !Ref RenderBucket
181+
- Statement:
182+
- Effect: Allow
183+
Action: lambda:InvokeFunction
184+
Resource: !If
185+
- HasVideoFunction
186+
- !Sub "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${ProjectName}-video"
187+
- !Sub "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${ProjectName}-render"
176188
- Statement:
177189
- Effect: Allow
178190
Action: s3:AbortMultipartUpload

‎examples/aws-lambda/video-function.yaml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ Resources:
6262
- Effect: Allow
6363
Action: lambda:GetAccountSettings
6464
Resource: "*"
65+
# Stitch helpers, should this function ever run an assemble.
66+
- Effect: Allow
67+
Action: lambda:InvokeFunction
68+
Resource: !Sub "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${ProjectName}-video"
6569
Tags:
6670
- Key: Project
6771
Value: !Ref ProjectName
@@ -95,6 +99,7 @@ Resources:
9599
TMPDIR: /tmp
96100
HYPERFRAMES_RENDER_BUCKET: !Ref RenderBucket
97101
HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY: !Ref ReservedConcurrency
102+
HYPERFRAMES_STITCH_FUNCTION: !Sub "${ProjectName}-video"
98103
Tags:
99104
- Key: Project
100105
Value: !Ref ProjectName

‎packages/aws-lambda/src/cdk/HyperframesRenderStack.snapshot.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,40 @@ describe("HyperframesRenderStack — snapshot", () => {
493493
expect(samActions).toContain("lambda:GetAccountSettings");
494494
}, 30000);
495495

496+
it("lets assemble invoke exactly the stitch helper it names, in CDK and SAM", () => {
497+
const cdkFunction = Object.values(
498+
SYNTHED.template.findResources("AWS::Lambda::Function"),
499+
)[0] as {
500+
Properties: { Environment: { Variables: Record<string, unknown> } };
501+
};
502+
expect(cdkFunction.Properties.Environment.Variables.HYPERFRAMES_STITCH_FUNCTION).toBe(
503+
"hyperframes-render",
504+
);
505+
const cdkInvoke = Object.values(SYNTHED.template.findResources("AWS::IAM::Policy"))
506+
.flatMap(policyStatements)
507+
.filter((statement) => statement.Action === "lambda:InvokeFunction");
508+
expect(JSON.stringify(cdkInvoke.map((s) => s.Resource))).toContain(
509+
":function:hyperframes-render",
510+
);
511+
512+
const samFunction = requireRecordProperty(
513+
requireRecordProperty(readSamResources(), "RenderFunction", "SAM RenderFunction"),
514+
"Properties",
515+
"SAM function properties",
516+
) as { Environment: { Variables: Record<string, unknown> }; Policies: unknown[] };
517+
// The YAML parser drops the !If and !Sub tags and keeps [condition, then, else].
518+
const [, withVideo, without] = samFunction.Environment.Variables
519+
.HYPERFRAMES_STITCH_FUNCTION as string[];
520+
expect([withVideo, without]).toEqual(["${ProjectName}-video", "${ProjectName}-render"]);
521+
const samInvoke = samFunction.Policies.flatMap(
522+
(policy) => (policy as { Statement?: Record<string, unknown>[] }).Statement ?? [],
523+
).filter((statement) => statement.Action === "lambda:InvokeFunction");
524+
expect(samInvoke).toHaveLength(1);
525+
const [, grantWithVideo, grantWithout] = samInvoke[0]!.Resource as string[];
526+
expect(grantWithVideo!.endsWith(`:function:${withVideo}`)).toBe(true);
527+
expect(grantWithout!.endsWith(`:function:${without}`)).toBe(true);
528+
}, 30000);
529+
496530
it("fails at once when a chunk cannot fit the worker timeout, in CDK and SAM", () => {
497531
for (const definition of [SYNTHED.definition, readSamDefinition()]) {
498532
for (const name of ["Plan", "PlanV2"]) {

‎packages/aws-lambda/src/cdk/HyperframesRenderStack.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
import { dirname, resolve } from "node:path";
2323
import { fileURLToPath } from "node:url";
24-
import { Duration, RemovalPolicy, Size } from "aws-cdk-lib";
24+
import { ArnFormat, Duration, RemovalPolicy, Size, Stack } from "aws-cdk-lib";
2525
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
2626
import * as iam from "aws-cdk-lib/aws-iam";
2727
import * as lambda from "aws-cdk-lib/aws-lambda";
@@ -120,6 +120,8 @@ export class HyperframesRenderStack extends Construct {
120120
HYPERFRAMES_LAMBDA_CHROME_SOURCE: chromeSource,
121121
HYPERFRAMES_RENDER_BUCKET: this.bucket.bucketName,
122122
HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY: String(props.reservedConcurrency ?? -1),
123+
// Assemble spreads the parts S3 cannot copy across this function's warm chunk containers.
124+
HYPERFRAMES_STITCH_FUNCTION: `${projectName}-render`,
123125
},
124126
});
125127

@@ -131,6 +133,20 @@ export class HyperframesRenderStack extends Construct {
131133
this.renderFunction.addToRolePolicy(
132134
new iam.PolicyStatement({ actions: ["lambda:GetAccountSettings"], resources: ["*"] }),
133135
);
136+
// By name, not `grantInvoke(this.renderFunction)`, which would make the role depend on its own function.
137+
this.renderFunction.addToRolePolicy(
138+
new iam.PolicyStatement({
139+
actions: ["lambda:InvokeFunction"],
140+
resources: [
141+
Stack.of(this).formatArn({
142+
service: "lambda",
143+
resource: "function",
144+
resourceName: `${projectName}-render`,
145+
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
146+
}),
147+
],
148+
}),
149+
);
134150

135151
const stateMachineLogGroup = new logs.LogGroup(this, "RenderStateMachineLogGroup", {
136152
logGroupName: `/aws/states/${projectName}-render`,

‎packages/aws-lambda/src/events.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,14 @@ export type LambdaAction = "plan" | "audio" | "renderChunk" | "assemble";
2828
export interface WarmEvent {
2929
Action: "warm";
3030
}
31+
/** Assemble hands a helper part of the final mp4's multipart upload: each part's S3 ranges, in order. */
32+
export interface StitchPartsEvent {
33+
Action: "stitchParts";
34+
Bucket: string;
35+
Key: string;
36+
UploadId: string;
37+
Parts: { partNumber: number; ranges: { uri: string; start: number; end: number }[] }[];
38+
}
3139
/** Transport protocol selected for one complete distributed render. */
3240
export type LambdaPlanProtocol = "v1" | "v2";
3341

@@ -45,6 +53,7 @@ export type LambdaEvent =
4553
| RenderChunkEvent
4654
| AssembleEvent
4755
| WarmEvent
56+
| StitchPartsEvent
4857
| { Payload: LambdaEvent }
4958
| { Input: LambdaEvent };
5059

@@ -239,8 +248,14 @@ export interface WarmLambdaResult {
239248
Action: "warm";
240249
}
241250

251+
export interface StitchPartsLambdaResult {
252+
Action: "stitchParts";
253+
ETags: string[];
254+
}
255+
242256
export type LambdaResult =
243257
| WarmLambdaResult
258+
| StitchPartsLambdaResult
244259
| PlanLambdaResult
245260
| AudioLambdaResult
246261
| RenderChunkLambdaResult

‎packages/aws-lambda/src/handler.test.ts‎

Lines changed: 99 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,14 @@ import {
3838
} from "@hyperframes/producer/distributed";
3939
import { resolveMaxParallelChunks } from "../../producer/src/services/distributed/plan.js";
4040
import { recomputePlanHashFromPlanDir } from "../../producer/src/services/render/stages/freezePlan.js";
41-
import type { AssembleEvent, LambdaEvent, PlanEvent, RenderChunkEvent } from "./events.js";
42-
import { handler as handleEvent, unwrapEvent } from "./handler.js";
41+
import type {
42+
AssembleEvent,
43+
LambdaEvent,
44+
PlanEvent,
45+
RenderChunkEvent,
46+
StitchPartsEvent,
47+
} from "./events.js";
48+
import { handler as handleEvent, stitchHelper, unwrapEvent } from "./handler.js";
4349
import { S3PlanV2ArtifactPublisher } from "./s3PlanV2Publisher.js";
4450

4551
interface FakeS3Op {
@@ -1626,6 +1632,97 @@ describe("handler — S3 URI allowlist (security: F-004)", () => {
16261632
await expect(handler(event, deps)).rejects.toMatchObject({ name: "S3_URI_NOT_ALLOWED" });
16271633
expect(s3.ops).toHaveLength(0);
16281634
});
1635+
1636+
it("rejects a stitchParts range outside the allowed bucket", async () => {
1637+
process.env.HYPERFRAMES_RENDER_BUCKET = "good-bucket";
1638+
const s3 = new FakeS3Client();
1639+
const event: StitchPartsEvent = {
1640+
Action: "stitchParts",
1641+
Bucket: "good-bucket",
1642+
Key: "renders/abc/output.mp4",
1643+
UploadId: "upload-1",
1644+
Parts: [{ partNumber: 2, ranges: [{ uri: "s3://evil-bucket/secret", start: 0, end: 4 }] }],
1645+
};
1646+
await expect(
1647+
handler(event, { s3: s3 as unknown as S3Client, skipChromeResolution: true }),
1648+
).rejects.toMatchObject({ name: "S3_URI_NOT_ALLOWED" });
1649+
expect(s3.ops).toHaveLength(0);
1650+
});
1651+
});
1652+
1653+
describe("handler — stitch helpers", () => {
1654+
const event = (uri: string): StitchPartsEvent => ({
1655+
Action: "stitchParts",
1656+
Bucket: "bucket",
1657+
Key: "renders/abc/output.mp4",
1658+
UploadId: "upload-1",
1659+
Parts: [
1660+
{ partNumber: 3, ranges: [{ uri, start: 1, end: 4 }] },
1661+
{
1662+
partNumber: 4,
1663+
ranges: [
1664+
{ uri, start: 0, end: 2 },
1665+
{ uri, start: 4, end: 6 },
1666+
],
1667+
},
1668+
],
1669+
});
1670+
1671+
it("builds the parts a stitchParts call names and returns their ETags in order", async () => {
1672+
const s3 = new FakeS3Client();
1673+
s3.objects.set("s3://bucket/chunks/0.mp4", Buffer.from("abcdef"));
1674+
const result = await handler(event("s3://bucket/chunks/0.mp4"), {
1675+
s3: s3 as unknown as S3Client,
1676+
skipChromeResolution: true,
1677+
});
1678+
expect(result).toEqual({ Action: "stitchParts", ETags: ['"part-3"', '"part-4"'] });
1679+
expect([s3.parts.get(3)?.toString(), s3.parts.get(4)?.toString()]).toEqual(["bcd", "abef"]);
1680+
});
1681+
1682+
it("the stitch helper invokes the function the stack names and fails with its error", async () => {
1683+
const prev = process.env.HYPERFRAMES_STITCH_FUNCTION;
1684+
const prevReserved = process.env.HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY;
1685+
delete process.env.HYPERFRAMES_STITCH_FUNCTION;
1686+
expect(stitchHelper()).toBeUndefined();
1687+
process.env.HYPERFRAMES_STITCH_FUNCTION = "proj-video";
1688+
try {
1689+
// A reservation of 8 leaves 7 slots once this assemble holds one.
1690+
process.env.HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY = "8";
1691+
expect(stitchHelper()!.maxInvocations).toBe(7);
1692+
process.env.HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY = "-1";
1693+
expect(stitchHelper()!.maxInvocations).toBe(Infinity);
1694+
const s3 = new FakeS3Client();
1695+
s3.objects.set("s3://bucket/chunks/0.mp4", Buffer.from("abcdef"));
1696+
const invoked: string[] = [];
1697+
const lambda = {
1698+
send: async (command: { input: { FunctionName: string; Payload: string } }) => {
1699+
invoked.push(command.input.FunctionName);
1700+
const sent = JSON.parse(command.input.Payload) as StitchPartsEvent;
1701+
if (sent.Parts[0]!.ranges[0]!.uri.endsWith("missing")) {
1702+
const payload = JSON.stringify({ errorMessage: "NoSuchKey" });
1703+
return { FunctionError: "Unhandled", Payload: new TextEncoder().encode(payload) };
1704+
}
1705+
const out = await handler(sent, { s3: s3 as unknown as S3Client });
1706+
return { Payload: new TextEncoder().encode(JSON.stringify(out)) };
1707+
},
1708+
} as unknown as LambdaClient;
1709+
const { send } = stitchHelper(lambda)!;
1710+
const target = { Bucket: "bucket", Key: "renders/abc/output.mp4", UploadId: "upload-1" };
1711+
expect(await send(target, event("s3://bucket/chunks/0.mp4").Parts)).toEqual([
1712+
'"part-3"',
1713+
'"part-4"',
1714+
]);
1715+
await expect(send(target, event("s3://bucket/missing").Parts)).rejects.toThrow(
1716+
"stitchParts on proj-video failed: NoSuchKey",
1717+
);
1718+
expect(invoked).toEqual(["proj-video", "proj-video"]);
1719+
} finally {
1720+
if (prev === undefined) delete process.env.HYPERFRAMES_STITCH_FUNCTION;
1721+
else process.env.HYPERFRAMES_STITCH_FUNCTION = prev;
1722+
if (prevReserved === undefined) delete process.env.HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY;
1723+
else process.env.HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY = prevReserved;
1724+
}
1725+
});
16291726
});
16301727

16311728
// ── helpers ─────────────────────────────────────────────────────────────────

0 commit comments

Comments
 (0)