Skip to content

🎥 Make videos programmatically with React

proper cleanup

Jonny Burger81bed4fa0e81
diff --git a/packages/lambda/src/functions/helpers/streamify-response.ts b/packages/lambda/src/functions/helpers/streamify-response.ts
index a8d4d183e6..95b0e93865 100644
--- a/packages/lambda/src/functions/helpers/streamify-response.ts
+++ b/packages/lambda/src/functions/helpers/streamify-response.ts
@@ -1,9 +1,14 @@
-import {Stream} from 'stream';
+import {Writable} from 'stream';
-export class ResponseStream extends Stream.Writable {
+type Chunk = {
+ PayloadChunk: {Payload: string | Buffer | null};
+ InvokeComplete: boolean;
+};
+
+export class ResponseStream extends Writable {
+ private queue: Chunk[] = [];
+ private waitingResolve: ((value?: Chunk) => void)[] = [];
private response: Buffer[];
- _contentType?: string;
- _isBase64Encoded?: boolean;
constructor() {
super();
@@ -11,34 +16,54 @@ export class ResponseStream extends Stream.Writable {
}
_write(
- chunk: string,
+ chunk: any,
encoding: BufferEncoding,
callback: (error?: Error | null) => void,
): void {
+ const data = Buffer.from(chunk, encoding);
+ const resolve = this.waitingResolve.shift();
+ if (resolve) {
+ resolve({PayloadChunk: {Payload: data}, InvokeComplete: false});
+ } else {
+ this.queue.push({PayloadChunk: {Payload: data}, InvokeComplete: false});
+ }
+
this.response.push(Buffer.from(chunk, encoding));
- callback();
- }
- getBufferedData(): Buffer {
- return Buffer.concat(this.response);
+ callback();
}
- setContentType(contentType: string) {
- this._contentType = contentType;
+ _finish() {
+ const resolve = this.waitingResolve.shift();
+ if (resolve) {
+ resolve({PayloadChunk: {Payload: null}, InvokeComplete: true});
+ } else {
+ this.queue.push({PayloadChunk: {Payload: null}, InvokeComplete: true});
+ }
}
- setIsBase64Encoded(isBase64Encoded: boolean) {
- this._isBase64Encoded = isBase64Encoded;
+ getBufferedData(): Buffer {
+ return Buffer.concat(this.response);
}
-}
-function patchArgs(argList: unknown[]): ResponseStream {
- if (!(argList[1] instanceof ResponseStream)) {
- const responseStream = new ResponseStream();
- argList.splice(1, 0, responseStream);
+ async *[Symbol.asyncIterator](): AsyncGenerator<Chunk, void, void> {
+ while (true) {
+ if (this.queue.length > 0) {
+ yield this.queue.shift()!;
+ } else {
+ // Wait for new data to be written
+ yield new Promise<Chunk>((resolve) => {
+ this.waitingResolve.push((data) => {
+ Promise.resolve(data).then((d) => {
+ if (d) {
+ resolve(d);
+ }
+ });
+ });
+ });
+ }
+ }
}
-
- return argList[1] as ResponseStream;
}
export function streamifyResponse(handler: Function): Function {
@@ -53,21 +78,7 @@ export function streamifyResponse(handler: Function): Function {
return awslambda.streamifyResponse(handler);
}
- return new Proxy(handler, {
- async apply(target, _, argList) {
- const responseStream: ResponseStream = patchArgs(argList);
- await target(...argList);
-
- return {
- EventStream: [
- {
- PayloadChunk: {
- Payload: responseStream.getBufferedData(),
- },
- InvokeComplete: true,
- },
- ],
- };
- },
- });
+ return () => {
+ throw new Error('Lambda not detected');
+ };
}
diff --git a/packages/lambda/src/functions/index.ts b/packages/lambda/src/functions/index.ts
index b723e3d52c..38f392684b 100644
--- a/packages/lambda/src/functions/index.ts
+++ b/packages/lambda/src/functions/index.ts
@@ -257,7 +257,7 @@ export type OrError<T> =
stack: string;
};
-const routine = async (
+export const routine = async (
params: LambdaPayload,
responseStream: ResponseStream,
context: RequestContext,
diff --git a/packages/lambda/src/shared/__mocks__/aws-clients.ts b/packages/lambda/src/shared/__mocks__/aws-clients.ts
index 3e4489b550..5b60aa5688 100644
--- a/packages/lambda/src/shared/__mocks__/aws-clients.ts
+++ b/packages/lambda/src/shared/__mocks__/aws-clients.ts
@@ -19,23 +19,29 @@ export const getLambdaClient: typeof original = (region, timeoutInTest) => {
}) => {
const payload = JSON.parse(params.input.Payload);
- const {handler} = await import('../../functions/index');
+ const {routine} = await import('../../functions/index');
const responseStream = new ResponseStream();
- const res = await handler(payload, responseStream, {
+ const prom = routine(payload, responseStream, {
invokedFunctionArn: 'arn:fake',
getRemainingTimeInMillis: () => timeoutInTest ?? 120000,
+ awsRequestId: 'fake',
});
if (
params.input.InvocationType === 'RequestResponse' ||
params.input.InvocationType === 'Event'
) {
- return {Payload: res.EventStream[0].PayloadChunk.Payload};
+ await prom;
+ return {Payload: responseStream.getBufferedData()};
}
+ prom.then(() => {
+ responseStream._finish();
+ responseStream.end();
+ });
// When streaming, we should not consume the response
return {
- EventStream: res.EventStream,
+ EventStream: responseStream,
};
},
} as unknown as LambdaClient;
diff --git a/packages/lambda/src/shared/call-lambda.ts b/packages/lambda/src/shared/call-lambda.ts
index e6c53d5bf4..38e91c5701 100644
--- a/packages/lambda/src/shared/call-lambda.ts
+++ b/packages/lambda/src/shared/call-lambda.ts
@@ -135,24 +135,22 @@ const invokeStreamOrTimeout = async ({
}),
);
- let cleanup: Function = () => undefined;
+ let cleanup = () => undefined;
const timeout = new Promise<InvokeWithResponseStreamCommandOutput>(
(_resolve, reject) => {
const int = setTimeout(() => {
reject(new Error(LAMBDA_STREAM_STALL));
}, STREAM_STALL_TIMEOUT);
- cleanup = () => clearTimeout(int);
+ cleanup = () => {
+ clearTimeout(int);
+ };
},
);
- const res = await Promise.race([
- resProm.then((r) => {
- cleanup();
- return r;
- }),
- timeout,
- ]);
+ const res = await Promise.race([resProm, timeout]);
+
+ cleanup();
return res;
};
@@ -222,6 +220,8 @@ const callLambdaWithStreamingWithoutRetry = async <T extends LambdaRoutines>({
`Lambda function ${functionName} failed with error code ${event.InvokeComplete.ErrorCode}: ${event.InvokeComplete.ErrorDetails}. See ${logs} to see the logs of this invocation.`,
);
}
+
+ break;
}
}