Skip to content
Open
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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,12 @@ new LambdaEdgeController(
### Methods

#### `attachEdgeFunction(distributionId: string): Promise<any>`
Attaches the Lambda@Edge function to the specified CloudFront distribution.
Attaches the Lambda@Edge function to the default cache behavior of the specified CloudFront distribution.

CloudFront allows only one function per event type in a cache behavior. If a function is already associated with the same event type (another version of the same function, or a different function), it is replaced by the function given to the constructor. Associations for other event types and the other cache behaviors are left unchanged.

#### `detachEdgeFunction(distributionId: string): Promise<any>`
Removes the Lambda@Edge function from the specified CloudFront distribution.
Removes the Lambda@Edge function from the default cache behavior of the specified CloudFront distribution. Only the association for the constructor's event type whose ARN (including the version) exactly matches the ARN given to the constructor is removed.

#### `enableDebugger(): this`
Enables detailed logging for debugging purposes.
Expand Down
6 changes: 4 additions & 2 deletions README_ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,12 @@ new LambdaEdgeController(
### メソッド

#### `attachEdgeFunction(distributionId: string): Promise<any>`
指定されたCloudFrontディストリビューションにLambda@Edge関数をアタッチします。
指定されたCloudFrontディストリビューションのデフォルトキャッシュ動作にLambda@Edge関数をアタッチします。

CloudFrontでは、1つのキャッシュ動作につき、1つのイベントタイプに関連付けられる関数は1つだけです。同じイベントタイプに関数(同じ関数の別バージョン、または別の関数)がすでに関連付けられている場合は、コンストラクタに渡した関数に置き換えます。ほかのイベントタイプの関連付けと、ほかのキャッシュ動作は変更しません。

#### `detachEdgeFunction(distributionId: string): Promise<any>`
指定されたCloudFrontディストリビューションからLambda@Edge関数を削除します。
指定されたCloudFrontディストリビューションのデフォルトキャッシュ動作からLambda@Edge関数を削除します。削除するのは、コンストラクタに渡したイベントタイプの関連付けのうち、ARN(バージョンを含む)がコンストラクタに渡したARNと完全に一致するものだけです。

#### `enableDebugger(): this`
デバッグ目的で詳細なログを有効化します。
Expand Down
143 changes: 143 additions & 0 deletions __tests__/configUpdator.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
import type { DistributionConfig, LambdaFunctionAssociation } from '@aws-sdk/client-cloudfront'
import Updator from '../libs/configUpdator'

// Lambda@Edge only accepts versioned function ARNs, so these fixtures carry a version.
const functionArn = (name: string, version: number): string =>
`arn:aws:lambda:us-east-1:123456789012:function:${name}:${version}`

const createDistributionConfig = (
items: LambdaFunctionAssociation[],
cacheBehaviors?: unknown
): DistributionConfig => ({
DefaultCacheBehavior: {
LambdaFunctionAssociations: {
Quantity: items.length,
Items: items
}
},
...(cacheBehaviors ? { CacheBehaviors: cacheBehaviors } : {})
}) as unknown as DistributionConfig

const countByEventType = (items: LambdaFunctionAssociation[]): Record<string, number> => {
return items.reduce((counts: Record<string, number>, item) => {
const key = String(item.EventType)
counts[key] = (counts[key] || 0) + 1
return counts
}, {})
}

describe('libs/configUpdator.ts', () => {
describe('constructor', () => {
it('should set valid arn', () => {
Expand Down Expand Up @@ -240,4 +266,121 @@ describe('libs/configUpdator.ts', () => {
})
})
})
describe('with versioned Lambda function ARNs', () => {
let updator: Updator
beforeEach(() => {
updator = new Updator(functionArn('edge-fn', 3), 'viewer-request')
})
describe('#attatchEdgeFunction()', () => {
it('should replace another version of the same function on the same event type', () => {
const config = createDistributionConfig([
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) }
])
const result = updator.attatchEdgeFunction(config)
expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({
Quantity: 1,
Items: [
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) }
]
})
})
it('should replace a different function on the same event type', () => {
const config = createDistributionConfig([
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('other-fn', 1) }
])
const result = updator.attatchEdgeFunction(config)
expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({
Quantity: 1,
Items: [
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) }
]
})
})
it('should keep associations for other event types and keep Quantity equal to the number of Items', () => {
const originRequest = {
EventType: 'origin-request',
LambdaFunctionARN: functionArn('origin-fn', 5),
IncludeBody: true
} as LambdaFunctionAssociation
const viewerResponse = {
EventType: 'viewer-response',
LambdaFunctionARN: functionArn('response-fn', 1)
} as LambdaFunctionAssociation
const config = createDistributionConfig([
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) },
originRequest,
viewerResponse
])
const result = updator.attatchEdgeFunction(config)
const associations = result.DefaultCacheBehavior?.LambdaFunctionAssociations
const items = associations?.Items || []
expect(items).toHaveLength(3)
expect(associations?.Quantity).toEqual(items.length)
expect(items).toEqual(expect.arrayContaining([
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) },
{ EventType: 'origin-request', LambdaFunctionARN: functionArn('origin-fn', 5), IncludeBody: true },
{ EventType: 'viewer-response', LambdaFunctionARN: functionArn('response-fn', 1) }
]))
expect(countByEventType(items)).toEqual({
'viewer-request': 1,
'origin-request': 1,
'viewer-response': 1
})
})
it('should not change the other cache behaviors', () => {
const cacheBehaviors = {
Quantity: 1,
Items: [
{
PathPattern: '/api/*',
LambdaFunctionAssociations: {
Quantity: 1,
Items: [
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) }
]
}
}
]
}
const expectedCacheBehaviors = JSON.parse(JSON.stringify(cacheBehaviors))
const config = createDistributionConfig([
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) }
], cacheBehaviors)
const result = updator.attatchEdgeFunction(config)
expect(result.CacheBehaviors).toEqual(expectedCacheBehaviors)
expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({
Quantity: 1,
Items: [
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) }
]
})
})
it('should keep a single association when the same version is attached again', () => {
const config = createDistributionConfig([
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) }
])
const result = updator.attatchEdgeFunction(config)
expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({
Quantity: 1,
Items: [
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) }
]
})
})
})
describe('#detatchEdgeFunction()', () => {
it('should remove only the exact function version', () => {
const config = createDistributionConfig([
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) }
])
const result = updator.detatchEdgeFunction(config)
expect(result.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({
Quantity: 1,
Items: [
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) }
]
})
})
})
})
})
49 changes: 49 additions & 0 deletions __tests__/controller.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { CloudFrontClient, GetDistributionCommand, UpdateDistributionCommand, UpdateDistributionCommandInput } from '@aws-sdk/client-cloudfront'
import Controller from '../libs/controller'

