Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 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
18 changes: 18 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,21 @@ 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 = {
COMMON: /^\s*application\/json(?:[;\s]|$)/i,
OCCASIONAL:
/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:xml|javascript)|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,
RARE: /^\s*(?:application\/(?: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]|$)/i,
};

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

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

/**
* Compresses HTTP response bodies using standard compression algorithms.
*
* This middleware automatically compresses response bodies when they exceed
* a specified threshold and the client supports compression. It respects
* cache-control directives and only compresses appropriate content types.
*
* The middleware checks several conditions before compressing:
* - Response is not already encoded or chunked
* - Request method is not HEAD
* - Content length exceeds the threshold
* - Content type is compressible
* - Cache-Control header doesn't contain no-transform
* - Response has a body
*
* **Basic compression with default settings**
*
* @example
* ```typescript
* import { Router } from '@aws-lambda-powertools/event-handler';
* import { compress } from '@aws-lambda-powertools/event-handler/rest/middleware';
*
* const app = new Router();
*
* app.use(compress());
*
* app.get('/api/data', async () => {
* return { data: 'large response body...' };
* });
* ```
*
* **Custom compression settings**
*
* @example
* ```typescript
* import { Router } from '@aws-lambda-powertools/event-handler';
* import { compress } from '@aws-lambda-powertools/event-handler/rest/middleware';
*
* const app = new Router();
*
* app.use(compress({
* threshold: 2048,
* encoding: 'deflate'
* }));
*
* app.get('/api/large-data', async () => {
* return { data: 'very large response...' };
* });
* ```
*
* @param options - Configuration options for compression behavior
* @param options.threshold - Minimum response size in bytes to trigger compression (default: 1024)
* @param options.encoding - Preferred compression encoding to use when client supports multiple formats
*/

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

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

const contentLength = reqCtx.res.headers.get('content-length');
const isEncodedOrChunked =
reqCtx.res.headers.has('content-encoding') ||
reqCtx.res.headers.has('transfer-encoding');

// Check if response should be compressed
if (
isEncodedOrChunked ||
reqCtx.request.method === 'HEAD' ||
(contentLength && Number(contentLength) < threshold) ||
!shouldCompress(reqCtx.res) ||
!shouldTransform(reqCtx.res) ||
!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.COMMON.test(type) ||
COMPRESSIBLE_CONTENT_TYPE_REGEX.OCCASIONAL.test(type) ||
COMPRESSIBLE_CONTENT_TYPE_REGEX.RARE.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).forEach(([key, value]) => {
options.res.headers.set(key, value);
});
};
};
Loading