Repository navigation
Expand file tree
/
Copy pathHyperframesRenderStack.ts
More file actions
468 lines (440 loc) · 18.4 KB
/
Copy pathHyperframesRenderStack.ts
File metadata and controls
468 lines (440 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/**
* `HyperframesRenderStack` — aws-cdk-lib L2 construct that emits the same
* topology as `examples/aws-lambda/template.yaml`.
*
* Adopters who embed HyperFrames inside their own CDK app can extend this
* construct or compose alongside it; the construct exposes its `.bucket`,
* `.renderFunction`, and `.stateMachine` properties so additional
* resources (alarms, dashboards, SNS topics) can be wired without
* re-deriving the ARNs from a stack export.
*
* `aws-cdk-lib` and `constructs` are **peerDependencies**. The package
* still type-checks (and the snapshot test still runs) because they're
* also `devDependencies`, but adopters who only consume the SDK side of
* `@hyperframes/aws-lambda` don't pull the CDK tree at runtime.
*
* Drift from the SAM template is guarded by the snapshot test
* (`HyperframesRenderStack.snapshot.test.ts`), which diffs the synthed
* CloudFormation against the SAM-rendered CloudFormation modulo
* normalisation.
*/
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ArnFormat, Duration, RemovalPolicy, Size, Stack } from "aws-cdk-lib";
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import * as iam from "aws-cdk-lib/aws-iam";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as logs from "aws-cdk-lib/aws-logs";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as sfn from "aws-cdk-lib/aws-stepfunctions";
import * as tasks from "aws-cdk-lib/aws-stepfunctions-tasks";
import { Construct } from "constructs";
import { CONTENT_STORE_PREFIX, CONTENT_STORE_RETENTION_DAYS } from "../contentStore.js";
/** Construction-time props for {@link HyperframesRenderStack}. */
export interface HyperframesRenderStackProps {
/** Name prefix applied to function / state-machine / alarm names. Default `"hyperframes"`. */
projectName?: string;
/** Lambda memory in MB. Allowed: 2048..10240 in 1024 steps. Default 10240. */
lambdaMemoryMb?: 2048 | 3072 | 4096 | 5120 | 6144 | 7168 | 8192 | 9216 | 10240;
/** Per-invocation Lambda timeout. Default 900 (15 min, Lambda hard cap). */
lambdaTimeoutSec?: number;
/** Lambda reserved concurrency cap. `undefined` = unreserved (account default). */
reservedConcurrency?: number;
/** Which Chrome runtime was bundled into the handler ZIP. Default `"sparticuz"`. */
chromeSource?: "sparticuz" | "chrome-headless-shell";
/** Threshold for the runaway-invocations alarm. Default 1000 invocations/hour. */
chunkInvocationAlarmThreshold?: number;
/**
* Absolute path to the handler ZIP produced by
* `bun run --cwd packages/aws-lambda build:zip`. Defaults to the
* package-relative path the build script writes to. Adopters who
* deploy the published handler ZIP set this explicitly.
*/
handlerZipPath?: string;
/** S3 bucket retention policy on stack delete. Default RETAIN. */
bucketRemovalPolicy?: RemovalPolicy;
}
const DEFAULT_MEMORY_MB = 10240;
const DEFAULT_TIMEOUT_SEC = 900;
const DEFAULT_CHROME_SOURCE = "sparticuz";
const DEFAULT_ALARM_THRESHOLD = 1000;
export class HyperframesRenderStack extends Construct {
/** S3 bucket for plan tarballs, chunk outputs, and final renders. */
readonly bucket: s3.Bucket;
/** The single Lambda function dispatching plan / renderChunk / assemble. */
readonly renderFunction: lambda.Function;
/** The Step Functions state machine orchestrating the render. */
readonly stateMachine: sfn.StateMachine;
constructor(scope: Construct, id: string, props: HyperframesRenderStackProps = {}) {
super(scope, id);
const projectName = props.projectName ?? "hyperframes";
const memorySize = props.lambdaMemoryMb ?? DEFAULT_MEMORY_MB;
const timeoutSec = props.lambdaTimeoutSec ?? DEFAULT_TIMEOUT_SEC;
const chromeSource = props.chromeSource ?? DEFAULT_CHROME_SOURCE;
const alarmThreshold = props.chunkInvocationAlarmThreshold ?? DEFAULT_ALARM_THRESHOLD;
const handlerZipPath = props.handlerZipPath ?? defaultHandlerZipPath();
this.bucket = new s3.Bucket(this, "RenderBucket", {
removalPolicy: props.bucketRemovalPolicy ?? RemovalPolicy.RETAIN,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
// `Suspended` is the cheapest mode that still satisfies KMS / replication
// prerequisites callers can layer on later. Adopters who treat the final
// mp4 as user-keepable can switch to `Enabled`.
versioned: false,
lifecycleRules: [
{
id: "ExpireIntermediates",
enabled: true,
prefix: "renders/",
expiration: Duration.days(7),
},
{
id: "ExpireSharedContent",
enabled: true,
prefix: `${CONTENT_STORE_PREFIX}/`,
expiration: Duration.days(CONTENT_STORE_RETENTION_DAYS),
},
],
});
this.renderFunction = new lambda.Function(this, "RenderFunction", {
functionName: `${projectName}-render`,
runtime: lambda.Runtime.NODEJS_22_X,
handler: "handler.handler",
code: lambda.Code.fromAsset(handlerZipPath),
memorySize,
timeout: Duration.seconds(timeoutSec),
ephemeralStorageSize: Size.gibibytes(10),
architecture: lambda.Architecture.X86_64,
reservedConcurrentExecutions: props.reservedConcurrency,
tracing: lambda.Tracing.ACTIVE,
environment: {
NODE_OPTIONS: "--enable-source-maps",
TMPDIR: "/tmp",
HYPERFRAMES_LAMBDA_CHROME_SOURCE: chromeSource,
HYPERFRAMES_RENDER_BUCKET: this.bucket.bucketName,
HYPERFRAMES_LAMBDA_RESERVED_CONCURRENCY: String(props.reservedConcurrency ?? -1),
HYPERFRAMES_STITCH_FUNCTION: `${projectName}-render`,
},
});
// Scoped S3 perms only — explicitly NOT `CloudWatchLogsFullAccess`,
// which would grant `logs:*` on `*` and overscope adopter accounts.
// SAM's AWSLambdaBasicExecutionRole equivalent is included by the
// default `new lambda.Function` execution role.
this.bucket.grantReadWrite(this.renderFunction);
this.renderFunction.addToRolePolicy(
new iam.PolicyStatement({ actions: ["lambda:GetAccountSettings"], resources: ["*"] }),
);
const renderFunctionArnWithoutRoleCycle = Stack.of(this).formatArn({
service: "lambda",
resource: "function",
resourceName: `${projectName}-render`,
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
});
this.renderFunction.addToRolePolicy(
new iam.PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: [renderFunctionArnWithoutRoleCycle],
}),
);
const stateMachineLogGroup = new logs.LogGroup(this, "RenderStateMachineLogGroup", {
logGroupName: `/aws/states/${projectName}-render`,
retention: logs.RetentionDays.ONE_MONTH,
removalPolicy: RemovalPolicy.DESTROY,
});
const definition = this.buildStateMachineDefinition();
this.stateMachine = new sfn.StateMachine(this, "RenderStateMachine", {
stateMachineName: `${projectName}-render`,
stateMachineType: sfn.StateMachineType.STANDARD,
definitionBody: sfn.DefinitionBody.fromChainable(definition),
tracingEnabled: true,
timeout: Duration.hours(1),
logs: {
destination: stateMachineLogGroup,
level: sfn.LogLevel.ERROR,
includeExecutionData: false,
},
});
this.renderFunction.grantInvoke(this.stateMachine);
new cloudwatch.Alarm(this, "RenderChunkInvocationAlarm", {
alarmName: `${projectName}-runaway-chunk-invocations`,
alarmDescription:
"Fires if RenderChunk Lambda invocations exceed the configured threshold in a 1-hour window.",
metric: this.renderFunction.metricInvocations({
period: Duration.hours(1),
statistic: cloudwatch.Stats.SUM,
}),
threshold: alarmThreshold,
evaluationPeriods: 1,
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});
new cloudwatch.Alarm(this, "RenderFunctionErrorsAlarm", {
alarmName: `${projectName}-render-function-errors`,
alarmDescription: "Fires if the render Lambda reports any errors in a 5-minute window.",
metric: this.renderFunction.metricErrors({
period: Duration.minutes(5),
statistic: cloudwatch.Stats.SUM,
}),
threshold: 1,
evaluationPeriods: 1,
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});
new cloudwatch.Alarm(this, "RenderStateMachineFailedAlarm", {
alarmName: `${projectName}-render-state-machine-failed`,
alarmDescription: "Fires when the render state machine reports a failed execution.",
metric: this.stateMachine.metricFailed({
period: Duration.minutes(5),
statistic: cloudwatch.Stats.SUM,
}),
threshold: 1,
evaluationPeriods: 1,
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});
}
/**
* Build the state-machine chain. Kept in a single method so the SAM
* template and this construct can be diffed shape-for-shape during
* the snapshot test.
*/
private buildStateMachineDefinition(): sfn.IChainable {
// `ChromeBinaryUnavailableError` is non-retryable: a wedged warm
// instance keeps returning the same falsy executablePath until the
// env recycles, so retries just burn the 4× 15-min budget.
const NON_RETRYABLE_PLAN = [
"FFMPEG_VERSION_MISMATCH",
"PLAN_HASH_MISMATCH",
"S3_URI_NOT_ALLOWED",
"BROWSER_GPU_NOT_SOFTWARE",
"FONT_FETCH_FAILED",
"PLAN_PROTOCOL_UNSUPPORTED",
"PlanProtocolUnsupportedError",
"PLAN_V2_INTEGRITY_UNRECOVERABLE",
"VIDEO_SOURCE_UNRENDERABLE",
"INVALID_VIDEO_METADATA",
"NOT_MEDIA_PAYLOAD",
"NotMediaPayloadError",
"PlanV2IntegrityError",
"PLAN_ARTIFACT_DIGEST_MISMATCH",
"FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED",
"CHUNK_EXCEEDS_WORKER_TIMEOUT",
"ChromeBinaryUnavailableError",
"SITE_MANIFEST_INVALID",
];
const NON_RETRYABLE_CHUNK = [
"FFMPEG_VERSION_MISMATCH",
"PLAN_HASH_MISMATCH",
"S3_URI_NOT_ALLOWED",
"BROWSER_GPU_NOT_SOFTWARE",
"PLAN_PROTOCOL_UNSUPPORTED",
"PlanProtocolUnsupportedError",
"PLAN_V2_INTEGRITY_UNRECOVERABLE",
"INVALID_VIDEO_METADATA",
"PlanV2IntegrityError",
"PLAN_ARTIFACT_DIGEST_MISMATCH",
"ChromeBinaryUnavailableError",
"ImageMissingFromFrameError",
];
const NON_RETRYABLE_ASSEMBLE = [
"FFMPEG_VERSION_MISMATCH",
"PLAN_HASH_MISMATCH",
"S3_URI_NOT_ALLOWED",
"PLAN_PROTOCOL_UNSUPPORTED",
"PlanProtocolUnsupportedError",
"PLAN_V2_INTEGRITY_UNRECOVERABLE",
"PlanV2IntegrityError",
"FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED",
"PLAN_ARTIFACT_DIGEST_MISMATCH",
"ChromeBinaryUnavailableError",
];
const THROTTLED_RETRY: sfn.RetryProps = {
errors: ["Lambda.TooManyRequestsException"],
interval: Duration.seconds(5),
maxAttempts: 10,
backoffRate: 2,
maxDelay: Duration.seconds(60),
jitterStrategy: sfn.JitterType.FULL,
};
const planV2 = new tasks.LambdaInvoke(this, "PlanV2", {
lambdaFunction: this.renderFunction,
payload: sfn.TaskInput.fromObject({
Action: "plan",
PlanProtocol: "v2",
"ProjectS3Uri.$": "$.ProjectS3Uri",
"PlanOutputS3Prefix.$": "$.PlanOutputS3Prefix",
"Config.$": "$.Config",
}),
resultSelector: {
PlanProtocol: "v2",
"PlanV2ManifestS3Uri.$": "$.Payload.PlanV2ManifestS3Uri",
"PlanV2ArtifactS3Prefix.$": "$.Payload.PlanV2ArtifactS3Prefix",
"PlanHash.$": "$.Payload.PlanHash",
"ChunkCount.$": "$.Payload.ChunkCount",
"MaxChunkConcurrency.$": "$.Payload.MaxChunkConcurrency",
"Format.$": "$.Payload.Format",
"HasAudio.$": "$.Payload.HasAudio",
"SeparateAudio.$": "$.Payload.SeparateAudio",
},
resultPath: "$.Plan",
});
planV2.addRetry({ errors: NON_RETRYABLE_PLAN, maxAttempts: 0 });
planV2.addRetry(THROTTLED_RETRY);
planV2.addRetry({
errors: ["States.ALL"],
interval: Duration.seconds(2),
maxAttempts: 4,
backoffRate: 2,
maxDelay: Duration.seconds(60),
});
const buildChunkList = new sfn.Pass(this, "BuildChunkList", {
parameters: {
"ChunkIndexes.$": "States.ArrayRange(0, States.MathAdd($.Plan.ChunkCount, -1), 1)",
},
resultPath: "$.Iterator",
});
const planProducedZero = new sfn.Fail(this, "PlanProducedZeroChunks", {
error: "PLAN_EMPTY",
cause: "Plan returned ChunkCount=0 — non-retryable producer-side invariant violation.",
});
const renderChunkV2Task = new tasks.LambdaInvoke(this, "RenderChunkV2", {
lambdaFunction: this.renderFunction,
payload: sfn.TaskInput.fromObject({
Action: "renderChunk",
PlanProtocol: "v2",
"ChunkIndex.$": "$.ChunkIndex",
"PlanV2ManifestS3Uri.$": "$.PlanV2ManifestS3Uri",
"PlanV2ArtifactS3Prefix.$": "$.PlanV2ArtifactS3Prefix",
"PlanHash.$": "$.PlanHash",
"ChunkOutputS3Prefix.$": "$.ChunkOutputS3Prefix",
"Format.$": "$.Format",
}),
resultSelector: {
"ChunkS3Uri.$": "$.Payload.ChunkS3Uri",
"ChunkIndex.$": "$.Payload.ChunkIndex",
"Sha256.$": "$.Payload.Sha256",
"FramesEncoded.$": "$.Payload.FramesEncoded",
"DurationMs.$": "$.Payload.DurationMs",
},
});
renderChunkV2Task.addRetry({ errors: NON_RETRYABLE_CHUNK, maxAttempts: 0 });
renderChunkV2Task.addRetry(THROTTLED_RETRY);
renderChunkV2Task.addRetry({
errors: ["States.ALL"],
interval: Duration.seconds(2),
maxAttempts: 4,
backoffRate: 2,
maxDelay: Duration.seconds(60),
});
const renderChunksV2 = new sfn.DistributedMap(this, "RenderChunksV2", {
label: "RenderChunksV2",
mapExecutionType: sfn.StateMachineType.STANDARD,
itemsPath: "$.Iterator.ChunkIndexes",
itemSelector: {
"ChunkIndex.$": "$$.Map.Item.Value",
"PlanV2ManifestS3Uri.$": "$.Plan.PlanV2ManifestS3Uri",
"PlanV2ArtifactS3Prefix.$": "$.Plan.PlanV2ArtifactS3Prefix",
"PlanHash.$": "$.Plan.PlanHash",
"ChunkOutputS3Prefix.$": "$.PlanOutputS3Prefix",
"Format.$": "$.Plan.Format",
},
maxConcurrencyPath: "$.Plan.MaxChunkConcurrency",
resultPath: "$.Chunks",
});
renderChunksV2.itemProcessor(renderChunkV2Task);
const assembleV2 = new tasks.LambdaInvoke(this, "AssembleV2", {
lambdaFunction: this.renderFunction,
payload: sfn.TaskInput.fromObject({
Action: "assemble",
PlanProtocol: "v2",
"PlanV2ManifestS3Uri.$": "$.Plan.PlanV2ManifestS3Uri",
"PlanV2ArtifactS3Prefix.$": "$.Plan.PlanV2ArtifactS3Prefix",
"PlanHash.$": "$.Plan.PlanHash",
"ChunkS3Uris.$": "$.Render.Chunks[*].ChunkS3Uri",
"AudioS3Uri.$": "$.Render.Audio.AudioS3Uri",
"OutputS3Uri.$": "$.OutputS3Uri",
"Format.$": "$.Plan.Format",
}),
resultSelector: {
"OutputS3Uri.$": "$.Payload.OutputS3Uri",
"FramesEncoded.$": "$.Payload.FramesEncoded",
"FileSize.$": "$.Payload.FileSize",
},
resultPath: "$.Output",
});
assembleV2.addRetry({ errors: NON_RETRYABLE_ASSEMBLE, maxAttempts: 0 });
assembleV2.addRetry(THROTTLED_RETRY);
assembleV2.addRetry({
errors: ["States.ALL"],
interval: Duration.seconds(2),
maxAttempts: 4,
backoffRate: 2,
maxDelay: Duration.seconds(60),
});
// The plan left its audio out: mix it while the chunks render.
const audio = new tasks.LambdaInvoke(this, "Audio", {
lambdaFunction: this.renderFunction,
payload: sfn.TaskInput.fromObject({
Action: "audio",
"ProjectS3Uri.$": "$.ProjectS3Uri",
"PlanOutputS3Prefix.$": "$.PlanOutputS3Prefix",
"Config.$": "$.Config",
}),
resultSelector: {
"HasAudio.$": "$.Payload.HasAudio",
"AudioS3Uri.$": "$.Payload.AudioS3Uri",
},
resultPath: "$.Audio",
});
audio.addRetry({ errors: NON_RETRYABLE_PLAN, maxAttempts: 0 });
audio.addRetry(THROTTLED_RETRY);
audio.addRetry({
errors: ["States.ALL"],
interval: Duration.seconds(2),
maxAttempts: 4,
backoffRate: 2,
maxDelay: Duration.seconds(60),
});
const audioNeeded = new sfn.Choice(this, "AudioNeeded")
.when(sfn.Condition.booleanEquals("$.Plan.SeparateAudio", true), audio)
.otherwise(
new sfn.Pass(this, "NoAudio", {
result: sfn.Result.fromObject({ HasAudio: false, AudioS3Uri: null }),
resultPath: "$.Audio",
}),
);
const renderV2 = new sfn.Parallel(this, "RenderV2", {
resultSelector: { "Chunks.$": "$[0].Chunks", "Audio.$": "$[1].Audio" },
resultPath: "$.Render",
})
.branch(renderChunksV2)
.branch(audioNeeded);
const assertChunkCount = new sfn.Choice(this, "AssertChunkCount")
.when(sfn.Condition.numberGreaterThan("$.Plan.ChunkCount", 0), renderV2.next(assembleV2))
.otherwise(planProducedZero);
planV2.next(buildChunkList);
buildChunkList.next(assertChunkCount);
const unsupportedPlanProtocol = new sfn.Fail(this, "UnsupportedPlanProtocol", {
error: "PLAN_PROTOCOL_UNSUPPORTED",
cause: 'PlanProtocol must be "v2" or absent (defaults to v2).',
});
// A comparison on a missing path is a States.Runtime error, not a non-match, so an omitted
// PlanProtocol has to be caught before the stringEquals rule.
return new sfn.Choice(this, "SelectPlanProtocol")
.when(sfn.Condition.isNotPresent("$.PlanProtocol"), planV2)
.when(sfn.Condition.stringEquals("$.PlanProtocol", "v2"), planV2)
.when(sfn.Condition.isPresent("$.PlanProtocol"), unsupportedPlanProtocol)
.otherwise(planV2);
}
}
/**
* Default location of the handler ZIP relative to this source file. Two
* parents up = `packages/aws-lambda/`; the build script writes the ZIP
* to `packages/aws-lambda/dist/handler.zip`. The package is published with
* `main: "./src/index.ts"`, so this path resolves correctly both in the
* source tree (during `bun test` / local CDK synth) and in a consumer's
* `node_modules/@hyperframes/aws-lambda/` install.
*/
function defaultHandlerZipPath(): string {
const here = dirname(fileURLToPath(import.meta.url));
return resolve(here, "..", "..", "dist", "handler.zip");
}