Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 19 additions & 25 deletions packages/event-handler/src/rest/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Duplex, Readable, Writable } from 'node:stream';
import { Duplex, Readable } from 'node:stream';
import {
isRecord,
isRegExp,
Expand Down Expand Up @@ -308,17 +308,12 @@ export const resolvePrefixedPath = (path: Path, prefix?: Path): Path => {

export const HttpResponseStream =
globalThis.awslambda?.HttpResponseStream ??
class LocalHttpResponseStream extends Writable {
#contentType: string | undefined;

setContentType(contentType: string) {
this.#contentType = contentType;
}

// biome-ignore lint/complexity/noStaticOnlyClass: This is how the Lambda RIC implements it
class LocalHttpResponseStream {
static from(
underlyingStream: ResponseStream,
prelude: Record<string, string>
) {
): ResponseStream {
underlyingStream.setContentType(
"'application/vnd.awslambda.http-integration-response'"
);
Expand Down Expand Up @@ -401,22 +396,21 @@ const streamifyResponse =
return (async (event, responseStream, context) => {
await handler(event, responseStream, context);

/* v8 ignore else -- @preserve */
if ('chunks' in responseStream && Array.isArray(responseStream.chunks)) {
const output = Buffer.concat(responseStream.chunks as Buffer[]);
const nullBytes = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]);
const separatorIndex = output.indexOf(nullBytes);

const preludeBuffer = output.subarray(0, separatorIndex);
const bodyBuffer = output.subarray(separatorIndex + 8);
const prelude = JSON.parse(preludeBuffer.toString());

return {
body: bodyBuffer.toString(),
headers: prelude.headers,
statusCode: prelude.statusCode,
} as TResult;
}
/* v8 ignore next -- @preserve */
const output: Buffer =
(responseStream as ResponseStream).getBuffer?.() ?? Buffer.from([]);
const nullBytes = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]);
const separatorIndex = output.indexOf(nullBytes);

const preludeBuffer = output.subarray(0, separatorIndex);
const bodyBuffer = output.subarray(separatorIndex + 8);
const prelude = JSON.parse(preludeBuffer.toString());

return {
body: bodyBuffer.toString(),
headers: prelude.headers,
statusCode: prelude.statusCode,
} as TResult;
}) as StreamifyHandler<TEvent, TResult>;
});

