Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
10 changes: 10 additions & 0 deletions packages/event-handler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@
"types": "./lib/esm/rest/index.d.ts",
"default": "./lib/esm/rest/index.js"
}
},
"./experimental-rest/middleware": {
"require": {
"types": "./lib/cjs/rest/middleware/index.d.ts",
"default": "./lib/cjs/rest/middleware/index.js"
},
"import": {
"types": "./lib/esm/rest/middleware/index.d.ts",
"default": "./lib/esm/rest/middleware/index.js"
}
}
},
"typesVersions": {
Expand Down
14 changes: 14 additions & 0 deletions packages/event-handler/src/rest/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,17 @@ export const PARAM_PATTERN = /:([a-zA-Z_]\w*)(?=\/|$)/g;
export const SAFE_CHARS = "-._~()'!*:@,;=+&$";

export const UNSAFE_CHARS = '%<> \\[\\]{}|^';

/**
* Match for compressible content type.
*/
export const COMPRESSIBLE_CONTENT_TYPE_REGEX =
/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;

export const CACHE_CONTROL_NO_TRANSFORM_REGEX =
/(?:^|,)\s*?no-transform\s*?(?:,|$)/i;

export const COMPRESSION_ENCODING_TYPES = {
GZIP: 'gzip',
DEFLATE: 'deflate',
} as const;
58 changes: 58 additions & 0 deletions packages/event-handler/src/rest/middleware/compress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { Middleware } from '@aws-lambda-powertools/event-handler/types';
import type { CompressionOptions } from 'src/types/rest.js';
import {
CACHE_CONTROL_NO_TRANSFORM_REGEX,
COMPRESSIBLE_CONTENT_TYPE_REGEX,
COMPRESSION_ENCODING_TYPES,
} from '../constants.js';

const compress = (options?: CompressionOptions): Middleware => {
const threshold = options?.threshold ?? 1024;

return async (_, reqCtx, next) => {
await next();

const contentLength = reqCtx.res.headers.get('content-length');

// Check if response should be compressed
if (
reqCtx.res.headers.has('content-encoding') || // already encoded
reqCtx.res.headers.has('transfer-encoding') || // already encoded or chunked
reqCtx.request.method === 'HEAD' || // HEAD request
(contentLength && Number(contentLength) < threshold) || // content-length below threshold
!shouldCompress(reqCtx.res) || // not compressible type
!shouldTransform(reqCtx.res) || // cache-control: no-transform
!reqCtx.res.body
) {
return;
}

const acceptedEncoding = reqCtx.request.headers.get('accept-encoding');
const encoding =
options?.encoding ??
Object.values(COMPRESSION_ENCODING_TYPES).find((encoding) =>
acceptedEncoding?.includes(encoding)
) ??
COMPRESSION_ENCODING_TYPES.GZIP;

// Compress the response
const stream = new CompressionStream(encoding);
reqCtx.res = new Response(reqCtx.res.body.pipeThrough(stream), reqCtx.res);
reqCtx.res.headers.delete('content-length');
reqCtx.res.headers.set('content-encoding', encoding);
};
};

const shouldCompress = (res: Response) => {
const type = res.headers.get('content-type');
return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type);
};

const shouldTransform = (res: Response) => {
const cacheControl = res.headers.get('cache-control');
// Don't compress for Cache-Control: no-transform
// https://tools.ietf.org/html/rfc7234#section-5.2.2.4
return !cacheControl || !CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl);
};

export { compress };
1 change: 1 addition & 0 deletions packages/event-handler/src/rest/middleware/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { compress } from './compress.js';
12 changes: 11 additions & 1 deletion packages/event-handler/src/types/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import type {
JSONObject,
} from '@aws-lambda-powertools/commons/types';
import type { APIGatewayProxyEvent, Context } from 'aws-lambda';
import type { HttpErrorCodes, HttpVerbs } from '../rest/constants.js';
import type {
COMPRESSION_ENCODING_TYPES,
HttpErrorCodes,
HttpVerbs,
} from '../rest/constants.js';
import type { Route } from '../rest/Route.js';
import type { Router } from '../rest/Router.js';
import type { ResolveOptions } from './common.js';
Expand Down Expand Up @@ -111,6 +115,11 @@ type ValidationResult = {
issues: string[];
};

type CompressionOptions = {
encoding?: (typeof COMPRESSION_ENCODING_TYPES)[keyof typeof COMPRESSION_ENCODING_TYPES];
threshold?: number;
};

