diff --git a/README.md b/README.md index 295209d..330bda0 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ export const createHandler = invokeHandler({ registerDependencies }) -export const handler = createHandler(parameters) +export const handler = await createHandler(parameters) ``` ## Installation @@ -76,7 +76,7 @@ A trivial handler that does nothing may be created like this import { invokeHandler } from '@pureskillgg/glhf' const createHandler = invokeHandler() -export const handler = createHandler() +export const handler = await createHandler() ``` To create a more useful handler, leverage @@ -86,7 +86,7 @@ To create a more useful handler, leverage import { invokeHandler } from '@pureskillgg/glhf' const createHandler = invokeHandler({ createProcessor, registerDependencies }) -export const handler = createHandler(parameters) +export const handler = await createHandler(parameters) ``` - Use `parameters` to load configuration with [AWS Config Executor]. @@ -97,12 +97,19 @@ export const handler = createHandler(parameters) This function is registered with the [Awilix] container as a factory function, thus it can access all dependencies registered using `registerDependencies`. +- Register a dependency named `init` as an async function which will be called + once when the handler is created. + This allows the function to perform one-time expensive setup on cold starts + or when provisioned concurrency is used. ### Handler Factories All exported handler functions return a new handler factory with identical signature: 1. `parameters`: The [AWS Config Executor] parameters to load. 2. `t`: The AVA `t` object (if running inside AVA). + If not using AVA, you must pass either `true` or an object with a `log` method + which takes a string message as it's only argument. + Additionally, your test running must set `NODE_ENV=test`. 3. `overrideDependencies`: A function with signature `(container, config) => void` which will be called immediately after `registerDependencies`. @@ -115,10 +122,11 @@ matching the signature expected by AWS Lambda. All handlers execute these steps in order: 1. Load the config defined by the parameters. 2. Create a new [Awilix] container and register the default dependencies: - `log`, `reqId`, and `processor`. - 3. Parse the event with the parser. - 4. Execute the processor on the event using the configured strategy and wrapper. - 5. Serialize and return the result. + `log`, `reqId`, `init`, and `processor`. + 3. Await the `init` function. + 4. Parse the event with the parser. + 6. Execute the processor on the event using the configured strategy and wrapper. + 7. Serialize and return the result. [AWS Config Executor]: https://github.com/pureskillgg/ace [Awilix]: https://github.com/jeffijoe/awilix @@ -142,7 +150,7 @@ const createProcessor = () => async (event, ctx) => { const createHandler = invokeHandler({ createProcessor }) -export const handler = createHandler() +export const handler = await createHandler() ``` #### EventBridge Handler @@ -181,7 +189,7 @@ const createProcessor = () => async (event, ctx) => { const createHandler = invokeHandler({ createProcessor }) -export const handler = createHandler() +export const handler = await createHandler() ``` ```yaml @@ -239,7 +247,7 @@ const createProcessor = () => async (event, ctx) => { const createHandler = sqsJsonHandler({ createProcessor }) -export const handler = createHandler() +export const handler = await createHandler() ``` ### Advanced usage diff --git a/handlers/blue.js b/handlers/blue.js index 25cbed8..3dedeb2 100644 --- a/handlers/blue.js +++ b/handlers/blue.js @@ -1,12 +1,40 @@ -'use strict' +import Sentry from '@sentry/serverless' +import { asFunction, asValue } from 'awilix' +import { envString } from '@pureskillgg/ace' -const Sentry = require('@sentry/serverless') +import { invokeHandler } from '../index.js' Sentry.AWSLambda.init() -const index = import('./blue.mjs') +const createInit = + ({ cache }) => + async () => { + cache.isInit = true + } -exports.handler = Sentry.AWSLambda.wrapHandler(async (...args) => { - const { handler } = await index - return handler(...args) +const registerDependencies = (container, config) => { + container.register({ rank: asValue(config.rank) }) + container.register({ + cache: asValue({}), + init: asFunction(createInit).singleton() + }) +} + +const parameters = { + rank: envString('RANK') +} + +const createProcessor = + ({ rank, cache }) => + async (event, ctx) => { + return { ...event, rank, isInit: cache.isInit } + } + +export const createHandler = invokeHandler({ + registerDependencies, + createProcessor }) + +export const handler = Sentry.AWSLambda.wrapHandler( + await createHandler(parameters) +) diff --git a/handlers/blue.mjs b/handlers/blue.mjs deleted file mode 100644 index a0c3bfd..0000000 --- a/handlers/blue.mjs +++ /dev/null @@ -1,25 +0,0 @@ -import { asValue } from 'awilix' -import { envString } from '@pureskillgg/ace' - -import { invokeHandler } from '../index.js' - -const registerDependencies = (container, config) => { - container.register({ rank: asValue(config.rank) }) -} - -const parameters = { - rank: envString('RANK') -} - -const createProcessor = - ({ rank }) => - async (event, ctx) => { - return { ...event, rank } - } - -export const createHandler = invokeHandler({ - registerDependencies, - createProcessor -}) - -export const handler = createHandler(parameters) diff --git a/handlers/package.json b/handlers/package.json deleted file mode 100644 index 0967ef4..0000000 --- a/handlers/package.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/handlers/red.js b/handlers/red.js index 7139fde..75673de 100644 --- a/handlers/red.js +++ b/handlers/red.js @@ -1,12 +1,40 @@ -'use strict' +import Sentry from '@sentry/serverless' +import { asClass } from 'awilix' +import { LambdaClient } from '@pureskillgg/awsjs' +import { ssmString } from '@pureskillgg/ace' -const Sentry = require('@sentry/serverless') +import { invokeHandler } from '../index.js' Sentry.AWSLambda.init() -const index = import('./red.mjs') +const parameters = { + blueLambdaFunction: ssmString('BLUE_LAMBDA_FUNCTION_SSM_PATH') +} -exports.handler = Sentry.AWSLambda.wrapHandler(async (...args) => { - const { handler } = await index - return handler(...args) +const createProcessor = + ({ blueLambdaClient, log }) => + async (event, ctx) => { + return blueLambdaClient.invokeJson(event) + } + +const registerDependencies = (container, config) => { + container.register( + 'blueLambdaClient', + asClass(LambdaClient).inject(() => ({ + name: 'blue', + functionName: config.blueLambdaFunction, + AwsLambdaClient: undefined, + params: undefined + })) + ) +} + +export const createHandler = invokeHandler({ + parameters, + createProcessor, + registerDependencies }) + +export const handler = Sentry.AWSLambda.wrapHandler( + await createHandler(parameters) +) diff --git a/handlers/red.mjs b/handlers/red.mjs deleted file mode 100644 index 98077bd..0000000 --- a/handlers/red.mjs +++ /dev/null @@ -1,35 +0,0 @@ -import { asClass } from 'awilix' -import { LambdaClient } from '@pureskillgg/awsjs' -import { ssmString } from '@pureskillgg/ace' - -import { invokeHandler } from '../index.js' - -const parameters = { - blueLambdaFunction: ssmString('BLUE_LAMBDA_FUNCTION_SSM_PATH') -} - -const createProcessor = - ({ blueLambdaClient, log }) => - async (event, ctx) => { - return blueLambdaClient.invokeJson(event) - } - -const registerDependencies = (container, config) => { - container.register( - 'blueLambdaClient', - asClass(LambdaClient).inject(() => ({ - name: 'blue', - functionName: config.blueLambdaFunction, - AwsLambdaClient: undefined, - params: undefined - })) - ) -} - -export const createHandler = invokeHandler({ - parameters, - createProcessor, - registerDependencies -}) - -export const handler = createHandler(parameters) diff --git a/lib/config.js b/lib/config.js index 887da12..73b7b1d 100644 --- a/lib/config.js +++ b/lib/config.js @@ -1,11 +1,9 @@ -import { getConfig } from '@pureskillgg/ace' +import { getConfig as getAceConfig } from '@pureskillgg/ace' -export const createGetConfig = - ({ parameters, cache, aliases }) => - async (ctx, log) => - getConfig({ - parameters, - cache, - aliases, - log: log.child({ isConfigLog: true }) - }) +export const getConfig = async ({ parameters, cache, aliases, log }) => + getAceConfig({ + parameters, + cache, + aliases, + log: log.child({ isConfigLog: true }) + }) diff --git a/lib/container.js b/lib/container.js index d84e9d4..4150318 100644 --- a/lib/container.js +++ b/lib/container.js @@ -1,6 +1,24 @@ -import { asFunction, asValue } from 'awilix' +import { asFunction, asValue, createContainer } from 'awilix' -export { createContainer } from 'awilix' +import { getRequestId } from './request-id.js' +import { createGlobalCtx } from './ctx.js' +import { createLogger } from './logger.js' + +export const createDependencies = (env, t) => { + const container = createContainer() + const ctx = createGlobalCtx(env) + const log = createLogger(ctx, t) + const reqId = getRequestId() + const init = async () => {} + + container.register({ + init: asValue(init), + reqId: asValue(reqId), + log: asValue(log.child({ reqId, isAppLog: false })) + }) + + return container +} export const createScope = (container, { ctx, log, createProcessor }) => { const scope = container.createScope() diff --git a/lib/ctx.js b/lib/ctx.js index 49922d7..26a6e1a 100644 --- a/lib/ctx.js +++ b/lib/ctx.js @@ -15,3 +15,7 @@ export const createCtx = (event, context) => { reqId } } + +export const createGlobalCtx = (env) => ({ + functionName: env.AWS_LAMBDA_FUNCTION_NAME +}) diff --git a/lib/handlers/factory.js b/lib/handlers/factory.js index d7a4c60..b5723ee 100644 --- a/lib/handlers/factory.js +++ b/lib/handlers/factory.js @@ -3,11 +3,13 @@ import { identityParser } from '../parsers/index.js' import { identitySerializer } from '../serializers/index.js' import { createInvokeWrapper } from '../wrappers/index.js' import { createEventStrategy } from '../strategies/index.js' -import { createContainer, createScope } from '../container.js' +import { createDependencies, createScope } from '../container.js' import { createCache } from '../cache.js' -import { createGetConfig } from '../config.js' +import { getConfig } from '../config.js' import { createCtx } from '../ctx.js' +const env = { ...process.env } + export const createHandler = ({ parser = identityParser, @@ -18,27 +20,30 @@ export const createHandler = createStrategy = createEventStrategy, logOptions = {} }) => - (parameters, t, overrideDependencies = registerEmptyDependencies) => { + async (parameters, t, overrideDependencies = registerEmptyDependencies) => { + if (process.env.NODE_ENV === 'test' && !t) return async () => {} + const cache = createCache() - const container = createContainer() + const container = createDependencies(env, t) - const getConfig = createGetConfig({ + const config = await getConfig({ parameters, cache, - aliases: t ? undefined : { ...process.env } + aliases: t ? undefined : env, + log: container.resolve('log') }) + registerDependencies(container, config) + overrideDependencies(container, config) + + const init = container.resolve('init') + await init() + return async (event, context = {}) => { try { const ctx = createCtx(event, context) const log = createLogger(ctx, t, logOptions) - const config = await getConfig(ctx, log) - - registerDependencies(container, config) - overrideDependencies(container, config) - const scope = createScope(container, { ctx, log, createProcessor }) - const strategy = createStrategy(scope) const handle = createWrapper(log, strategy, parser, serializer) return handle(event, ctx) diff --git a/lib/logger.js b/lib/logger.js index a7b1e17..8d5a9b2 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -11,16 +11,16 @@ const envBase = { version: process.env.LOG_VERSION } -export const createLogger = (ctx, t, options) => +export const createLogger = (ctx, t, options = {}) => createMlabsLogger({ name: getName(ctx), level, outputMode: isDev ? 'pretty' : 'json', - t, + t: t?.log == null ? { ...t, log: () => {} } : t, ...options, base: { ...createBase(ctx), - ...options.base + ...(options?.base ?? {}) } }) diff --git a/test/handlers/blue.spec.js b/test/handlers/blue.spec.js index c7cba5c..6dc3817 100644 --- a/test/handlers/blue.spec.js +++ b/test/handlers/blue.spec.js @@ -1,11 +1,11 @@ import test from 'ava' import { localString } from '@pureskillgg/ace' -import { createHandler } from '../../handlers/blue.mjs' +import { createHandler } from '../../handlers/blue.js' test('invoke', async (t) => { const event = { foo: 'bar' } - const handler = createHandler(parameters, t) + const handler = await createHandler(parameters, t) const data = await handler(event) t.snapshot(data, 'handler') }) diff --git a/test/handlers/http.spec.js b/test/handlers/http.spec.js index 51c5702..f0c93e0 100644 --- a/test/handlers/http.spec.js +++ b/test/handlers/http.spec.js @@ -7,7 +7,7 @@ test('httpHandler: invoke', async (t) => { const event = await readJson('fixtures', 'event', 'api-gateway-proxy.json') event.reqId = 'mock-req-id' const createHandler = httpHandler({ createProcessor }) - const handler = createHandler({}, t) + const handler = await createHandler({}, t) const data = await handler(event) t.snapshot(data, 'handler') }) @@ -18,7 +18,7 @@ test('httpHandler: handle error', async (t) => { const createHandler = httpHandler({ createProcessor: createProcessorWithError }) - const handler = createHandler({}, t) + const handler = await createHandler({}, t) const data = await handler(event) t.snapshot(data, 'handler') }) @@ -29,7 +29,7 @@ test('httpHandler: handle boom error', async (t) => { const createHandler = httpHandler({ createProcessor: createProcessorWithBoomError }) - const handler = createHandler({}, t) + const handler = await createHandler({}, t) const data = await handler(event) t.snapshot(data, 'handler') }) @@ -39,7 +39,7 @@ test('httpJsonHandler: invoke', async (t) => { event.reqId = 'mock-req-id' event.body = '{"a":1}' const createHandler = httpJsonHandler({ createProcessor }) - const handler = createHandler({}, t) + const handler = await createHandler({}, t) const data = await handler(event) t.snapshot(data, 'handler') }) @@ -51,7 +51,7 @@ test('httpJsonHandler: handle error', async (t) => { const createHandler = httpHandler({ createProcessor: createProcessorWithError }) - const handler = createHandler({}, t) + const handler = await createHandler({}, t) const data = await handler(event) t.snapshot(data, 'handler') }) @@ -63,7 +63,7 @@ test('httpJsonHandler: handle boom error', async (t) => { const createHandler = httpJsonHandler({ createProcessor: createProcessorWithBoomError }) - const handler = createHandler({}, t) + const handler = await createHandler({}, t) const data = await handler(event) t.snapshot(data, 'handler') }) diff --git a/test/handlers/red.spec.js b/test/handlers/red.spec.js index f4a6298..eb0e48a 100644 --- a/test/handlers/red.spec.js +++ b/test/handlers/red.spec.js @@ -1,7 +1,7 @@ import test from 'ava' import { asValue } from 'awilix' -import { createHandler } from '../../handlers/red.mjs' +import { createHandler } from '../../handlers/red.js' test('invoke', async (t) => { const event = { foo: 'bar' } @@ -17,7 +17,7 @@ test('invoke', async (t) => { container.register('blueLambdaClient', asValue(blueLambdaClient)) } - const handler = createHandler({}, t, overrideDependencies) + const handler = await createHandler({}, t, overrideDependencies) const data = await handler(event) t.snapshot(data, 'handler') }) diff --git a/test/handlers/snapshots/blue.spec.js.md b/test/handlers/snapshots/blue.spec.js.md index c62f3bf..35ce0ff 100644 --- a/test/handlers/snapshots/blue.spec.js.md +++ b/test/handlers/snapshots/blue.spec.js.md @@ -10,5 +10,6 @@ Generated by [AVA](https://avajs.dev). { foo: 'bar', + isInit: true, rank: 'mock-rank', } diff --git a/test/handlers/snapshots/blue.spec.js.snap b/test/handlers/snapshots/blue.spec.js.snap index cd4713f..1e20546 100644 Binary files a/test/handlers/snapshots/blue.spec.js.snap and b/test/handlers/snapshots/blue.spec.js.snap differ diff --git a/test/handlers/sqs.spec.js b/test/handlers/sqs.spec.js index 5f8943b..dcb2d6c 100644 --- a/test/handlers/sqs.spec.js +++ b/test/handlers/sqs.spec.js @@ -6,7 +6,7 @@ test('sqsHandler: invoke', async (t) => { const event = await readJson('fixtures', 'event', 'sqs.json') event.reqId = 'mock-req-id' const createHandler = sqsHandler({ createProcessor }) - const handler = createHandler({}, t) + const handler = await createHandler({}, t) const data = await handler(event) t.snapshot(data, 'handler') }) @@ -15,7 +15,7 @@ test('sqsJsonHandler: invoke', async (t) => { const event = await readJson('fixtures', 'event', 'sqs.json') event.reqId = 'mock-req-id' const createHandler = sqsJsonHandler({ createProcessor }) - const handler = createHandler({}, t) + const handler = await createHandler({}, t) const data = await handler(event) t.snapshot(data, 'handler') })