diff --git a/README.md b/README.md index 867a711..9c3d610 100644 --- a/README.md +++ b/README.md @@ -108,10 +108,12 @@ new LambdaEdgeController( ### Methods #### `attachEdgeFunction(distributionId: string): Promise` -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` -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. diff --git a/README_ja.md b/README_ja.md index 061c20d..aecba18 100644 --- a/README_ja.md +++ b/README_ja.md @@ -108,10 +108,12 @@ new LambdaEdgeController( ### メソッド #### `attachEdgeFunction(distributionId: string): Promise` -指定されたCloudFrontディストリビューションにLambda@Edge関数をアタッチします。 +指定されたCloudFrontディストリビューションのデフォルトキャッシュ動作にLambda@Edge関数をアタッチします。 + +CloudFrontでは、1つのキャッシュ動作につき、1つのイベントタイプに関連付けられる関数は1つだけです。同じイベントタイプに関数(同じ関数の別バージョン、または別の関数)がすでに関連付けられている場合は、コンストラクタに渡した関数に置き換えます。ほかのイベントタイプの関連付けと、ほかのキャッシュ動作は変更しません。 #### `detachEdgeFunction(distributionId: string): Promise` -指定されたCloudFrontディストリビューションからLambda@Edge関数を削除します。 +指定されたCloudFrontディストリビューションのデフォルトキャッシュ動作からLambda@Edge関数を削除します。削除するのは、コンストラクタに渡したイベントタイプの関連付けのうち、ARN(バージョンを含む)がコンストラクタに渡したARNと完全に一致するものだけです。 #### `enableDebugger(): this` デバッグ目的で詳細なログを有効化します。 diff --git a/__tests__/configUpdator.test.ts b/__tests__/configUpdator.test.ts index 8cec9de..3011383 100644 --- a/__tests__/configUpdator.test.ts +++ b/__tests__/configUpdator.test.ts @@ -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 => { + return items.reduce((counts: Record, 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', () => { @@ -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) } + ] + }) + }) + }) + }) }) diff --git a/__tests__/controller.test.ts b/__tests__/controller.test.ts index 42ac271..dc259a3 100644 --- a/__tests__/controller.test.ts +++ b/__tests__/controller.test.ts @@ -1,3 +1,4 @@ +import { CloudFrontClient, GetDistributionCommand, UpdateDistributionCommand, UpdateDistributionCommandInput } from '@aws-sdk/client-cloudfront' import Controller from '../libs/controller' describe('libs/contorller.ts', () => { @@ -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) } + ] + }) + }) + }) }) diff --git a/libs/configUpdator.ts b/libs/configUpdator.ts index ca7d4c3..79eb716 100644 --- a/libs/configUpdator.ts +++ b/libs/configUpdator.ts @@ -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 **/ @@ -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