mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
* fix(aws-lambda): match the shell to its own pin, ship only hashed files, refuse the shell ZIP in CDK and SAM Review follow-ups to the pinned shell route: - build-zip --source=chrome-headless-shell accepts the folder only when its digest is pinned for this version, not for any pinned build. - It leaves out the files the digest skips (debug.log and chrome_debug.log, which Chrome writes as it runs), so nothing unhashed ships. - The CDK construct throws on chromeSource "chrome-headless-shell" and the SAM template allows only sparticuz, as lambda deploy already refused it: a shell ZIP cannot fit a function. The CHROME_PATH wiring for that ZIP is gone with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(aws-lambda): raise the packed size budget to 82,000 bytes The shipped build-zip script now checks the shell against its own version's pin and skips the files the digest leaves out. That takes the tarball to 81,378 bytes in CI, over the 80,500 budget's 1% tolerance; main was already within about 200 bytes of it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
479 lines
19 KiB
TypeScript
479 lines
19 KiB
TypeScript
/**
|
||
* `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. Only `"sparticuz"`: a shell ZIP is over Lambda's limit. */
|
||
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;
|
||
|
||
function zipChromeSource(
|
||
source: NonNullable<HyperframesRenderStackProps["chromeSource"]>,
|
||
): "sparticuz" {
|
||
if (source === "sparticuz") return source;
|
||
throw new Error(
|
||
"[HyperframesRenderStack] chromeSource chrome-headless-shell does not fit a Lambda ZIP function, so the " +
|
||
"handler ZIP ships @sparticuz/chromium. The arm64 video image runs chrome-headless-shell.",
|
||
);
|
||
}
|
||
|
||
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 = zipChromeSource(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");
|
||
}
|