|
| 1 | +/** This file is an entry point for flags/utils, so its exports are public */ |
| 2 | +import type { EdgeConfigClient } from '@vercel/edge-config'; |
| 3 | +import { AsyncLocalStorage } from 'async_hooks'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Returns a patched version of the EdgeConfigClient that cache reads |
| 7 | + * for the duration of a request. |
| 8 | + * |
| 9 | + * Uses the headers as a cache key. |
| 10 | + */ |
| 11 | +export function createCachedEdgeConfigClient( |
| 12 | + edgeConfigClient: EdgeConfigClient, |
| 13 | +): { |
| 14 | + /** |
| 15 | + * A patched version of the Edge Config client, which only |
| 16 | + * reads Edge Config once per request and caches the result |
| 17 | + * for the duration of the request. |
| 18 | + */ |
| 19 | + client: EdgeConfigClient; |
| 20 | + run: <R>(headers: HeadersInit, fn: () => R) => R; |
| 21 | +} { |
| 22 | + const store = new AsyncLocalStorage<WeakKey>(); |
| 23 | + const cache = new WeakMap<WeakKey, Promise<unknown>>(); |
| 24 | + |
| 25 | + const patchedEdgeConfigClient: EdgeConfigClient = { |
| 26 | + ...edgeConfigClient, |
| 27 | + get: async <T>(key: string) => { |
| 28 | + const h = store.getStore(); |
| 29 | + if (h) { |
| 30 | + const cached = cache.get(h); |
| 31 | + if (cached) { |
| 32 | + return cached as Promise<T>; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + const promise = edgeConfigClient.get<T>(key); |
| 37 | + if (h) cache.set(h, promise); |
| 38 | + |
| 39 | + return promise; |
| 40 | + }, |
| 41 | + }; |
| 42 | + |
| 43 | + return { |
| 44 | + client: patchedEdgeConfigClient, |
| 45 | + // The "run" function puts the headers into the AsyncLocalStorage, which |
| 46 | + // allows the patchedEdgeConfigClient to read the headers without otherwise |
| 47 | + // having access to them. |
| 48 | + // |
| 49 | + // The patchedEdgeConfigClient then uses the headers as a cache key to |
| 50 | + // deduplicate Edge Config reads for the duration of a request. |
| 51 | + // |
| 52 | + // Performance wise it would actually be fine to read Edge Config on every |
| 53 | + // flag evaluation, but this would also cause a lot of unnecessary reads, |
| 54 | + // and as Edge Config is charged per read, this would cause unnecessary charges. |
| 55 | + // |
| 56 | + // So this approach helps with performance and ensures a fair usage of Edge Config. |
| 57 | + run: store.run.bind(store), |
| 58 | + }; |
| 59 | +} |
0 commit comments