|
| 1 | +// @ts-check |
| 2 | + |
| 3 | +// this is not TS file because it's used both directly inside test process |
| 4 | +// as well as child process that lacks TS on-the-fly transpilation |
| 5 | + |
| 6 | +import { join } from 'node:path' |
| 7 | +import { BLOB_TOKEN } from './constants.mjs' |
| 8 | +import { execute as untypedExecute } from 'lambda-local' |
| 9 | + |
| 10 | +const SERVER_HANDLER_NAME = '___netlify-server-handler' |
| 11 | + |
| 12 | +/** |
| 13 | + * @typedef {import('./contexts').FixtureTestContext} FixtureTestContext |
| 14 | + * |
| 15 | + * @typedef {Awaited<ReturnType<ReturnType<typeof import('@netlify/serverless-functions-api').getLambdaHandler>>>} LambdaResult |
| 16 | + * |
| 17 | + * @typedef {Object} FunctionInvocationOptions |
| 18 | + * @property {Record<string, string>} [env] Environment variables that should be set during the invocation |
| 19 | + * @property {string} [httpMethod] The http method that is used for the invocation. Defaults to 'GET' |
| 20 | + * @property {string} [url] TThe relative path that should be requested. Defaults to '/' |
| 21 | + * @property {Record<string, string>} [headers] The headers used for the invocation |
| 22 | + * @property {Record<string, unknown>} [flags] Feature flags that should be set during the invocation |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * This is helper to get LambdaLocal's execute to actually provide result type instead of `unknown` |
| 27 | + * Because jsdoc doesn't seem to have equivalent of `as` in TS and trying to assign `LambdaResult` type |
| 28 | + * to return value of `execute` leading to `Type 'unknown' is not assignable to type 'LambdaResult'` |
| 29 | + * error, this types it as `any` instead which allow to later type it as `LambdaResult`. |
| 30 | + * @param {Parameters<typeof untypedExecute>} args |
| 31 | + * @returns {Promise<LambdaResult>} |
| 32 | + */ |
| 33 | +async function execute(...args) { |
| 34 | + /** |
| 35 | + * @type {any} |
| 36 | + */ |
| 37 | + const anyResult = await untypedExecute(...args) |
| 38 | + |
| 39 | + return anyResult |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * @param {FixtureTestContext} ctx |
| 44 | + */ |
| 45 | +export const createBlobContext = (ctx) => |
| 46 | + Buffer.from( |
| 47 | + JSON.stringify({ |
| 48 | + edgeURL: `http://${ctx.blobStoreHost}`, |
| 49 | + uncachedEdgeURL: `http://${ctx.blobStoreHost}`, |
| 50 | + token: BLOB_TOKEN, |
| 51 | + siteID: ctx.siteID, |
| 52 | + deployID: ctx.deployID, |
| 53 | + primaryRegion: 'us-test-1', |
| 54 | + }), |
| 55 | + ).toString('base64') |
| 56 | + |
| 57 | +/** |
| 58 | + * Converts a readable stream to a buffer |
| 59 | + * @param {NodeJS.ReadableStream} stream |
| 60 | + * @returns {Promise<Buffer>} |
| 61 | + */ |
| 62 | +function streamToBuffer(stream) { |
| 63 | + /** |
| 64 | + * @type {Buffer[]} |
| 65 | + */ |
| 66 | + const chunks = [] |
| 67 | + |
| 68 | + return new Promise((resolve, reject) => { |
| 69 | + stream.on('data', (chunk) => chunks.push(Buffer.from(chunk))) |
| 70 | + stream.on('error', (err) => reject(err)) |
| 71 | + stream.on('end', () => resolve(Buffer.concat(chunks))) |
| 72 | + }) |
| 73 | +} |
| 74 | + |
| 75 | +/** |
| 76 | + * @param {FixtureTestContext} ctx |
| 77 | + * @param {Record<string, string>} [env] |
| 78 | + */ |
| 79 | +function temporarilySetEnv(ctx, env) { |
| 80 | + const environment = { |
| 81 | + NODE_ENV: 'production', |
| 82 | + NETLIFY_BLOBS_CONTEXT: createBlobContext(ctx), |
| 83 | + ...(env || {}), |
| 84 | + } |
| 85 | + |
| 86 | + const envVarsToRestore = {} |
| 87 | + |
| 88 | + // We are not using lambda-local's environment variable setting because it cleans up |
| 89 | + // environment vars to early (before stream is closed) |
| 90 | + Object.keys(environment).forEach(function (key) { |
| 91 | + if (typeof process.env[key] !== 'undefined') { |
| 92 | + envVarsToRestore[key] = process.env[key] |
| 93 | + } |
| 94 | + process.env[key] = environment[key] |
| 95 | + }) |
| 96 | + |
| 97 | + return function restoreEnvironment() { |
| 98 | + Object.keys(environment).forEach(function (key) { |
| 99 | + if (typeof envVarsToRestore[key] !== 'undefined') { |
| 100 | + process.env[key] = envVarsToRestore[key] |
| 101 | + } else { |
| 102 | + delete process.env[key] |
| 103 | + } |
| 104 | + }) |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +const DEFAULT_FLAGS = {} |
| 109 | + |
| 110 | +/** |
| 111 | + * @param {FixtureTestContext} ctx |
| 112 | + * @param {FunctionInvocationOptions} options |
| 113 | + */ |
| 114 | +export async function loadAndInvokeFunctionImpl( |
| 115 | + ctx, |
| 116 | + { headers, httpMethod, flags, url, env } = {}, |
| 117 | +) { |
| 118 | + const { handler } = await import( |
| 119 | + 'file:///' + join(ctx.functionDist, SERVER_HANDLER_NAME, '___netlify-entry-point.mjs') |
| 120 | + ) |
| 121 | + |
| 122 | + const restoreEnvironment = temporarilySetEnv(ctx, env) |
| 123 | + |
| 124 | + let resolveInvocation, rejectInvocation |
| 125 | + const invocationPromise = new Promise((resolve, reject) => { |
| 126 | + resolveInvocation = resolve |
| 127 | + rejectInvocation = reject |
| 128 | + }) |
| 129 | + |
| 130 | + const response = await execute({ |
| 131 | + event: { |
| 132 | + headers: { |
| 133 | + // 'x-nf-debug-logging': 1, |
| 134 | + ...(headers || {}), |
| 135 | + }, |
| 136 | + httpMethod: httpMethod || 'GET', |
| 137 | + rawUrl: new URL(url || '/', 'https://example.netlify').href, |
| 138 | + flags: flags ?? DEFAULT_FLAGS, |
| 139 | + }, |
| 140 | + lambdaFunc: { handler }, |
| 141 | + timeoutMs: 4_000, |
| 142 | + onInvocationEnd: (error) => { |
| 143 | + // lambda-local resolve promise return from execute when response is closed |
| 144 | + // but we should wait for tracked background work to finish |
| 145 | + // before resolving the promise to allow background work to finish |
| 146 | + if (error) { |
| 147 | + rejectInvocation(error) |
| 148 | + } else { |
| 149 | + resolveInvocation() |
| 150 | + } |
| 151 | + }, |
| 152 | + }) |
| 153 | + |
| 154 | + await invocationPromise |
| 155 | + |
| 156 | + if (!response) { |
| 157 | + throw new Error('No response from lambda-local') |
| 158 | + } |
| 159 | + |
| 160 | + const responseHeaders = Object.entries(response.multiValueHeaders || {}).reduce( |
| 161 | + (prev, [key, value]) => ({ |
| 162 | + ...prev, |
| 163 | + [key]: value.length === 1 ? `${value}` : value.join(', '), |
| 164 | + }), |
| 165 | + response.headers || {}, |
| 166 | + ) |
| 167 | + |
| 168 | + const bodyBuffer = await streamToBuffer(response.body) |
| 169 | + |
| 170 | + restoreEnvironment() |
| 171 | + |
| 172 | + return { |
| 173 | + statusCode: response.statusCode, |
| 174 | + bodyBuffer, |
| 175 | + body: bodyBuffer.toString('utf-8'), |
| 176 | + headers: responseHeaders, |
| 177 | + isBase64Encoded: response.isBase64Encoded, |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +/** |
| 182 | + * @typedef {typeof loadAndInvokeFunctionImpl} InvokeFunction |
| 183 | + * @typedef {Promise<Awaited<ReturnType<InvokeFunction>>>} InvokeFunctionResult |
| 184 | + */ |
0 commit comments