Skip to content

Commit c07e88f

Browse files
committed
fix(aws-lambda): a throttled stitch helper builds its parts in the assemble instead
Another render can hold the stack's reserved concurrency while this one assembles, so a helper invocation may be refused. The assemble now builds that batch itself, logs it, and counts it in assemble_stages; the helper's error type is kept as the error name. Comments trimmed back to each file's share at the base.
1 parent 5af76b2 commit c07e88f

5 files changed

Lines changed: 45 additions & 27 deletions

File tree

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

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,6 @@ 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.
124123
HYPERFRAMES_STITCH_FUNCTION: `${projectName}-render`,
125124
},
126125
});
@@ -133,18 +132,16 @@ export class HyperframesRenderStack extends Construct {
133132
this.renderFunction.addToRolePolicy(
134133
new iam.PolicyStatement({ actions: ["lambda:GetAccountSettings"], resources: ["*"] }),
135134
);
136-
// By name, not `grantInvoke(this.renderFunction)`, which would make the role depend on its own function.
135+
const renderFunctionArnWithoutRoleCycle = Stack.of(this).formatArn({
136+
service: "lambda",
137+
resource: "function",
138+
resourceName: `${projectName}-render`,
139+
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
140+
});
137141
this.renderFunction.addToRolePolicy(
138142
new iam.PolicyStatement({
139143
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-
],
144+
resources: [renderFunctionArnWithoutRoleCycle],
148145
}),
149146
);
150147

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1699,7 +1699,7 @@ describe("handler — stitch helpers", () => {
16991699
invoked.push(command.input.FunctionName);
17001700
const sent = JSON.parse(command.input.Payload) as StitchPartsEvent;
17011701
if (sent.Parts[0]!.ranges[0]!.uri.endsWith("missing")) {
1702-
const payload = JSON.stringify({ errorMessage: "NoSuchKey" });
1702+
const payload = JSON.stringify({ errorMessage: "NoSuchKey", errorType: "NoSuchKey" });
17031703
return { FunctionError: "Unhandled", Payload: new TextEncoder().encode(payload) };
17041704
}
17051705
const out = await handler(sent, { s3: s3 as unknown as S3Client });
@@ -1712,9 +1712,10 @@ describe("handler — stitch helpers", () => {
17121712
'"part-3"',
17131713
'"part-4"',
17141714
]);
1715-
await expect(send(target, event("s3://bucket/missing").Parts)).rejects.toThrow(
1716-
"stitchParts on proj-video failed: NoSuchKey",
1717-
);
1715+
await expect(send(target, event("s3://bucket/missing").Parts)).rejects.toMatchObject({
1716+
name: "NoSuchKey",
1717+
message: expect.stringContaining("stitchParts on proj-video failed: NoSuchKey"),
1718+
});
17181719
expect(invoked).toEqual(["proj-video", "proj-video"]);
17191720
} finally {
17201721
if (prev === undefined) delete process.env.HYPERFRAMES_STITCH_FUNCTION;

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -941,6 +941,7 @@ async function stitchChunksInS3(
941941
parts: stitched.parts,
942942
downloadedBytes: stitched.downloadedBytes,
943943
helpers: stitched.helpers,
944+
helperFallbacks: stitched.helperFallbacks,
944945
});
945946
return {
946947
Action: "assemble",
@@ -1129,11 +1130,14 @@ export function stitchHelper(lambda?: LambdaClient): StitchHelper | undefined {
11291130
new TextDecoder().decode(response.Payload),
11301131
) as StitchPartsLambdaResult & {
11311132
errorMessage?: string;
1133+
errorType?: string;
11321134
};
11331135
if (response.FunctionError) {
1134-
throw new Error(
1136+
const error = new Error(
11351137
`[handler] stitchParts on ${functionName} failed: ${body.errorMessage ?? response.FunctionError}`,
11361138
);
1139+
if (body.errorType) error.name = body.errorType;
1140+
throw error;
11371141
}
11381142
return body.ETags;
11391143
};

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,19 @@ describe.skipIf(!hasFfmpeg)("stitchMp4InS3 on real chunks", () => {
321321
expect(batches.length).toBeGreaterThan(0);
322322
expect(s3.objects.get("s3://bucket/helped.mp4")!.equals(output)).toBe(true);
323323

324+
// Every helper throttled (another render holds the reservation): built here, same bytes.
325+
const throttled = await stitchMp4InS3(s3.asClient(), uris, "s3://bucket/throttled.mp4", {
326+
minPartBytes: 16 * 1024,
327+
helper: {
328+
send: async () => {
329+
throw Object.assign(new Error("Rate exceeded"), { name: "TooManyRequestsException" });
330+
},
331+
maxInvocations: Infinity,
332+
},
333+
});
334+
expect(throttled.helperFallbacks).toBe(batches.length);
335+
expect(s3.objects.get("s3://bucket/throttled.mp4")!.equals(output)).toBe(true);
336+
324337
// Today's join: the video-only chunks plus the plan audio.
325338
writeFileSync(join(planDir, "meta", "encoder.json"), "{}");
326339
const referencePath = join(dir, "reference.mp4");

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

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// Builds the final mp4 inside S3: part 1 carries the stitched header, the other parts copy each
22
// chunk's mdat payload with UploadPartCopy, so almost no video byte passes through the function.
3-
// Chunks under S3's 5 MiB part minimum cannot be copied; their parts can go to helper invocations.
43

54
import {
65
type CompletedPart,
@@ -13,7 +12,6 @@ import { buildStitchedHeader, readMp4Layout } from "@hyperframes/producer/distri
1312
import { multipartUpload, type MultipartTarget, parseS3Uri } from "./s3Transport.js";
1413

1514
const MIN_PART_BYTES = 5 * 1024 * 1024;
16-
// One helper's share: ~0.5 s each way on a Lambda's ~80 MB/s link.
1715
const HELPER_BATCH_BYTES = 32 * 1024 * 1024;
1816

1917
/** Bytes `[start, end)` of an S3 object. */
@@ -27,16 +25,13 @@ export type Part = { copy: RangeSegment } | { upload: Segment[] };
2725

2826
const segmentSize = (s: Segment): number => ("bytes" in s ? s.bytes.length : s.end - s.start);
2927

30-
/** An upload part made only of S3 ranges, so another invocation can build it. */
3128
export interface RangePart {
3229
partNumber: number;
3330
ranges: RangeSegment[];
3431
}
35-
/** Uploads `parts` into `target` elsewhere and resolves their ETags in order. */
3632
export type SendRangeParts = (target: MultipartTarget, parts: RangePart[]) => Promise<string[]>;
3733
export interface StitchHelper {
3834
send: SendRangeParts;
39-
/** Invocations the helper function can run at once (its reserved concurrency). */
4035
maxInvocations: number;
4136
}
4237

@@ -119,10 +114,7 @@ const rangesOnly = (part: Part): RangeSegment[] | undefined =>
119114
const rangeBytes = (ranges: readonly RangeSegment[]) =>
120115
ranges.reduce((total, r) => total + segmentSize(r), 0);
121116

122-
/**
123-
* Groups the range-only upload parts into batches of about `HELPER_BATCH_BYTES`, grown so there
124-
* are never more than `maxBatches`: every closed batch holds at least total / maxBatches bytes.
125-
*/
117+
// Every closed batch holds at least total / maxBatches bytes, so there are never more than maxBatches.
126118
export function helperBatches(parts: readonly Part[], maxBatches = Infinity): RangePart[][] {
127119
const total = parts.reduce((sum, part) => sum + rangeBytes(rangesOnly(part) ?? []), 0);
128120
const batchBytes = Math.max(HELPER_BATCH_BYTES, Math.ceil(total / maxBatches));
@@ -143,7 +135,6 @@ export function helperBatches(parts: readonly Part[], maxBatches = Infinity): Ra
143135
return batches;
144136
}
145137

146-
/** A helper's side: builds each range part and returns the ETags in order. */
147138
export async function sendRangeParts(
148139
s3: S3Client,
149140
target: MultipartTarget,
@@ -204,8 +195,8 @@ export interface StitchResult {
204195
fileSize: number;
205196
parts: number;
206197
downloadedBytes: number;
207-
/** Helper invocations that built the range-only parts (0 without a helper). */
208198
helpers: number;
199+
helperFallbacks: number;
209200
}
210201

211202
/** One faststart mp4 at `destUri` from the stitched mp4 chunks at `chunkUris`, plus `audioUri`'s track when given. */
@@ -235,12 +226,24 @@ export async function stitchMp4InS3(
235226
})),
236227
];
237228
const parts = planParts(segments, minPartBytes);
238-
await uploadParts(s3, parts, destUri, "video/mp4", helper);
229+
let helperFallbacks = 0;
230+
const helperOrLocal = helper && {
231+
maxInvocations: helper.maxInvocations,
232+
// A throttled helper (another render may hold the reservation) costs time, not the render.
233+
send: (target: MultipartTarget, batch: RangePart[]) =>
234+
helper.send(target, batch).catch((error: unknown) => {
235+
helperFallbacks++;
236+
console.warn(`[s3Stitch] helper failed, building ${batch.length} parts here:`, error);
237+
return sendRangeParts(s3, target, batch);
238+
}),
239+
};
240+
await uploadParts(s3, parts, destUri, "video/mp4", helperOrLocal);
239241
const uploaded = parts.flatMap((part) => ("upload" in part ? part.upload : []));
240242
return {
241243
fileSize: segments.reduce((total, s) => total + segmentSize(s), 0),
242244
parts: parts.length,
243245
downloadedBytes: uploaded.reduce((total, s) => total + ("uri" in s ? segmentSize(s) : 0), 0),
244246
helpers: helper ? helperBatches(parts, helper.maxInvocations).length : 0,
247+
helperFallbacks,
245248
};
246249
}

0 commit comments

Comments
 (0)