Expand Down
11 changes: 6 additions & 5 deletions packages/event-handler/src/types/rest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Readable } from 'node:stream';
import type { Readable, Writable } from 'node:stream';
import type {
GenericLogger,
JSONValue,
Expand All @@ -12,7 +12,6 @@ import type {
} from 'aws-lambda';
import type { HttpStatusCodes, HttpVerbs } from '../rest/constants.js';
import type { Route } from '../rest/Route.js';
import type { HttpResponseStream } from '../rest/utils.js';
import type { ResolveOptions } from './common.js';

type ResponseType = 'ApiGatewayV1' | 'ApiGatewayV2';
Expand Down Expand Up @@ -140,9 +139,11 @@ type ValidationResult = {
issues: string[];
};

type ResponseStream = InstanceType<typeof HttpResponseStream> & {
_onBeforeFirstWrite?: (write: (data: Uint8Array | string) => void) => void;
};
interface ResponseStream extends Writable {
setContentType(contentType: string): void;
_onBeforeFirstWrite?: (writeFn: (chunk: unknown) => void) => void;
getBuffer?: () => Buffer;
}

type V1Headers = {
headers: Record<string, string>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
createTestEventV2,
createTestLambdaClass,
createTrackingMiddleware,
MockResponseStream,
ResponseStream,
} from '../helpers.js';

describe.each([
Expand Down Expand Up @@ -498,7 +498,7 @@ describe.each([
}

const lambda = new Lambda();
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();
const handler = lambda.handler.bind(lambda);

// Act
Expand Down Expand Up @@ -540,7 +540,7 @@ describe.each([
}

const lambda = new Lambda();
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();
const handler = lambda.handler.bind(lambda);

// Act
Expand Down
30 changes: 15 additions & 15 deletions packages/event-handler/tests/unit/rest/Router/streaming.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
import {
createTestEvent,
createTestEventV2,
MockResponseStream,
ResponseStream,
} from '../helpers.js';

describe.each([
Expand All @@ -22,7 +22,7 @@ describe.each([
app.get('/test', async () => ({ message: 'Hello, World!' }));

const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand All @@ -47,7 +47,7 @@ describe.each([
});

const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand All @@ -65,7 +65,7 @@ describe.each([
// Prepare
const app = new Router();
const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand Down Expand Up @@ -93,7 +93,7 @@ describe.each([
app.get('/test', () => ({ message: 'middleware test' }));

const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand All @@ -116,7 +116,7 @@ describe.each([
});

const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand Down Expand Up @@ -145,7 +145,7 @@ describe.each([
});

const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand Down Expand Up @@ -193,7 +193,7 @@ describe.each([
const app = new Router();
app.get('/test', handlerFn);
const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand All @@ -212,7 +212,7 @@ describe.each([
const app = new Router();
app.get('/test', () => new Response(null, { status: 204 }));
const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand All @@ -231,7 +231,7 @@ describe.each([
const app = new Router();
app.get('/test', () => new Response(undefined, { status: 200 }));
const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand All @@ -256,7 +256,7 @@ describe.each([

app.get('/test', () => new Response(errorStream, { status: 200 }));
const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act & Assess
await expect(
Expand All @@ -275,7 +275,7 @@ describe.each([
});

const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand All @@ -299,7 +299,7 @@ describe.each([
});

const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand All @@ -323,7 +323,7 @@ describe.each([
const app = new Router();
const handler = streamify(app);
const invalidEvent = { invalid: 'event' };
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act & Assess
await expect(
Expand All @@ -344,7 +344,7 @@ describe.each([
}));

const handler = streamify(app);
const responseStream = new MockResponseStream();
const responseStream = new ResponseStream();

// Act
const result = await handler(
Expand Down
28 changes: 21 additions & 7 deletions packages/event-handler/tests/unit/rest/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Writable } from 'node:stream';
import type {
APIGatewayProxyEvent,
APIGatewayProxyEventV2,
Expand All @@ -6,8 +7,11 @@ import type {
Context,
} from 'aws-lambda';
import type { Router } from '../../../src/rest/Router.js';
import { HttpResponseStream } from '../../../src/rest/utils.js';
import type { HandlerResponse, Middleware } from '../../../src/types/rest.js';
import type {
HandlerResponse,
ResponseStream as IResponseStream,
Middleware,
} from '../../../src/types/rest.js';

export const createTestEvent = (
path: string,
Expand Down Expand Up @@ -129,24 +133,34 @@ export const createHeaderCheckMiddleware = (headers: {
};
};

// Mock ResponseStream that extends the actual ResponseStream class
export class MockResponseStream extends HttpResponseStream {
public chunks: Buffer[] = [];
export class ResponseStream extends Writable implements IResponseStream {
// biome-ignore lint/correctness/noUnusedPrivateClassMembers: This is how the Lambda RIC implements it
#contentType: string | undefined;
readonly #chunks: Buffer[] = [];
public _onBeforeFirstWrite?: (
write: (data: Uint8Array | string) => void
) => void;
#firstWrite = true;

setContentType(contentType: string) {
this.#contentType = contentType;
}

_write(chunk: Buffer, _encoding: string, callback: () => void): void {
/* v8 ignore else -- @preserve */
if (this.#firstWrite && this._onBeforeFirstWrite) {
this._onBeforeFirstWrite((data: Uint8Array | string) => {
this.chunks.push(Buffer.from(data));
this.#chunks.push(Buffer.from(data));
});
this.#firstWrite = false;
}
this.chunks.push(chunk);
this.#chunks.push(chunk);
callback();
}

public getBuffer(): Buffer {
return Buffer.concat(this.#chunks);
}
}

// Create a handler function from the Router instance
Expand Down
Loading