From 0b76643d4075b218b8e225422b44339ec27448f2 Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Thu, 15 Oct 2026 13:19:34 -0400 Subject: [PATCH 1/2] perf: warm lambdas on page load and front-load cold-start setup Each cold start serially paid a Cognito JWKS fetch on the first verify() and a DB connect on the first query. warmAuth(db) does both in parallel; prewarm() kicks it off at module scope during Lambda init, and GET //health awaits it. The frontend pings all six /health endpoints once per page load (no-cors simple GET, no preflight), so containers are warm before the user navigates to them. Co-Authored-By: Claude Opus 5.5 --- apps/backend/lambdas/AGENTS.md | 4 ++- apps/backend/lambdas/auth/auth.ts | 9 +++++- apps/backend/lambdas/auth/handler.ts | 9 ++++-- apps/backend/lambdas/donors/auth.ts | 9 +++++- apps/backend/lambdas/donors/handler.ts | 9 ++++-- apps/backend/lambdas/expenditures/auth.ts | 9 +++++- apps/backend/lambdas/expenditures/handler.ts | 9 ++++-- apps/backend/lambdas/projects/auth.ts | 9 +++++- apps/backend/lambdas/projects/handler.ts | 9 ++++-- apps/backend/lambdas/reports/auth.ts | 9 +++++- apps/backend/lambdas/reports/handler.ts | 9 ++++-- apps/backend/lambdas/users/auth.ts | 9 +++++- apps/backend/lambdas/users/handler.ts | 9 ++++-- apps/frontend/src/app/providers.tsx | 5 ++- apps/frontend/src/lib/api.ts | 21 ++++++++++++ apps/frontend/test/lib/api.test.ts | 17 ++++++++++ shared/lambda-auth/src/authenticate.ts | 11 +++++++ shared/lambda-auth/src/index.ts | 2 +- shared/lambda-auth/test/authenticate.test.ts | 17 ++++++++++ shared/lambda-http/README.md | 7 ++-- shared/lambda-http/src/dispatch.ts | 3 +- shared/lambda-http/src/index.ts | 1 + shared/lambda-http/src/types.ts | 2 ++ shared/lambda-http/src/warmup.ts | 17 ++++++++++ shared/lambda-http/test/dispatch.test.ts | 23 +++++++++++++ shared/lambda-http/test/warmup.test.ts | 34 ++++++++++++++++++++ 26 files changed, 242 insertions(+), 30 deletions(-) create mode 100644 shared/lambda-http/src/warmup.ts create mode 100644 shared/lambda-http/test/warmup.test.ts diff --git a/apps/backend/lambdas/AGENTS.md b/apps/backend/lambdas/AGENTS.md index ecbcc731..94b05300 100644 --- a/apps/backend/lambdas/AGENTS.md +++ b/apps/backend/lambdas/AGENTS.md @@ -50,7 +50,7 @@ export const getDonor: RouteHandler = async ({ params }) => { return json(200, { ... }); }; ``` -- `dispatch()` handles OPTIONS preflight, `GET //health`, 404 and 500 centrally — routes.ts only lists real endpoints. +- `dispatch()` handles OPTIONS preflight, `GET //health` (after awaiting `warmup`), 404 and 500 centrally — routes.ts only lists real endpoints. - **A caught error is an error Sentry cannot see.** The Sentry layer wraps the handler and records uncaught throws only, and we always catch so API Gateway returns a JSON 500 instead of a 502. `dispatch()` reports what reaches its catch; a controller that returns its own 500 must use `serverError(err, 'Failed to …')` from `@branch/lambda-http` rather than `console.error` + `json(500, …)`. Same status to the caller, one less invisible failure. - **NEVER remove or modify the `ROUTES-START` / `ROUTES-END` markers** — the CLI inserts new table entries between them. - Patterns are always full-prefixed (`/donors/:id`, never `/:id`) so one table works whether the event arrives via API Gateway's `{proxy+}` (full path) or the shared dev-server (prefix stripped) — `dispatch()` canonicalizes both to the prefixed form. @@ -77,6 +77,8 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (ctx) => load `handler.ts` hands `resolveAuth` to `dispatch`, which calls it **once per request**. +`auth.ts` also exports `warmup = () => warmAuth(db)` (Cognito JWKS + DB connection). `handler.ts` wraps it in `prewarm()` at module scope, so the work starts during Lambda init, and passes it to `dispatch` as `warmup`. `GET //health` waits for it, and the frontend pings every service's `/health` on page load (`warmServices` in `apps/frontend/src/lib/api.ts`) to absorb cold starts early. + ### Two layers, and which one to use 1. **Route level** — declared in `routes.ts`, enforced by `dispatch` before the diff --git a/apps/backend/lambdas/auth/auth.ts b/apps/backend/lambdas/auth/auth.ts index d5f3b4c8..3cac124f 100644 --- a/apps/backend/lambdas/auth/auth.ts +++ b/apps/backend/lambdas/auth/auth.ts @@ -1,4 +1,8 @@ -import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; +import { + authenticateRequest as _authenticateRequest, + loadRbacSubject, + warmAuth, +} from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; import { db } from '@branch/store'; @@ -17,3 +21,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ +export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/auth/handler.ts b/apps/backend/lambdas/auth/handler.ts index 0ff9f22a..eb4a3f3f 100644 --- a/apps/backend/lambdas/auth/handler.ts +++ b/apps/backend/lambdas/auth/handler.ts @@ -1,6 +1,9 @@ -import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { dispatch, prewarm } from '@branch/lambda-http'; +import { resolveAuth, warmup } from './auth'; import { routes } from './routes'; +// Module scope, so it starts during init rather than on the first request. +const warm = prewarm(warmup); + export const handler = (event: any) => - dispatch(event, { prefix: 'auth', routes, resolveAuth }); + dispatch(event, { prefix: 'auth', routes, resolveAuth, warmup: warm }); diff --git a/apps/backend/lambdas/donors/auth.ts b/apps/backend/lambdas/donors/auth.ts index d5f3b4c8..3cac124f 100644 --- a/apps/backend/lambdas/donors/auth.ts +++ b/apps/backend/lambdas/donors/auth.ts @@ -1,4 +1,8 @@ -import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; +import { + authenticateRequest as _authenticateRequest, + loadRbacSubject, + warmAuth, +} from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; import { db } from '@branch/store'; @@ -17,3 +21,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ +export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/donors/handler.ts b/apps/backend/lambdas/donors/handler.ts index 7eb83925..11bbabcd 100644 --- a/apps/backend/lambdas/donors/handler.ts +++ b/apps/backend/lambdas/donors/handler.ts @@ -1,6 +1,9 @@ -import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { dispatch, prewarm } from '@branch/lambda-http'; +import { resolveAuth, warmup } from './auth'; import { routes } from './routes'; +// Module scope, so it starts during init rather than on the first request. +const warm = prewarm(warmup); + export const handler = (event: any) => - dispatch(event, { prefix: 'donors', routes, resolveAuth }); + dispatch(event, { prefix: 'donors', routes, resolveAuth, warmup: warm }); diff --git a/apps/backend/lambdas/expenditures/auth.ts b/apps/backend/lambdas/expenditures/auth.ts index d5f3b4c8..3cac124f 100644 --- a/apps/backend/lambdas/expenditures/auth.ts +++ b/apps/backend/lambdas/expenditures/auth.ts @@ -1,4 +1,8 @@ -import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; +import { + authenticateRequest as _authenticateRequest, + loadRbacSubject, + warmAuth, +} from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; import { db } from '@branch/store'; @@ -17,3 +21,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ +export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/expenditures/handler.ts b/apps/backend/lambdas/expenditures/handler.ts index 1d933824..a237b5e6 100644 --- a/apps/backend/lambdas/expenditures/handler.ts +++ b/apps/backend/lambdas/expenditures/handler.ts @@ -1,6 +1,9 @@ -import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { dispatch, prewarm } from '@branch/lambda-http'; +import { resolveAuth, warmup } from './auth'; import { routes } from './routes'; +// Module scope, so it starts during init rather than on the first request. +const warm = prewarm(warmup); + export const handler = (event: any) => - dispatch(event, { prefix: 'expenditures', routes, resolveAuth }); \ No newline at end of file + dispatch(event, { prefix: 'expenditures', routes, resolveAuth, warmup: warm }); diff --git a/apps/backend/lambdas/projects/auth.ts b/apps/backend/lambdas/projects/auth.ts index d5f3b4c8..3cac124f 100644 --- a/apps/backend/lambdas/projects/auth.ts +++ b/apps/backend/lambdas/projects/auth.ts @@ -1,4 +1,8 @@ -import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; +import { + authenticateRequest as _authenticateRequest, + loadRbacSubject, + warmAuth, +} from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; import { db } from '@branch/store'; @@ -17,3 +21,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ +export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/projects/handler.ts b/apps/backend/lambdas/projects/handler.ts index 5ac4f62e..65631987 100644 --- a/apps/backend/lambdas/projects/handler.ts +++ b/apps/backend/lambdas/projects/handler.ts @@ -1,6 +1,9 @@ -import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { dispatch, prewarm } from '@branch/lambda-http'; +import { resolveAuth, warmup } from './auth'; import { routes } from './routes'; +// Module scope, so it starts during init rather than on the first request. +const warm = prewarm(warmup); + export const handler = (event: any) => - dispatch(event, { prefix: 'projects', routes, resolveAuth }); + dispatch(event, { prefix: 'projects', routes, resolveAuth, warmup: warm }); diff --git a/apps/backend/lambdas/reports/auth.ts b/apps/backend/lambdas/reports/auth.ts index d5f3b4c8..3cac124f 100644 --- a/apps/backend/lambdas/reports/auth.ts +++ b/apps/backend/lambdas/reports/auth.ts @@ -1,4 +1,8 @@ -import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; +import { + authenticateRequest as _authenticateRequest, + loadRbacSubject, + warmAuth, +} from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; import { db } from '@branch/store'; @@ -17,3 +21,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ +export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/reports/handler.ts b/apps/backend/lambdas/reports/handler.ts index 160c9d75..602d2c6b 100644 --- a/apps/backend/lambdas/reports/handler.ts +++ b/apps/backend/lambdas/reports/handler.ts @@ -1,6 +1,9 @@ -import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { dispatch, prewarm } from '@branch/lambda-http'; +import { resolveAuth, warmup } from './auth'; import { routes } from './routes'; +// Module scope, so it starts during init rather than on the first request. +const warm = prewarm(warmup); + export const handler = (event: any) => - dispatch(event, { prefix: 'reports', routes, resolveAuth }); + dispatch(event, { prefix: 'reports', routes, resolveAuth, warmup: warm }); diff --git a/apps/backend/lambdas/users/auth.ts b/apps/backend/lambdas/users/auth.ts index d5f3b4c8..3cac124f 100644 --- a/apps/backend/lambdas/users/auth.ts +++ b/apps/backend/lambdas/users/auth.ts @@ -1,4 +1,8 @@ -import { authenticateRequest as _authenticateRequest, loadRbacSubject } from '@branch/lambda-auth'; +import { + authenticateRequest as _authenticateRequest, + loadRbacSubject, + warmAuth, +} from '@branch/lambda-auth'; import { createAuthResolver } from '@branch/lambda-http'; import { db } from '@branch/store'; @@ -17,3 +21,6 @@ export async function authenticateRequest( export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); + +/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ +export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/users/handler.ts b/apps/backend/lambdas/users/handler.ts index 0f8204f7..86dcea4d 100644 --- a/apps/backend/lambdas/users/handler.ts +++ b/apps/backend/lambdas/users/handler.ts @@ -1,6 +1,9 @@ -import { dispatch } from '@branch/lambda-http'; -import { resolveAuth } from './auth'; +import { dispatch, prewarm } from '@branch/lambda-http'; +import { resolveAuth, warmup } from './auth'; import { routes } from './routes'; +// Module scope, so it starts during init rather than on the first request. +const warm = prewarm(warmup); + export const handler = (event: any) => - dispatch(event, { prefix: 'users', routes, resolveAuth }); + dispatch(event, { prefix: 'users', routes, resolveAuth, warmup: warm }); diff --git a/apps/frontend/src/app/providers.tsx b/apps/frontend/src/app/providers.tsx index 2dbc6d9e..0bfceb21 100644 --- a/apps/frontend/src/app/providers.tsx +++ b/apps/frontend/src/app/providers.tsx @@ -1,10 +1,11 @@ 'use client'; -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { ChakraProvider, defaultSystem } from '@chakra-ui/react'; import { QueryClientProvider } from '@tanstack/react-query'; import { AuthProvider } from '@/context/AuthContext'; import { makeQueryClient } from '@/lib/queryClient'; +import { warmServices } from '@/lib/api'; import AuthGate from './components/AuthGate'; import RoutePrefetcher from './components/RoutePrefetcher'; @@ -21,6 +22,8 @@ export function Providers({ children }: { children: React.ReactNode }) { // user's cache into the next in tests and in any future SSR pass. const [queryClient] = useState(makeQueryClient); + useEffect(warmServices, []); + return ( diff --git a/apps/frontend/src/lib/api.ts b/apps/frontend/src/lib/api.ts index f68fec48..2d2d7b98 100644 --- a/apps/frontend/src/lib/api.ts +++ b/apps/frontend/src/lib/api.ts @@ -15,6 +15,27 @@ function resolveBaseUrl(path: string): string { return `http://localhost:${port}`; } +let servicesWarmed = false; + +/** + * Ping every service's `/health` once per page load, so the Lambdas cold-start + * while the user is still on the first screen instead of on each first visit. + * `/health` waits for the JWKS fetch and DB connection before answering. + * + * A bare GET with `no-cors` is a CORS "simple request": no preflight, and the + * opaque response is never read. + */ +export function warmServices(): void { + if (servicesWarmed) return; + servicesWarmed = true; + for (const service of Object.keys(SERVICE_PORTS)) { + const path = `/${service}/health`; + fetch(`${resolveBaseUrl(path)}${path}`, { mode: 'no-cors' }).catch( + () => {}, + ); + } +} + /** * A failed HTTP response, carrying the status so callers can branch on it. * diff --git a/apps/frontend/test/lib/api.test.ts b/apps/frontend/test/lib/api.test.ts index b9422120..e7e3b7fb 100644 --- a/apps/frontend/test/lib/api.test.ts +++ b/apps/frontend/test/lib/api.test.ts @@ -49,3 +49,20 @@ describe('apiFetch', () => { await expect(apiFetch('/auth/login')).rejects.toThrow('Bad Request'); }); }); + +describe('warmServices', () => { + it('pings every service health endpoint once, without a preflight', async () => { + const { warmServices } = await import('@/lib/api'); + global.fetch = jest.fn().mockResolvedValue({} as Response); + warmServices(); + warmServices(); + + const calls = (global.fetch as jest.Mock).mock.calls; + expect(calls.map(([url]) => new URL(url as string).pathname).sort()).toEqual( + ['auth', 'donors', 'expenditures', 'projects', 'reports', 'users'].map( + (s) => `/${s}/health`, + ), + ); + for (const [, init] of calls) expect(init).toEqual({ mode: 'no-cors' }); + }); +}); diff --git a/shared/lambda-auth/src/authenticate.ts b/shared/lambda-auth/src/authenticate.ts index 23fa96d8..af09d3b3 100644 --- a/shared/lambda-auth/src/authenticate.ts +++ b/shared/lambda-auth/src/authenticate.ts @@ -32,6 +32,17 @@ function getVerifier() { return verifier; } +/** + * Pay a cold start's two network setups up front: the Cognito JWKS fetch the + * first `verify()` would make, and the DB connection the first query would open. + */ +export async function warmAuth(db: QueryableDb): Promise { + await Promise.all([ + getVerifier().hydrate(), + db.selectFrom('branch.users').select('user_id').limit(1).execute(), + ]); +} + export function extractToken(event: any): string | null { const authHeader = event.headers?.Authorization || event.headers?.authorization; if (!authHeader) return null; diff --git a/shared/lambda-auth/src/index.ts b/shared/lambda-auth/src/index.ts index 5574d4c9..877144bc 100644 --- a/shared/lambda-auth/src/index.ts +++ b/shared/lambda-auth/src/index.ts @@ -1,5 +1,5 @@ export * from './types'; -export { extractToken, authenticateRequest } from './authenticate'; +export { extractToken, authenticateRequest, warmAuth } from './authenticate'; export { loadRbacSubject, preloadedSubject } from './rbac'; // The policy itself is re-exported so a lambda needs one import for auth and // authorization, the same way this package already re-exports the auth DTOs. diff --git a/shared/lambda-auth/test/authenticate.test.ts b/shared/lambda-auth/test/authenticate.test.ts index 19de2f8b..0e948d02 100644 --- a/shared/lambda-auth/test/authenticate.test.ts +++ b/shared/lambda-auth/test/authenticate.test.ts @@ -352,3 +352,20 @@ describe('authenticateRequest', () => { ); }); }); + +describe('warmAuth', () => { + it('hydrates the JWKS and opens the DB connection in parallel', async () => { + const hydrate = jest.fn().mockResolvedValue(undefined); + mockCreate.mockReturnValueOnce({ verify: mockVerify, hydrate } as any); + const execute = jest.fn().mockResolvedValue([]); + const chain = { select: () => chain, limit: () => chain, execute }; + const db = { selectFrom: jest.fn(() => chain) }; + + const { warmAuth } = await loadModule(); + await warmAuth(db); + + expect(hydrate).toHaveBeenCalledTimes(1); + expect(db.selectFrom).toHaveBeenCalledWith('branch.users'); + expect(execute).toHaveBeenCalledTimes(1); + }); +}); diff --git a/shared/lambda-http/README.md b/shared/lambda-http/README.md index bac61294..6dbf6476 100644 --- a/shared/lambda-http/README.md +++ b/shared/lambda-http/README.md @@ -49,7 +49,9 @@ the row is loaded. Paths are canonicalized to the prefixed form, so one table serves both. - **Authentication and the route's permission**, resolved once per request via `resolveAuth`. A controller that runs has already cleared its route's gate. -- OPTIONS preflight, `GET //health`, 404, and 500. +- OPTIONS preflight, `GET //health`, 404, and 500. Health awaits the + optional `warmup` first, so the frontend's load-time ping leaves a cold + container with its JWKS and DB connection ready. - CORS headers on every response, via `json`. - **Sentry reporting for the 500 path.** The Sentry Lambda layer wraps the handler and records *uncaught throws* only. Every lambda catches instead, so @@ -62,7 +64,8 @@ the row is loaded. | Export | Purpose | | --- | --- | -| `dispatch(event, { prefix, routes, resolveAuth })` | Route an event; returns a response. | +| `dispatch(event, { prefix, routes, resolveAuth, warmup })` | Route an event; returns a response. | +| `prewarm(warm)` | Start `warm` at module scope (Lambda only) and return the `warmup` health awaits. | | `json(status, body)` | JSON response with CORS headers. | | `parseBody(event)` | Parse a JSON body; `null` when malformed. | | `requirePermission(subject, action, resource?)` | 403 carrying the policy's own reason, or `undefined` when allowed. | diff --git a/shared/lambda-http/src/dispatch.ts b/shared/lambda-http/src/dispatch.ts index d54770db..a7575298 100644 --- a/shared/lambda-http/src/dispatch.ts +++ b/shared/lambda-http/src/dispatch.ts @@ -21,7 +21,7 @@ import type { DispatchOptions, RequestAuth, Route } from './types'; */ export async function dispatch( event: any, - { prefix, routes, resolveAuth }: DispatchOptions, + { prefix, routes, resolveAuth, warmup }: DispatchOptions, ): Promise { // Hoisted out of the try so the catch can name the route that failed. const rawPath: string = event?.rawPath || event?.path || '/'; @@ -42,6 +42,7 @@ export async function dispatch( if (method === 'OPTIONS') return json(200, {}); if (path === `${base}/health` && method === 'GET') { + await warmup?.(); return json(200, { ok: true, timestamp: new Date().toISOString() }); } diff --git a/shared/lambda-http/src/index.ts b/shared/lambda-http/src/index.ts index a3b5ff0f..bca73914 100644 --- a/shared/lambda-http/src/index.ts +++ b/shared/lambda-http/src/index.ts @@ -5,3 +5,4 @@ export { dispatch } from './dispatch'; export { parseBody } from './body'; export { requirePermission, createAuthResolver, ANONYMOUS_AUTH } from './authz'; export { reportError, serverError } from './errors'; +export { prewarm } from './warmup'; diff --git a/shared/lambda-http/src/types.ts b/shared/lambda-http/src/types.ts index 95f9270d..de7852f1 100644 --- a/shared/lambda-http/src/types.ts +++ b/shared/lambda-http/src/types.ts @@ -63,4 +63,6 @@ export interface DispatchOptions { * route without it. */ resolveAuth?: (event: any) => Promise; + /** Awaited by `//health`; build it with `prewarm`. */ + warmup?: () => Promise; } diff --git a/shared/lambda-http/src/warmup.ts b/shared/lambda-http/src/warmup.ts new file mode 100644 index 00000000..f0de0757 --- /dev/null +++ b/shared/lambda-http/src/warmup.ts @@ -0,0 +1,17 @@ +/** + * Start `warm` during Lambda init, so a cold container's network setup overlaps + * with the rest of init instead of queueing behind the first request. + * + * Returns the in-flight promise for `dispatch`'s `warmup` option, which `/health` + * awaits so a ping leaves the container fully warm before Lambda freezes it. + * Outside Lambda (tests, dev-server) it does nothing. A failure is logged, not + * retried: the first real request does the same work anyway. + */ +export function prewarm(warm: () => Promise): () => Promise { + if (!process.env.AWS_LAMBDA_FUNCTION_NAME) return async () => {}; + const pending = warm().then( + () => undefined, + (err) => console.warn('Warm-up failed:', err), + ); + return () => pending; +} diff --git a/shared/lambda-http/test/dispatch.test.ts b/shared/lambda-http/test/dispatch.test.ts index dc325e71..a865c288 100644 --- a/shared/lambda-http/test/dispatch.test.ts +++ b/shared/lambda-http/test/dispatch.test.ts @@ -112,6 +112,29 @@ describe('dispatch routing', () => { } }); + it('holds the health response until warmup settles', async () => { + let release!: () => void; + const warmup = jest.fn(() => new Promise((r) => (release = r))); + let settled = false; + const pending = dispatch(event('GET', '/projects/health'), { + prefix: 'projects', + routes, + warmup, + }).then((res) => ((settled = true), res)); + + await Promise.resolve(); + expect(warmup).toHaveBeenCalledTimes(1); + expect(settled).toBe(false); + release(); + expect((await pending).statusCode).toBe(200); + }); + + it('does not run warmup on ordinary routes', async () => { + const warmup = jest.fn(async () => {}); + await dispatch(event('GET', '/projects'), { ...opts(), warmup }); + expect(warmup).not.toHaveBeenCalled(); + }); + it('404s an unmatched path', async () => { const res = await dispatch(event('GET', '/projects/7/nope'), opts()); expect(res.statusCode).toBe(404); diff --git a/shared/lambda-http/test/warmup.test.ts b/shared/lambda-http/test/warmup.test.ts new file mode 100644 index 00000000..33f1094e --- /dev/null +++ b/shared/lambda-http/test/warmup.test.ts @@ -0,0 +1,34 @@ +import { prewarm } from '../src/warmup'; + +describe('prewarm', () => { + const original = process.env.AWS_LAMBDA_FUNCTION_NAME; + afterEach(() => { + if (original === undefined) delete process.env.AWS_LAMBDA_FUNCTION_NAME; + else process.env.AWS_LAMBDA_FUNCTION_NAME = original; + }); + + it('does nothing outside Lambda', async () => { + delete process.env.AWS_LAMBDA_FUNCTION_NAME; + const warm = jest.fn(async () => {}); + await prewarm(warm)(); + expect(warm).not.toHaveBeenCalled(); + }); + + it('starts immediately in Lambda and runs once', async () => { + process.env.AWS_LAMBDA_FUNCTION_NAME = 'branch-projects'; + const warm = jest.fn(async () => {}); + const run = prewarm(warm); + expect(warm).toHaveBeenCalledTimes(1); + await run(); + await run(); + expect(warm).toHaveBeenCalledTimes(1); + }); + + it('swallows a failure so health still answers', async () => { + process.env.AWS_LAMBDA_FUNCTION_NAME = 'branch-projects'; + const spy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + await expect(prewarm(async () => Promise.reject(new Error('boom')))()).resolves.toBeUndefined(); + expect(spy).toHaveBeenCalled(); + spy.mockRestore(); + }); +}); From 70d28fabe96274816abb620e7fb8f7136e6d14f1 Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Thu, 15 Oct 2026 13:21:12 -0400 Subject: [PATCH 2/2] chore: trim comments Co-Authored-By: Claude Opus 5.5 --- apps/backend/lambdas/auth/auth.ts | 1 - apps/backend/lambdas/donors/auth.ts | 1 - apps/backend/lambdas/expenditures/auth.ts | 1 - apps/backend/lambdas/projects/auth.ts | 1 - apps/backend/lambdas/reports/auth.ts | 1 - apps/backend/lambdas/users/auth.ts | 1 - apps/frontend/src/lib/api.ts | 9 +-------- shared/lambda-auth/src/authenticate.ts | 4 ---- shared/lambda-http/src/types.ts | 1 - shared/lambda-http/src/warmup.ts | 10 +--------- 10 files changed, 2 insertions(+), 28 deletions(-) diff --git a/apps/backend/lambdas/auth/auth.ts b/apps/backend/lambdas/auth/auth.ts index 3cac124f..de54099e 100644 --- a/apps/backend/lambdas/auth/auth.ts +++ b/apps/backend/lambdas/auth/auth.ts @@ -22,5 +22,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/donors/auth.ts b/apps/backend/lambdas/donors/auth.ts index 3cac124f..de54099e 100644 --- a/apps/backend/lambdas/donors/auth.ts +++ b/apps/backend/lambdas/donors/auth.ts @@ -22,5 +22,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/expenditures/auth.ts b/apps/backend/lambdas/expenditures/auth.ts index 3cac124f..de54099e 100644 --- a/apps/backend/lambdas/expenditures/auth.ts +++ b/apps/backend/lambdas/expenditures/auth.ts @@ -22,5 +22,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/projects/auth.ts b/apps/backend/lambdas/projects/auth.ts index 3cac124f..de54099e 100644 --- a/apps/backend/lambdas/projects/auth.ts +++ b/apps/backend/lambdas/projects/auth.ts @@ -22,5 +22,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/reports/auth.ts b/apps/backend/lambdas/reports/auth.ts index 3cac124f..de54099e 100644 --- a/apps/backend/lambdas/reports/auth.ts +++ b/apps/backend/lambdas/reports/auth.ts @@ -22,5 +22,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ export const warmup = () => warmAuth(db); diff --git a/apps/backend/lambdas/users/auth.ts b/apps/backend/lambdas/users/auth.ts index 3cac124f..de54099e 100644 --- a/apps/backend/lambdas/users/auth.ts +++ b/apps/backend/lambdas/users/auth.ts @@ -22,5 +22,4 @@ export const resolveAuth = createAuthResolver(authenticateRequest, (context) => loadRbacSubject(db, context), ); -/** JWKS + DB connection; handed to `prewarm` in handler.ts. */ export const warmup = () => warmAuth(db); diff --git a/apps/frontend/src/lib/api.ts b/apps/frontend/src/lib/api.ts index 2d2d7b98..be886c78 100644 --- a/apps/frontend/src/lib/api.ts +++ b/apps/frontend/src/lib/api.ts @@ -17,19 +17,12 @@ function resolveBaseUrl(path: string): string { let servicesWarmed = false; -/** - * Ping every service's `/health` once per page load, so the Lambdas cold-start - * while the user is still on the first screen instead of on each first visit. - * `/health` waits for the JWKS fetch and DB connection before answering. - * - * A bare GET with `no-cors` is a CORS "simple request": no preflight, and the - * opaque response is never read. - */ export function warmServices(): void { if (servicesWarmed) return; servicesWarmed = true; for (const service of Object.keys(SERVICE_PORTS)) { const path = `/${service}/health`; + // no-cors GET is a CORS simple request: no preflight. fetch(`${resolveBaseUrl(path)}${path}`, { mode: 'no-cors' }).catch( () => {}, ); diff --git a/shared/lambda-auth/src/authenticate.ts b/shared/lambda-auth/src/authenticate.ts index af09d3b3..eedd23a9 100644 --- a/shared/lambda-auth/src/authenticate.ts +++ b/shared/lambda-auth/src/authenticate.ts @@ -32,10 +32,6 @@ function getVerifier() { return verifier; } -/** - * Pay a cold start's two network setups up front: the Cognito JWKS fetch the - * first `verify()` would make, and the DB connection the first query would open. - */ export async function warmAuth(db: QueryableDb): Promise { await Promise.all([ getVerifier().hydrate(), diff --git a/shared/lambda-http/src/types.ts b/shared/lambda-http/src/types.ts index de7852f1..4c0adcd7 100644 --- a/shared/lambda-http/src/types.ts +++ b/shared/lambda-http/src/types.ts @@ -63,6 +63,5 @@ export interface DispatchOptions { * route without it. */ resolveAuth?: (event: any) => Promise; - /** Awaited by `//health`; build it with `prewarm`. */ warmup?: () => Promise; } diff --git a/shared/lambda-http/src/warmup.ts b/shared/lambda-http/src/warmup.ts index f0de0757..d554090e 100644 --- a/shared/lambda-http/src/warmup.ts +++ b/shared/lambda-http/src/warmup.ts @@ -1,12 +1,4 @@ -/** - * Start `warm` during Lambda init, so a cold container's network setup overlaps - * with the rest of init instead of queueing behind the first request. - * - * Returns the in-flight promise for `dispatch`'s `warmup` option, which `/health` - * awaits so a ping leaves the container fully warm before Lambda freezes it. - * Outside Lambda (tests, dev-server) it does nothing. A failure is logged, not - * retried: the first real request does the same work anyway. - */ +// /health awaits this so Lambda does not freeze the container mid-warm-up. export function prewarm(warm: () => Promise): () => Promise { if (!process.env.AWS_LAMBDA_FUNCTION_NAME) return async () => {}; const pending = warm().then(