mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 00:07:09 +00:00
* feat(aws-lambda): price arm64 chunk invocations at the arm64 rate getRenderProgress takes chunkArchitecture, the architecture of the function that renders chunks. RenderChunk invocations are priced at its per GB-second rate, both inline and from a Distributed Map's output; plan, audio and assemble stay at the x86 rate. * feat(cli): render chunks on an arm64 function with lambda deploy --video-arch --video-arch arm64 pushes the arm64 video function image to the stack's own ECR repository and deploys the template with VideoImageUri set to its digest. Outside a checkout the image is the one the installed adapter pins; inside a checkout it must come from HYPERFRAMES_LAMBDA_VIDEO_IMAGE, built from that checkout. The default stays x86_64, which always sends an empty VideoImageUri so a redeploy drops a video function rather than keeping it. destroy deletes the repository, render and progress price chunks at the arm64 rate, and policies lists the ECR actions. * fix(cli): push the video image only to an ECR repository this stack tagged * fix(cli): price the plan at the video function's rate now that it runs there * feat(cli): lambda deploy renders on arm64 by default; --video-arch x86_64 keeps x86 * refactor(cli): drop two doc comments the names already carry
243 lines
8.7 KiB
TypeScript
243 lines
8.7 KiB
TypeScript
/**
|
|
* Thin wrappers around the AWS SAM CLI used by `hyperframes lambda deploy`
|
|
* and `hyperframes lambda destroy`.
|
|
*
|
|
* We shell out instead of programmatically driving the CloudFormation API
|
|
* because:
|
|
* 1. SAM handles the rollback-on-failure semantics correctly, including
|
|
* stuck-rollback recovery. Re-implementing that in TypeScript would
|
|
* duplicate a non-trivial chunk of the SAM CLI.
|
|
* 2. The SAM template at `examples/aws-lambda/template.yaml` already
|
|
* describes the topology; adopters who customize the template
|
|
* shouldn't have to maintain it twice.
|
|
* 3. SAM's `--resolve-s3` auto-creates an artifact bucket for the
|
|
* handler ZIP upload, which we'd otherwise have to re-implement.
|
|
*
|
|
* CDK adopters use `HyperframesRenderStack` directly from their own
|
|
* CDK app — this CLI path is for users who don't want to write a CDK
|
|
* project.
|
|
*/
|
|
|
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
|
|
/** Throws with a clear hint when the SAM CLI is not on PATH. */
|
|
function assertSamAvailable(): void {
|
|
try {
|
|
execFileSync("sam", ["--version"], { stdio: "ignore" });
|
|
} catch {
|
|
throw new Error(
|
|
"`sam` CLI not found on PATH. Install AWS SAM CLI from https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html and retry.",
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Throws with a clear hint when the `aws` CLI is not on PATH. */
|
|
function assertAwsCliAvailable(): void {
|
|
try {
|
|
execFileSync("aws", ["--version"], { stdio: "ignore" });
|
|
} catch {
|
|
throw new Error(
|
|
"`aws` CLI not found on PATH. Install from https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html and configure credentials before retrying.",
|
|
);
|
|
}
|
|
}
|
|
|
|
export interface DeployOptions {
|
|
/** Directory holding the `template.yaml` to deploy; SAM runs from here. */
|
|
samDir: string;
|
|
/** CloudFormation stack name. */
|
|
stackName: string;
|
|
region: string;
|
|
awsProfile?: string;
|
|
reservedConcurrency?: number;
|
|
/** Lambda memory in MB. Forwarded as the `LambdaMemoryMb` parameter override. */
|
|
lambdaMemoryMb?: number;
|
|
chromeSource?: "sparticuz" | "chrome-headless-shell";
|
|
/** ECR image for the arm64 video function; omitted, chunks render on the x86 function. */
|
|
videoImageUri?: string;
|
|
/** Pass-through stdio. Defaults to "inherit" so SAM's progress lines stream live. */
|
|
stdio?: "inherit" | "pipe";
|
|
}
|
|
|
|
/**
|
|
* Resolve the checkout's SAM template. Its `CodeUri` is relative to the monorepo; outside a
|
|
* checkout deploy uses the adapter's packaged template instead (see prebuiltHandler.ts).
|
|
*/
|
|
export function locateSamTemplate(repoRoot: string): string {
|
|
const candidate = join(repoRoot, "examples", "aws-lambda", "template.yaml");
|
|
if (!existsSync(candidate)) {
|
|
throw new Error(
|
|
`[lambda] SAM template not found at ${candidate}. ` +
|
|
"`hyperframes lambda deploy` needs a HyperFrames repo checkout: run it from one, " +
|
|
"or set HYPERFRAMES_REPO_ROOT to point at one.",
|
|
);
|
|
}
|
|
return candidate;
|
|
}
|
|
|
|
/** `--concurrency`: a positive integer, or `none` (-1, the template's "unreserved"). */
|
|
export function parseReservedConcurrency(raw: unknown): number | undefined {
|
|
if (raw === undefined || raw === null || raw === "") return undefined;
|
|
if (raw === "none") return -1;
|
|
const n = Number(raw);
|
|
if (!Number.isInteger(n) || n < 1) {
|
|
throw new Error(
|
|
`[lambda] --concurrency must be a positive integer or "none"; got ${String(raw)}`,
|
|
);
|
|
}
|
|
return n;
|
|
}
|
|
|
|
/** Run `sam deploy` non-interactively. Returns when SAM exits 0; throws on non-zero. */
|
|
export function samDeploy(opts: DeployOptions): void {
|
|
assertSamAvailable();
|
|
const paramOverrides = [
|
|
`ChromeSource=${opts.chromeSource ?? "sparticuz"}`,
|
|
// Always sent: omitted, SAM's UsePreviousValue would keep a video function the user dropped.
|
|
`VideoImageUri=${opts.videoImageUri ?? '""'}`,
|
|
];
|
|
// Omitted, SAM sends UsePreviousValue: a redeploy keeps the stack's reservation, a new stack gets -1.
|
|
if (opts.reservedConcurrency !== undefined) {
|
|
paramOverrides.push(`ReservedConcurrency=${opts.reservedConcurrency}`);
|
|
}
|
|
if (opts.lambdaMemoryMb !== undefined) {
|
|
paramOverrides.push(`LambdaMemoryMb=${opts.lambdaMemoryMb}`);
|
|
}
|
|
const args = [
|
|
"deploy",
|
|
"--stack-name",
|
|
opts.stackName,
|
|
"--region",
|
|
opts.region,
|
|
"--resolve-s3",
|
|
"--capabilities",
|
|
"CAPABILITY_IAM",
|
|
"--no-confirm-changeset",
|
|
"--no-fail-on-empty-changeset",
|
|
"--parameter-overrides",
|
|
...paramOverrides,
|
|
];
|
|
if (opts.awsProfile) {
|
|
args.push("--profile", opts.awsProfile);
|
|
}
|
|
const result = spawnSync("sam", args, { cwd: opts.samDir, stdio: opts.stdio ?? "inherit" });
|
|
if (result.status !== 0) {
|
|
throw new Error(
|
|
`[lambda] sam deploy exited with code ${result.status ?? "unknown"}\n` +
|
|
`If a prior attempt left a stack in ROLLBACK_COMPLETE, CloudFormation can't reuse it. ` +
|
|
`Delete it before retrying:\n` +
|
|
` aws cloudformation delete-stack --stack-name aws-sam-cli-managed-default --region ${opts.region}\n` +
|
|
` aws cloudformation delete-stack --stack-name ${opts.stackName} --region ${opts.region}\n` +
|
|
`(the first is SAM's managed artifacts stack from --resolve-s3; the second is the render stack).`,
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Run `sam delete` non-interactively. */
|
|
export function samDelete(opts: {
|
|
samDir: string;
|
|
stackName: string;
|
|
region: string;
|
|
awsProfile?: string;
|
|
stdio?: "inherit" | "pipe";
|
|
}): void {
|
|
assertSamAvailable();
|
|
const args = ["delete", "--stack-name", opts.stackName, "--region", opts.region, "--no-prompts"];
|
|
if (opts.awsProfile) {
|
|
args.push("--profile", opts.awsProfile);
|
|
}
|
|
const result = spawnSync("sam", args, { cwd: opts.samDir, stdio: opts.stdio ?? "inherit" });
|
|
if (result.status !== 0) {
|
|
throw new Error(`[lambda] sam delete exited with code ${result.status ?? "unknown"}`);
|
|
}
|
|
}
|
|
|
|
export interface StackOutputBag {
|
|
bucketName: string;
|
|
functionName: string;
|
|
stateMachineArn: string;
|
|
reservedConcurrency?: number;
|
|
/** Present when the stack has the arm64 video function. */
|
|
videoFunctionName?: string;
|
|
}
|
|
|
|
/**
|
|
* Query CloudFormation for the stack outputs the SAM template exports.
|
|
* Used after `samDeploy` to populate the local state file.
|
|
*/
|
|
export function fetchStackOutputs(opts: {
|
|
stackName: string;
|
|
region: string;
|
|
awsProfile?: string;
|
|
}): StackOutputBag {
|
|
assertAwsCliAvailable();
|
|
const args = [
|
|
"cloudformation",
|
|
"describe-stacks",
|
|
"--stack-name",
|
|
opts.stackName,
|
|
"--region",
|
|
opts.region,
|
|
"--query",
|
|
"Stacks[0]",
|
|
"--output",
|
|
"json",
|
|
];
|
|
if (opts.awsProfile) {
|
|
args.unshift("--profile", opts.awsProfile);
|
|
}
|
|
const out = execFileSync("aws", args, { encoding: "utf-8" });
|
|
const stack = JSON.parse(out) as {
|
|
Outputs?: { OutputKey: string; OutputValue: string }[];
|
|
Parameters?: { ParameterKey: string; ParameterValue: string }[];
|
|
};
|
|
const byKey = new Map((stack.Outputs ?? []).map((o) => [o.OutputKey, o.OutputValue]));
|
|
const reserved = Number(
|
|
stack.Parameters?.find((p) => p.ParameterKey === "ReservedConcurrency")?.ParameterValue,
|
|
);
|
|
const bucketName = byKey.get("RenderBucketName");
|
|
const functionName = byKey.get("RenderFunctionArn");
|
|
const stateMachineArn = byKey.get("RenderStateMachineArn");
|
|
if (!bucketName || !functionName || !stateMachineArn) {
|
|
throw new Error(
|
|
`[lambda] stack ${opts.stackName} is missing one of RenderBucketName/RenderFunctionArn/RenderStateMachineArn. Got keys: ${[...byKey.keys()].join(", ")}`,
|
|
);
|
|
}
|
|
return {
|
|
bucketName,
|
|
// RenderFunctionArn is the full ARN; the Lambda function name is the
|
|
// last colon-segment, which downstream `getRenderProgress` calls use
|
|
// for cost math + CloudWatch lookups.
|
|
functionName: functionName.split(":").pop() ?? functionName,
|
|
stateMachineArn,
|
|
reservedConcurrency: reserved > 0 ? reserved : undefined,
|
|
videoFunctionName: byKey.get("VideoFunctionArn")?.split(":").pop(),
|
|
};
|
|
}
|
|
|
|
/** Delete an ECR repository and its images; one that is already gone counts as deleted. */
|
|
export function deleteEcrRepository(opts: {
|
|
repositoryName: string;
|
|
region: string;
|
|
awsProfile?: string;
|
|
}): void {
|
|
assertAwsCliAvailable();
|
|
const args = [
|
|
"ecr",
|
|
"delete-repository",
|
|
"--repository-name",
|
|
opts.repositoryName,
|
|
"--force",
|
|
"--region",
|
|
opts.region,
|
|
];
|
|
if (opts.awsProfile) args.push("--profile", opts.awsProfile);
|
|
const result = spawnSync("aws", args, { encoding: "utf-8" });
|
|
if (result.status === 0 || result.stderr?.includes("RepositoryNotFoundException")) return;
|
|
throw new Error(
|
|
`[lambda] aws ecr delete-repository ${opts.repositoryName} exited with code ${result.status ?? "unknown"}: ${result.stderr ?? ""}`,
|
|
);
|
|
}
|