describe('libs/contorller.ts', () => {
Expand All @@ -8,4 +9,52 @@ describe('libs/contorller.ts', () => {
}).not.toThrow()
})
})
describe('#attachEdgeFunction()', () => {
const functionArn = (name: string, version: number): string =>
`arn:aws:lambda:us-east-1:123456789012:function:${name}:${version}`

it('should send a single viewer-request association when another version is already attached', async () => {
const updateInputs: UpdateDistributionCommandInput[] = []
const cloudfront = {
send: async (command: unknown) => {
if (command instanceof GetDistributionCommand) {
return {
ETag: 'etag',
Distribution: {
Id: 'EDISTRIBUTIONID',
DistributionConfig: {
DefaultCacheBehavior: {
LambdaFunctionAssociations: {
Quantity: 1,
Items: [
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 2) }
]
}
}
}
}
}
}
if (command instanceof UpdateDistributionCommand) {
updateInputs.push(command.input)
return {}
}
throw new Error('unexpected command')
}
} as unknown as CloudFrontClient
const controller = new Controller(functionArn('edge-fn', 3), 'viewer-request', { cloudfront })

await controller.attachEdgeFunction('EDISTRIBUTIONID')

expect(updateInputs).toHaveLength(1)
expect(updateInputs[0].Id).toEqual('EDISTRIBUTIONID')
expect(updateInputs[0].IfMatch).toEqual('etag')
expect(updateInputs[0].DistributionConfig?.DefaultCacheBehavior?.LambdaFunctionAssociations).toEqual({
Quantity: 1,
Items: [
{ EventType: 'viewer-request', LambdaFunctionARN: functionArn('edge-fn', 3) }
]
})
})
})
})
14 changes: 9 additions & 5 deletions libs/configUpdator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ export class ConfigUpdator {
/**
* update distribution config to attach edge function
*
* CloudFront allows only one function per event type in a cache behavior,
* so any function (or function version) already associated with the target
* event type of the default cache behavior is replaced.
*
* @param {CloudFront.Types.DistributionConfig} config - CloudFront distribution config
* @return {CloudFront.Types.DistributionConfig} updated distribution config
**/
Expand All @@ -142,11 +146,11 @@ export class ConfigUpdator {
LambdaFunctionARN: this.getLambdaArn(),
EventType: this.eventType
}
if (!lambdas.Items) {
lambdas.Items = [newItem]
} else {
lambdas.Items.push(newItem)
}
const newLambdaItems: LambdaFunctionAssociation[] = (lambdas.Items || []).filter(
(item: LambdaFunctionAssociation) => item.EventType !== this.eventType
)
newLambdaItems.push(newItem)
lambdas.Items = newLambdaItems
lambdas.Quantity = lambdas.Items.length
defaultCacheBehavior.LambdaFunctionAssociations = lambdas
return param
Expand Down
Loading