/** * Effect `Persistence` backed by the Vercel Runtime Cache, so a * `PersistedCache` shares results across Function instances in a region. * * Outside Vercel, `getCache` falls back to an in-memory cache, so the same * layer works in local dev and tests. * * @example * ```ts * import * as RuntimeCache from "effect-vercel/RuntimeCache" * import { Effect } from "effect" * import { PersistedCache } from "effect/persistence" * * const program = Effect.gen(function* () { * const users = yield* PersistedCache.make(fetchUser, { * storeId: "users", * timeToLive: () => "1 hour", * }) * return yield* users.get(new GetUser({ id: 1 })) * }).pipe(Effect.scoped, Effect.provide(RuntimeCache.layer)) * ``` */ import { createHash } from "node:crypto" import { getCache, type RuntimeCache } from "@vercel/functions" import { Duration, Effect, Layer } from "effect" import { Persistence } from "effect/persistence" const sha256 = (key: string) => createHash("sha256").update(key).digest("hex") /** * A `BackingPersistence` over `cache`. * * Entries are keyed by the JSON pair `[storeId, key]`, so no two stores share * a key. Each entry is tagged with a hash of the store id, since tags are * joined with `,` and sent unescaped, and `clear` expires that tag. Entries * are sent without a name, so keys don't reach Vercel's o11y or the request * headers, where non-Latin-1 characters would make the write fail. TTLs round * up to whole seconds, the cache's resolution. * * Each call runs in a `RuntimeCache.` client span with the store * id, and `get` records whether it hit. Keys stay out of span attributes and * error messages, which a failed span exports. * * `getCache()` hashes keys with a 32-bit hash by default, which can collide. * Pass a cache made with a stronger `keyHashFunction`, as `layerBacking` does. */ export const makeBacking = (cache: RuntimeCache): Persistence.BackingPersistence["Service"] => Persistence.BackingPersistence.of({ make: (storeId) => Effect.sync(() => { const prefixed = (key: string) => JSON.stringify([storeId, key]) const tag = `effect-persistence:${sha256(storeId)}` const traced = (operation: string) => Effect.withSpan(`RuntimeCache.${operation}`, { kind: "client", attributes: { "cache.store_id": storeId }, }) const get = (key: string) => Effect.tryPromise({ try: () => cache.get(prefixed(key)), catch: (cause) => new Persistence.PersistenceError({ message: `Failed to get an entry in ${storeId}`, cause, }), }).pipe( Effect.map((value) => typeof value === "object" && value !== null ? value : undefined, ), Effect.tap((value) => Effect.annotateCurrentSpan("cache.hit", value !== undefined)), traced("get"), ) const set = (key: string, value: object, ttl: Duration.Duration | undefined) => Effect.tryPromise({ try: () => cache.set(prefixed(key), value, { name: "", tags: [tag], ...(ttl && { ttl: Math.max(1, Math.ceil(Duration.toSeconds(ttl))) }), }), catch: (cause) => new Persistence.PersistenceError({ message: `Failed to set an entry in ${storeId}`, cause, }), }).pipe(traced("set")) return { get, getMany: (keys) => Effect.forEach(keys, get, { concurrency: "unbounded" }), set, // Writes run concurrently, so keep only the last entry for each key. setMany: (entries) => Effect.forEach( new Map(entries.map(([key, value, ttl]) => [key, [value, ttl] as const])), ([key, [value, ttl]]) => set(key, value, ttl), { concurrency: "unbounded", discard: true }, ), remove: (key) => Effect.tryPromise({ try: () => cache.delete(prefixed(key)), catch: (cause) => new Persistence.PersistenceError({ message: `Failed to remove an entry in ${storeId}`, cause, }), }).pipe(traced("remove")), clear: Effect.tryPromise({ try: () => cache.expireTag(tag), catch: (cause) => new Persistence.PersistenceError({ message: `Failed to clear ${storeId}`, cause }), }).pipe(traced("clear")), } }), }) /** `BackingPersistence` over `getCache()`, with SHA-256 key hashing. */ export const layerBacking: Layer.Layer = Layer.sync( Persistence.BackingPersistence, )(() => makeBacking(getCache({ keyHashFunction: sha256 }))) /** `Persistence` backed by the Vercel Runtime Cache. */ export const layer: Layer.Layer = Persistence.layer.pipe( Layer.provide(layerBacking), )