generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 175
feat(event-handler): added compress middleware for the REST API event handler #4495
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
d264ab9
Added compress middleware
sdangol 6c477ab
Added tests for the middleware
sdangol aa76a42
added export for middleware
sdangol ea9cc34
fixed tests and improved coverage
sdangol 6670bad
Added docstring comment for the compress function
sdangol aecd5bc
Changed map to foreach
sdangol 3bfccbc
Removed unused imports
sdangol 2627663
Addressed the feedbacks
sdangol 980c4f2
Broke down the regex into chunks and optimized tests
sdangol 67339fb
Broke down the regex further
sdangol 87058a2
Updated the regex
sdangol 4f071ce
Refactored the logic to remove checks for content types
sdangol 558caf5
Added tests for the converter
sdangol b74783e
Removed unused imports and unnecessary assignments
sdangol 70dae88
Simplified the shouldCompress check and added base64encoded checks
sdangol 4458a36
Added check for base64 encoding when the response is compressed
sdangol f24c501
Merge branch 'main' into feat/compress-middleware
sdangol c5270fa
Merge branch 'main' into feat/compress-middleware
svozza f6967a5
Fixed the tests structure
sdangol bc0241c
Merge branch 'feat/compress-middleware' of github.com:aws-powertools/…
sdangol File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import type { Middleware } from '@aws-lambda-powertools/event-handler/types'; | ||
dreamorosi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
import type { CompressionOptions } from 'src/types/rest.js'; | ||
dreamorosi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
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(); | ||
sdangol marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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 | ||
dreamorosi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
reqCtx.request.method === 'HEAD' || // HEAD request | ||
dreamorosi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
(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 }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { compress } from './compress.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
212 changes: 212 additions & 0 deletions
212
packages/event-handler/tests/unit/rest/middleware/compress.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', () => { | ||
sdangol marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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 () => { | ||
dreamorosi marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
// 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'); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.