export type {
CompiledRoute,
DynamicRoute,
Expand All @@ -131,4 +140,5 @@ export type {
RestRouteHandlerOptions,
RouteRegistryOptions,
ValidationResult,
CompressionOptions,
};
16 changes: 14 additions & 2 deletions packages/event-handler/tests/unit/rest/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import type { Middleware } from '../../../src/types/rest.js';

export const createTestEvent = (
path: string,
httpMethod: string
httpMethod: string,
headers: Record<string, string> = {}
): APIGatewayProxyEvent => ({
path,
httpMethod,
headers: {},
headers,
body: null,
multiValueHeaders: {},
isBase64Encoded: false,
Expand Down Expand Up @@ -65,3 +66,14 @@ export const createNoNextMiddleware = (
// Intentionally doesn't call next()
};
};

export const createSettingHeadersMiddleware = (headers: {
[key: string]: string;
}): Middleware => {
return async (_params, _options, next) => {
await next();
Object.entries(headers).map(([key, value]) =>
_options.res.headers.set(key, value)
);
};
};
212 changes: 212 additions & 0 deletions packages/event-handler/tests/unit/rest/middleware/compress.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import context from '@aws-lambda-powertools/testing-utils/context';
import { Router } from 'src/rest/Router.js';
import type { Middleware } from 'src/types/index.js';
import { beforeEach, describe, expect, it } from 'vitest';
import { compress } from '../../../../src/rest/middleware/index.js';
import { createSettingHeadersMiddleware, createTestEvent } from '../helpers.js';

describe('Compress Middleware', () => {
it('compresses response when conditions are met', async () => {
// Prepare
const event = createTestEvent('/test', 'GET');
const app = new Router();
app.get(
'/test',
[
compress(),
createSettingHeadersMiddleware({
'content-length': '2000',
}),
],
async () => {
return { test: 'x'.repeat(2000) };
}
);

// Act
const result = await app.resolve(event, context);

// Assess
expect(result.headers?.['content-encoding']).toBe('gzip');
expect(result.headers?.['content-length']).toBeUndefined();
});

it('skips compression when content is below threshold', async () => {
// Prepare
const event = createTestEvent('/test', 'GET');
const app = new Router();
app.get(
'/test',
[
compress({ threshold: 1024 }),
createSettingHeadersMiddleware({
'content-length': '1',
}),
],
async () => {
return { test: 'x' };
}
);

// Act
const result = await app.resolve(event, context);

// Assess
expect(result.headers?.['content-encoding']).toBeUndefined();
});

it('skips compression for HEAD requests', async () => {
// Prepare
const event = createTestEvent('/test', 'HEAD');
const app = new Router();
app.head(
'/test',
[
compress(),
createSettingHeadersMiddleware({
'content-length': '2000',
}),
],
async () => {
return { test: 'x'.repeat(2000) };
}
);

// Act
const result = await app.resolve(event, context);

// Assess
expect(result.headers?.['content-encoding']).toBeUndefined();
});

it('skips compression when already encoded', async () => {
// Prepare
const event = createTestEvent('/test', 'GET');
const app = new Router();
app.get(
'/test',
[
compress({
encoding: 'deflate',
}),
compress({
encoding: 'gzip',
}),
createSettingHeadersMiddleware({
'content-length': '2000',
}),
],
async () => {
return { test: 'x'.repeat(2000) };
}
);

// Act
const result = await app.resolve(event, context);

// Assess
expect(result.headers?.['content-encoding']).toEqual('gzip');
});

it('skips compression for non-compressible content types', async () => {
// Prepare
const event = createTestEvent('/test', 'GET');
const app = new Router();
app.get(
'/test',
[
compress(),
createSettingHeadersMiddleware({
'content-length': '2000',
'content-type': 'image/jpeg',
}),
],
async () => {
return { test: 'x'.repeat(2000) };
}
);

// Act
const result = await app.resolve(event, context);

// Assess
expect(result.headers?.['content-encoding']).toBeUndefined();
});

it('skips compression when cache-control no-transform is set', async () => {
// Prepare
const event = createTestEvent('/test', 'GET');
const app = new Router();
app.get(
'/test',
[
compress(),
createSettingHeadersMiddleware({
'content-length': '2000',
'cache-control': 'no-transform',
}),
],
async () => {
return { test: 'x'.repeat(2000) };
}
);

// Act
const result = await app.resolve(event, context);

// Assess
expect(result.headers?.['content-encoding']).toBeUndefined();
});

it('uses specified encoding when provided', async () => {
// Prepare
const event = createTestEvent('/test', 'GET');
const app = new Router();
app.get(
'/test',
[
compress({
encoding: 'deflate',
}),
createSettingHeadersMiddleware({
'content-length': '2000',
}),
],
async () => {
return { test: 'x'.repeat(2000) };
}
);

// Act
const result = await app.resolve(event, context);

// Assess
expect(result.headers?.['content-encoding']).toBe('deflate');
});

it('infers encoding from Accept-Encoding header', async () => {
// Prepare
const event = createTestEvent('/test', 'GET', {
'Accept-Encoding': 'deflate',
});
const app = new Router();
app.get(
'/test',
[
compress(),
createSettingHeadersMiddleware({
'content-length': '2000',
}),
],
async () => {
return { test: 'x'.repeat(2000) };
}
);

// Act
const result = await app.resolve(event, context);

// Assess
expect(result.headers?.['content-encoding']).toBe('deflate');
});
});
Loading