From 5897c5ec7c3ee2db6e1a3b053d079180e1b590d0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 17:12:15 +0000 Subject: [PATCH 1/4] Add @pegma/cache-redis and pass conformance on real Redis. Phase 2 lands a generic Redis CacheStore adapter with clock-driven TTL, a sidecar tag index, and no implicit multi-key commands. CI keeps the Phase 1 Node matrix and adds a Redis service job. Co-authored-by: Fly Over Coder --- .github/workflows/ci.yml | 43 +++ .github/workflows/publish.yml | 13 + AGENTS.md | 13 +- CONTRIBUTING.md | 1 + README.md | 12 +- docs/PROJECT_PLAN.md | 26 +- docs/RELEASING.md | 24 +- package.json | 3 +- packages/cache-redis/LICENSE | 21 ++ packages/cache-redis/README.md | 41 +++ packages/cache-redis/package.json | 44 +++ packages/cache-redis/src/index.test.ts | 229 ++++++++++++++ packages/cache-redis/src/index.ts | 395 +++++++++++++++++++++++++ packages/cache-redis/tsconfig.json | 12 + pnpm-lock.yaml | 86 ++++++ scripts/release-packages.mjs | 4 + tests/redis-server.ts | 82 +++++ tests/release-packages.test.ts | 50 ++++ tsconfig.json | 3 +- tsconfig.test.json | 5 +- vitest.config.ts | 2 +- vitest.redis.config.ts | 9 + 22 files changed, 1083 insertions(+), 35 deletions(-) create mode 100644 packages/cache-redis/LICENSE create mode 100644 packages/cache-redis/README.md create mode 100644 packages/cache-redis/package.json create mode 100644 packages/cache-redis/src/index.test.ts create mode 100644 packages/cache-redis/src/index.ts create mode 100644 packages/cache-redis/tsconfig.json create mode 100644 tests/redis-server.ts create mode 100644 vitest.redis.config.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 888dd75..084f293 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,3 +48,46 @@ jobs: - name: Run tests run: pnpm test + + redis: + name: Redis adapter · Node.js ${{ matrix.node-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: + - 22 + - 24 + + services: + redis: + image: redis:7.4-alpine + ports: + - 16379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Set up pnpm + uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0 + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: ${{ matrix.node-version }} + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Check types + run: pnpm run check + + - name: Run Redis adapter tests + run: pnpm run test:redis diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e6d0b62..cb4acf7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,6 +17,16 @@ concurrency: jobs: prepare: runs-on: ubuntu-latest + services: + redis: + image: redis:7.4-alpine + ports: + - 16379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 env: RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} @@ -71,6 +81,9 @@ jobs: - name: Run tests run: pnpm test + - name: Run Redis adapter tests + run: pnpm run test:redis + - name: Prepare and verify release tarballs run: pnpm run release:pack -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release diff --git a/AGENTS.md b/AGENTS.md index ee69bba..5526ac5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,6 +46,8 @@ unbounded in-process map as a fallback when the remote cache is down. **No vendor clients in application code.** Adapters wrap Redis, Azure Cache, ElastiCache, or Upstash. Hosts depend on `CacheStore`. Do not create an adapter package until implementation begins and a named consumer exists. +`@pegma/cache-redis` exists because RetireGolden.org and Exsimplify are +named future hosts. **This is not durable state.** Persistence, optimistic concurrency, and transactions belong in `@pegma/storage-core`. A cache miss is not data loss. @@ -71,7 +73,9 @@ when pnpm set it, or pack/publish silently go through pnpm. Work on a `claude/*` branch and open a pull request. The gate is `pnpm run format:check`, `pnpm run check`, `pnpm test` — all three, on Node 22 -and 24. +and 24. Changes to `@pegma/cache-redis` also run `pnpm run test:redis` +against a real Redis (CI starts one; locally `redis-server` on port 16379 +or a service already bound there). Publishing is trusted-publisher only; no tokens exist. A release starts from a protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by @@ -79,10 +83,9 @@ protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by ## Where things stand -Phase 1: `@pegma/cache-core` (ports, codecs, `formatCacheKey`, single-flight -helper, in-memory store) and `@pegma/cache-conformance` (executable suite). -Redis / Azure Redis / ElastiCache / Upstash adapters are later phases — do -not create those packages here yet. +Phase 2: `@pegma/cache-core`, `@pegma/cache-conformance`, and +`@pegma/cache-redis` (generic Redis adapter). Azure Redis / ElastiCache / +Upstash adapters are later phases — do not create those packages here yet. Siblings: [spine](https://github.com/pegma-dev/spine), [storage-core](https://github.com/pegma-dev/storage-core), diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 423a380..7c15f0e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,6 +22,7 @@ corepack enable pnpm install --frozen-lockfile pnpm run check pnpm test +pnpm run test:redis pnpm run format:check ``` diff --git a/README.md b/README.md index 47835f4..301ca49 100644 --- a/README.md +++ b/README.md @@ -35,13 +35,14 @@ and a conformance suite every adapter must pass. | ---------------------------- | ----------------------------------------- | ----- | | `@pegma/cache-core` | Port, codecs, single-flight, memory store | 1 | | `@pegma/cache-conformance` | Executable suite every adapter must pass | 1 | -| `@pegma/cache-redis` | Generic Redis adapter | later | +| `@pegma/cache-redis` | Generic Redis adapter | 2 | | `@pegma/cache-azure-redis` | Azure Cache for Redis adapter | later | | `@pegma/cache-elasticache` | Amazon ElastiCache adapter | later | | `@pegma/cache-upstash-redis` | Upstash Redis adapter | later | -Adapter packages are not created until implementation begins and a named -consumer exists. +`@pegma/cache-redis` is the generic Redis adapter. Intended future hosts: +RetireGolden.org and Exsimplify. Remaining adapter packages wait until +implementation begins and a named consumer exists. ## Constraint that shapes everything @@ -66,8 +67,13 @@ pnpm install --frozen-lockfile pnpm run format:check pnpm run check pnpm test +pnpm run test:redis ``` +`pnpm test` is the Phase 1 gate and does not need Redis. `pnpm run test:redis` +starts a local `redis-server` on port 16379 when that port is free, or uses +whatever is already listening there. + ## License [MIT](LICENSE) © 2026 RetireGolden, LLC diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index a394e41..080482c 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,8 +2,9 @@ ## Status -**Stage:** Phase 1 — ports, in-memory store, and the conformance suite. -Nothing is published. (`0.1.0`, unpublished.) +**Stage:** Phase 2 — generic Redis adapter, in-tree, unpublished. +`@pegma/cache-core`, `@pegma/cache-conformance`, and `@pegma/cache-redis` +are `0.1.0` and not published. **License:** MIT @@ -94,10 +95,10 @@ those land with a later adapter, named, tested, and never smuggled into ### No adapter package without a consumer -The Pegma rule: do not create `cache-redis`, `cache-azure-redis`, -`cache-elasticache`, or `cache-upstash-redis` until implementation begins -and a named consumer exists. Phase 1 ships the port, the memory store, and -the suite those adapters will have to pass. +The Pegma rule: do not create an adapter package until implementation +begins and a named consumer exists. Phase 2 creates `@pegma/cache-redis` +because RetireGolden.org and Exsimplify are named future hosts. +`cache-azure-redis`, `cache-elasticache`, and `cache-upstash-redis` wait. ### Vendor clients stay behind the port @@ -125,7 +126,8 @@ local composition never take a network client. - **Unbounded local memory fallbacks when a remote cache is down.** Fail-open computes; it does not accumulate. - **Vendor clients in application code.** -- **Redis / Azure Redis / ElastiCache / Upstash packages in Phase 1.** +- **Azure Redis / ElastiCache / Upstash packages in Phase 2.** + Those remain later phases. ## Package architecture @@ -143,17 +145,19 @@ Dependencies: `@pegma/spine` pinned exactly. Conformance pins ## Delivery phases -### Phase 1 — port, memory store, conformance (this PR) +### Phase 1 — port, memory store, conformance `CacheStore`, codecs, `formatCacheKey`, single-flight `getOrCompute` helper, in-memory store, and the suite cases listed above. The in-memory store is the first adapter and must pass. -### Phase 2 — generic Redis adapter +### Phase 2 — generic Redis adapter (this PR) `@pegma/cache-redis` against a real empty Redis (or a faithful local -server). Created only when implementation begins and a consumer exists. -Must pass `@pegma/cache-conformance`. +server). Created because RetireGolden.org and Exsimplify are named future +hosts. Must pass `@pegma/cache-conformance`. Expiry stays on the injected +Clock; tag invalidation uses a sidecar index and never implies a +multi-key command. ### Phase 3 — Azure Cache for Redis diff --git a/docs/RELEASING.md b/docs/RELEASING.md index f54c756..5810429 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,17 +1,17 @@ # Release operations -`@pegma/cache-core` and `@pegma/cache-conformance` publish only from a -stable GitHub release. Merging a pull request never publishes, and the -workflow has no manual-dispatch or npm-token fallback. +`@pegma/cache-core`, `@pegma/cache-conformance`, and `@pegma/cache-redis` +publish only from a stable GitHub release. Merging a pull request never +publishes, and the workflow has no manual-dispatch or npm-token fallback. ## Required external configuration Before the first release through this workflow: -- configure `@pegma/cache-core` and `@pegma/cache-conformance` on npm with - the GitHub Actions trusted publisher `pegma-dev/cache-core`, workflow - `publish.yml`, environment `npm-publish`, and allowed action - `npm publish`; +- configure `@pegma/cache-core`, `@pegma/cache-conformance`, and + `@pegma/cache-redis` on npm with the GitHub Actions trusted publisher + `pegma-dev/cache-core`, workflow `publish.yml`, environment `npm-publish`, + and allowed action `npm publish`; - create the GitHub `npm-publish` environment. A second reviewer is not required under Pegma's single-maintainer policy; - create the repository Actions variable `RELEASE_ALLOWED_SIGNERS` containing @@ -26,10 +26,12 @@ remaining traditional npm publish tokens. ## Release procedure -The version in `packages/cache-core/package.json` and -`packages/cache-conformance/package.json` is the release version. Both -public packages publish at the same version. Change it through an ordinary -reviewed pull request and run the complete gate on Node 22 and 24. +The version in `packages/cache-core/package.json`, +`packages/cache-conformance/package.json`, and +`packages/cache-redis/package.json` is the release version. All public +packages publish at the same version. Change it through an ordinary +reviewed pull request and run the complete gate on Node 22 and 24, +including `pnpm run test:redis`. After that pull request is merged, create a signed annotated tag at the exact `origin/main` commit, push the tag, verify the fetched tag, and only then diff --git a/package.json b/package.json index 2de6033..c7c2c3f 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,8 @@ "release:check": "node scripts/release-packages.mjs check", "release:pack": "node scripts/release-packages.mjs pack", "release:publish": "node scripts/release-packages.mjs publish", - "test": "pnpm run build && vitest run" + "test": "pnpm run build && vitest run", + "test:redis": "pnpm run build && vitest run --config vitest.redis.config.ts" }, "devDependencies": { "@types/node": "^26.1.1", diff --git a/packages/cache-redis/LICENSE b/packages/cache-redis/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/cache-redis/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 RetireGolden, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/cache-redis/README.md b/packages/cache-redis/README.md new file mode 100644 index 0000000..8187192 --- /dev/null +++ b/packages/cache-redis/README.md @@ -0,0 +1,41 @@ +# `@pegma/cache-redis` + +Generic Redis adapter for [`@pegma/cache-core`](https://github.com/pegma-dev/cache-core). +Intended future hosts: RetireGolden.org and Exsimplify. + +> [!IMPORTANT] +> Pegma is in early `0.x` development. This package's public API is unstable. + +```ts +import { createControllableClock, jsonCodec } from "@pegma/cache-core"; +import { createRedisCacheStore } from "@pegma/cache-redis"; +import Redis from "ioredis"; + +const clock = createControllableClock("2026-08-15T16:00:00.000Z"); +const cache = createRedisCacheStore({ + clock, + redis: new Redis(process.env.REDIS_URL ?? "redis://127.0.0.1:6379"), +}); +const codec = jsonCodec(); + +const result = await cache.getOrCompute( + { namespace: "sessions", key: "abc", hashTag: "user-1" }, + { + codec, + ttl: { absoluteMs: 60_000 }, + fallback: "fail-open", + compute: () => loadSession(), + }, +); +``` + +Hosts depend on `CacheStore`. Construct the Redis client at the composition +root and hand it to this adapter; application code does not import `ioredis`. + +TTL, sliding refresh, and XFetch read the injected Spine `Clock`. Redis +`EXPIRE` is not the source of truth, so a test clock can pin expiry. Tag +invalidation uses a sidecar index in Redis — one key at a time, never an +implicit multi-key command. Hash tags stay formatting: `{tag}` in the wire +key from `formatCacheKey`. + +This adapter passes `@pegma/cache-conformance` against a real Redis. diff --git a/packages/cache-redis/package.json b/packages/cache-redis/package.json new file mode 100644 index 0000000..958a7e6 --- /dev/null +++ b/packages/cache-redis/package.json @@ -0,0 +1,44 @@ +{ + "name": "@pegma/cache-redis", + "version": "0.1.0", + "description": "Generic Redis adapter for @pegma/cache-core.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/cache-core.git", + "directory": "packages/cache-redis" + }, + "dependencies": { + "@pegma/cache-core": "0.1.0", + "@pegma/spine": "0.1.2", + "ioredis": "^5.8.2" + }, + "devDependencies": { + "@pegma/cache-conformance": "0.1.0" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run build" + } +} diff --git a/packages/cache-redis/src/index.test.ts b/packages/cache-redis/src/index.test.ts new file mode 100644 index 0000000..9eec66a --- /dev/null +++ b/packages/cache-redis/src/index.test.ts @@ -0,0 +1,229 @@ +import Redis from "ioredis"; +import { afterAll, describe, expect, it } from "vitest"; + +import { createControllableClock, jsonCodec } from "@pegma/cache-core"; +import { conformanceCases } from "@pegma/cache-conformance"; +import { noopLogger } from "@pegma/spine"; + +import { REDIS_URL } from "../../../tests/redis-server.js"; +import { createRedisCacheStore, type RedisCacheClient } from "./index.js"; + +const START = "2026-08-15T16:00:00.000Z"; + +const redis = new Redis(REDIS_URL, { + maxRetriesPerRequest: 1, + enableOfflineQueue: false, +}); + +afterAll(async () => { + await redis.quit(); +}); + +let prefixCounter = 0; + +function nextPrefix(): string { + prefixCounter += 1; + return `pegma-cache:t${String(process.pid)}:${String(prefixCounter)}:`; +} + +function unavailableRedis(): RedisCacheClient { + const down = new Error("cache backend unavailable"); + const reject = async (): Promise => { + throw down; + }; + return { + getBuffer: reject, + set: reject, + del: reject, + sadd: reject, + srem: reject, + smembers: reject, + ping: reject, + }; +} + +describe("createRedisCacheStore", () => { + for (const testCase of conformanceCases) { + it(testCase.name, async () => { + const clock = createControllableClock(START); + const logger = noopLogger; + const keyPrefix = nextPrefix(); + await testCase.run({ + clock, + logger, + createStore: () => + createRedisCacheStore({ clock, logger, redis, keyPrefix }), + createUnavailableStore: () => + createRedisCacheStore({ + clock, + logger, + redis: unavailableRedis(), + keyPrefix, + }), + }); + }); + } +}); + +describe("Redis adapter guarantees", () => { + it("shares entries and tag index across store handles", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const first = createRedisCacheStore({ clock, redis, keyPrefix }); + const second = createRedisCacheStore({ clock, redis, keyPrefix }); + const codec = jsonCodec(); + const address = { namespace: "ns", key: "shared" }; + await first.set(address, "value", codec, { tags: ["group"] }); + expect(await second.get(address, codec)).toMatchObject({ + status: "hit", + value: "value", + }); + expect(await second.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 1, + }); + expect(await first.get(address, codec)).toEqual({ status: "miss" }); + }); + + it("does not let a later tag-array mutation poison the index", async () => { + const clock = createControllableClock(START); + const store = createRedisCacheStore({ + clock, + redis, + keyPrefix: nextPrefix(), + }); + const codec = jsonCodec(); + const address = { namespace: "tags", key: "row" }; + const tags = ["group"]; + await store.set(address, "v1", codec, { tags }); + tags[0] = "mutated"; + await store.delete(address); + await store.set(address, "v2", codec); + expect(await store.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 0, + }); + expect(await store.get(address, codec)).toMatchObject({ + status: "hit", + value: "v2", + }); + }); + + it("keeps the previous entry indexed when encode throws", async () => { + const clock = createControllableClock(START); + const store = createRedisCacheStore({ + clock, + redis, + keyPrefix: nextPrefix(), + }); + const codec = jsonCodec(); + const address = { namespace: "tags", key: "row" }; + await store.set(address, "v1", codec, { tags: ["group"] }); + const exploding: typeof codec = { + encode() { + throw new Error("cannot encode"); + }, + decode() { + throw new Error("unused"); + }, + }; + await expect( + store.set(address, "v2", exploding, { tags: ["other"] }), + ).rejects.toThrow("cannot encode"); + expect(await store.get(address, codec)).toMatchObject({ + status: "hit", + value: "v1", + }); + expect(await store.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 1, + }); + expect(await store.get(address, codec)).toEqual({ status: "miss" }); + }); + + it("treats delete of an expired entry as a miss and purges it", async () => { + const clock = createControllableClock(START); + const store = createRedisCacheStore({ + clock, + redis, + keyPrefix: nextPrefix(), + }); + const codec = jsonCodec(); + const address = { namespace: "ttl", key: "stale" }; + await store.set(address, "old", codec, { + ttl: { absoluteMs: 1_000 }, + tags: ["group"], + }); + clock.advance(1_000); + expect(await store.delete(address)).toEqual({ + status: "hit", + value: false, + }); + expect(await store.get(address, codec)).toEqual({ status: "miss" }); + expect(await store.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 0, + }); + }); + + it("recomputes under XFetch when the random draw says so", async () => { + const clock = createControllableClock(START); + const store = createRedisCacheStore({ + clock, + redis, + keyPrefix: nextPrefix(), + random: () => 0.5, + }); + const codec = jsonCodec(); + const address = { namespace: "xfetch", key: "hot" }; + let computes = 0; + const first = await store.getOrCompute(address, { + codec, + ttl: { absoluteMs: 60_000 }, + earlyExpiration: { beta: 1 }, + compute: () => { + computes += 1; + clock.advance(50); + return `v${String(computes)}`; + }, + }); + expect(first).toMatchObject({ status: "hit", value: "v1" }); + clock.advance(59_980); + const second = await store.getOrCompute(address, { + codec, + ttl: { absoluteMs: 60_000 }, + earlyExpiration: { beta: 1 }, + compute: () => { + computes += 1; + return `v${String(computes)}`; + }, + }); + expect(computes).toBe(2); + expect(second).toMatchObject({ status: "hit", value: "v2" }); + }); + + it("keeps the CacheKey hash tag as the first brace pair on the wire", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const store = createRedisCacheStore({ clock, redis, keyPrefix }); + const codec = jsonCodec(); + await store.set( + { namespace: "sessions", key: "one", hashTag: "user-1" }, + "tagged", + codec, + ); + expect( + await redis.getBuffer(`${keyPrefix}e:{user-1}sessions:one`), + ).not.toBeNull(); + }); + + it("rejects a keyPrefix that would steal the hash tag", () => { + expect(() => + createRedisCacheStore({ + clock: createControllableClock(START), + redis, + keyPrefix: "pre{fix}:", + }), + ).toThrow(/braces/u); + }); +}); diff --git a/packages/cache-redis/src/index.ts b/packages/cache-redis/src/index.ts new file mode 100644 index 0000000..503f9fe --- /dev/null +++ b/packages/cache-redis/src/index.ts @@ -0,0 +1,395 @@ +import { + createSingleFlight, + formatCacheKey, + runGetOrCompute, + type CacheDependencies, + type CacheGetOrComputeOptions, + type CacheKey, + type CacheResult, + type CacheStore, + type CacheTtl, +} from "@pegma/cache-core"; +import { + noopLogger, + type Clock, + type IsoTimestamp, + type Logger, +} from "@pegma/spine"; + +/** + * Narrow Redis command surface this adapter needs. `ioredis` satisfies it; + * hosts construct the client at the composition root. + */ +export interface RedisCacheClient { + getBuffer(key: string): Promise; + set(key: string, value: Buffer): Promise; + del(...keys: string[]): Promise; + sadd(key: string, ...members: string[]): Promise; + srem(key: string, ...members: string[]): Promise; + smembers(key: string): Promise; + ping(): Promise; +} + +export interface RedisCacheStoreOptions extends CacheDependencies { + readonly redis: RedisCacheClient; + /** + * Prepended to entry and tag-index keys. Must not contain `{` or `}` so a + * `CacheKey.hashTag` remains the first hash tag in the wire key. + * Defaults to `pegma-cache:`. + */ + readonly keyPrefix?: string; +} + +const ENVELOPE_VERSION = 1; +const DEFAULT_PREFIX = "pegma-cache:"; + +interface RedisEntry { + bytes: Uint8Array; + tags: readonly string[]; + absoluteDeadlineMs: number | null; + slidingMs: number | null; + expiresAtMs: number | null; + lastComputeMs: number; +} + +function clockMs(clock: Clock): number { + return Date.parse(clock.now()); +} + +function toIso(ms: number): IsoTimestamp { + return new Date(ms).toISOString() as IsoTimestamp; +} + +function logOutcome( + logger: Logger, + status: "hit" | "miss" | "error" | "compute", + namespace: string, +): void { + logger.log("info", `cache.${status}`, { namespace, status }); +} + +function ttlDeadlines( + nowMs: number, + ttl: CacheTtl | undefined, +): Pick { + const absoluteMs = ttl?.absoluteMs; + const slidingMs = ttl?.slidingMs; + const absoluteDeadlineMs = + absoluteMs === undefined ? null : nowMs + absoluteMs; + const sliding = slidingMs === undefined ? null : slidingMs; + let expiresAtMs: number | null = null; + if (absoluteDeadlineMs !== null && sliding !== null) { + expiresAtMs = Math.min(absoluteDeadlineMs, nowMs + sliding); + } else if (absoluteDeadlineMs !== null) { + expiresAtMs = absoluteDeadlineMs; + } else if (sliding !== null) { + expiresAtMs = nowMs + sliding; + } + return { absoluteDeadlineMs, slidingMs: sliding, expiresAtMs }; +} + +function refreshSliding(entry: RedisEntry, nowMs: number): boolean { + if (entry.slidingMs === null) { + return false; + } + let next = nowMs + entry.slidingMs; + if (entry.absoluteDeadlineMs !== null) { + next = Math.min(next, entry.absoluteDeadlineMs); + } + if (entry.expiresAtMs === next) { + return false; + } + entry.expiresAtMs = next; + return true; +} + +function requirePrefix(value: string | undefined): string { + const prefix = value ?? DEFAULT_PREFIX; + if (prefix.includes("{") || prefix.includes("}")) { + throw new Error("keyPrefix must not contain braces"); + } + return prefix; +} + +function encodeEnvelope(entry: RedisEntry): Buffer { + const meta = new TextEncoder().encode( + JSON.stringify({ + tags: entry.tags, + absoluteDeadlineMs: entry.absoluteDeadlineMs, + slidingMs: entry.slidingMs, + expiresAtMs: entry.expiresAtMs, + lastComputeMs: entry.lastComputeMs, + }), + ); + const out = Buffer.allocUnsafe(5 + meta.length + entry.bytes.length); + out[0] = ENVELOPE_VERSION; + out.writeUInt32BE(meta.length, 1); + out.set(meta, 5); + out.set(entry.bytes, 5 + meta.length); + return out; +} + +function asFiniteOrNull(value: unknown): number | null { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} + +function decodeEnvelope(raw: Uint8Array): RedisEntry { + if (raw.length < 5 || raw[0] !== ENVELOPE_VERSION) { + throw new Error("invalid cache envelope"); + } + const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength); + const metaLen = view.getUint32(1, false); + if (raw.length < 5 + metaLen) { + throw new Error("invalid cache envelope"); + } + const parsed: unknown = JSON.parse( + new TextDecoder().decode(raw.subarray(5, 5 + metaLen)), + ); + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error("invalid cache envelope"); + } + const meta = parsed as Record; + const tags = meta["tags"]; + if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== "string")) { + throw new Error("invalid cache envelope"); + } + const lastComputeMs = meta["lastComputeMs"]; + if (typeof lastComputeMs !== "number" || !Number.isFinite(lastComputeMs)) { + throw new Error("invalid cache envelope"); + } + return { + bytes: raw.subarray(5 + metaLen).slice(), + tags: [...tags], + absoluteDeadlineMs: asFiniteOrNull(meta["absoluteDeadlineMs"]), + slidingMs: asFiniteOrNull(meta["slidingMs"]), + expiresAtMs: asFiniteOrNull(meta["expiresAtMs"]), + lastComputeMs, + }; +} + +function isExpired(entry: RedisEntry, nowMs: number): boolean { + return entry.expiresAtMs !== null && nowMs >= entry.expiresAtMs; +} + +/** + * {@link CacheStore} backed by a generic Redis. Expiry is clock-driven. + * Tag membership lives in a sidecar set per tag so invalidation does not + * scan and does not issue an implicit multi-key command. + */ +export function createRedisCacheStore( + options: RedisCacheStoreOptions, +): CacheStore { + const clock = options.clock; + const logger = options.logger ?? noopLogger; + const random = options.random ?? Math.random; + const redis = options.redis; + const prefix = requirePrefix(options.keyPrefix); + const singleFlight = createSingleFlight(); + + function entryKey(formatted: string): string { + return `${prefix}e:${formatted}`; + } + + function tagKey(tag: string): string { + return `${prefix}t:${tag}`; + } + + async function forgetTags( + formatted: string, + tags: readonly string[], + ): Promise { + for (const tag of tags) { + await redis.srem(tagKey(tag), formatted); + } + } + + async function rememberTags( + formatted: string, + tags: readonly string[], + ): Promise { + for (const tag of tags) { + await redis.sadd(tagKey(tag), formatted); + } + } + + async function readEntry(formatted: string): Promise { + const raw = await redis.getBuffer(entryKey(formatted)); + if (raw === null) { + return null; + } + return decodeEnvelope(raw); + } + + async function writeEntry( + formatted: string, + entry: RedisEntry, + ): Promise { + await redis.set(entryKey(formatted), encodeEnvelope(entry)); + } + + async function purge(formatted: string, entry: RedisEntry): Promise { + await redis.del(entryKey(formatted)); + await forgetTags(formatted, entry.tags); + } + + const store: CacheStore = { + async get(key, codec) { + const formatted = formatCacheKey(key); + try { + let entry: RedisEntry | null; + try { + entry = await readEntry(formatted); + } catch (error) { + await redis.del(entryKey(formatted)); + logOutcome(logger, "error", key.namespace); + return { status: "error", error }; + } + const nowMs = clockMs(clock); + if (entry === null || isExpired(entry, nowMs)) { + if (entry !== null) { + await purge(formatted, entry); + } + logOutcome(logger, "miss", key.namespace); + return { status: "miss" }; + } + if (refreshSliding(entry, nowMs)) { + await writeEntry(formatted, entry); + } + try { + const value = codec.decode(entry.bytes); + const hit: CacheResult = { + status: "hit", + value, + ...(entry.expiresAtMs === null + ? {} + : { expiresAt: toIso(entry.expiresAtMs) }), + ...(entry.lastComputeMs > 0 + ? { lastComputeMs: entry.lastComputeMs } + : {}), + }; + logOutcome(logger, "hit", key.namespace); + return hit; + } catch (error) { + await purge(formatted, entry); + logOutcome(logger, "error", key.namespace); + return { status: "error", error }; + } + } catch (error) { + logOutcome(logger, "error", key.namespace); + return { status: "error", error }; + } + }, + + async set(key, value, codec, setOptions) { + const formatted = formatCacheKey(key); + const nowMs = clockMs(clock); + const bytes = codec.encode(value).slice(); + const tags = [...(setOptions?.tags ?? [])]; + const deadlines = ttlDeadlines(nowMs, setOptions?.ttl); + try { + let previous: RedisEntry | null; + try { + previous = await readEntry(formatted); + } catch { + previous = null; + await redis.del(entryKey(formatted)); + } + if (previous !== null) { + await forgetTags(formatted, previous.tags); + } + await writeEntry(formatted, { + bytes, + tags, + lastComputeMs: setOptions?.lastComputeMs ?? 0, + ...deadlines, + }); + await rememberTags(formatted, tags); + return { status: "hit", value: true }; + } catch (error) { + return { status: "error", error }; + } + }, + + async delete(key) { + const formatted = formatCacheKey(key); + try { + const entry = await readEntry(formatted); + if (entry === null) { + return { status: "hit", value: false }; + } + const expired = isExpired(entry, clockMs(clock)); + await purge(formatted, entry); + return { status: "hit", value: !expired }; + } catch (error) { + return { status: "error", error }; + } + }, + + async getOrCompute( + key: CacheKey, + computeOptions: CacheGetOrComputeOptions, + ): Promise> { + return runGetOrCompute({ + key, + backend: store, + clock, + logger, + singleFlight, + random, + compute: computeOptions.compute, + codec: computeOptions.codec, + ...(computeOptions.ttl === undefined + ? {} + : { ttl: computeOptions.ttl }), + ...(computeOptions.tags === undefined + ? {} + : { tags: computeOptions.tags }), + ...(computeOptions.fallback === undefined + ? {} + : { fallback: computeOptions.fallback }), + ...(computeOptions.earlyExpiration === undefined + ? {} + : { earlyExpiration: computeOptions.earlyExpiration }), + }); + }, + + async invalidateTags(tags) { + try { + let removed = 0; + for (const tag of tags) { + const members = await redis.smembers(tagKey(tag)); + for (const formatted of members) { + let entry: RedisEntry | null; + try { + entry = await readEntry(formatted); + } catch { + await redis.del(entryKey(formatted)); + entry = null; + } + if (entry === null) { + continue; + } + await redis.del(entryKey(formatted)); + await forgetTags(formatted, entry.tags); + removed += 1; + } + await redis.del(tagKey(tag)); + } + return { status: "hit", value: removed }; + } catch (error) { + return { status: "error", error }; + } + }, + + async ping() { + try { + await redis.ping(); + return { status: "hit", value: true }; + } catch (error) { + return { status: "error", error }; + } + }, + }; + + return store; +} diff --git a/packages/cache-redis/tsconfig.json b/packages/cache-redis/tsconfig.json new file mode 100644 index 0000000..337ee68 --- /dev/null +++ b/packages/cache-redis/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"], + "references": [{ "path": "../cache-core" }] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dd5b46d..c41bad3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -36,8 +36,27 @@ importers: specifier: 0.1.2 version: 0.1.2 + packages/cache-redis: + dependencies: + '@pegma/cache-core': + specifier: 0.1.0 + version: link:../cache-core + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + ioredis: + specifier: ^5.8.2 + version: 5.11.1 + devDependencies: + '@pegma/cache-conformance': + specifier: 0.1.0 + version: link:../cache-conformance + packages: + '@ioredis/commands@1.10.0': + resolution: {integrity: sha512-UmeW7z4LfctwoQ5wkhVzgq8tXkreED2xZGpX+Bg+zA+WJFZCT6c062AfCK/Dfk81xZnnwdhJCUMkitihRaoC2Q==} + '@jridgewell/sourcemap-codec@1.5.5': resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} @@ -313,9 +332,26 @@ packages: resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} engines: {node: '>=18'} + cluster-key-slot@1.1.1: + resolution: {integrity: sha512-rwHwUfXL40Chm1r08yrhU3qpUvdVlgkKNeyeGPOxnW8/SyVDvgRaed/Uz54AqWNaTCAThlj6QAs3TZcKI0xDEw==} + engines: {node: '>=0.10.0'} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + denque@2.1.0: + resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==} + engines: {node: '>=0.10'} + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -344,6 +380,10 @@ packages: engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] + ioredis@5.11.1: + resolution: {integrity: sha512-ehuGcf94bQXhfagULNXrJdfnWO38v070jxSx/qE87Kjzmu2fU7ro5EFAb+OPituLqgfyuQaym5DlrNydW2sJ9A==} + engines: {node: '>=12.22.0'} + lightningcss-android-arm64@1.33.0: resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} engines: {node: '>= 12.0.0'} @@ -421,6 +461,9 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + nanoid@3.3.18: resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -449,6 +492,14 @@ packages: engines: {node: '>=14'} hasBin: true + redis-errors@1.2.0: + resolution: {integrity: sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==} + engines: {node: '>=4'} + + redis-parser@3.0.0: + resolution: {integrity: sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==} + engines: {node: '>=4'} + rolldown@1.2.4: resolution: {integrity: sha512-rSr7irW0K7QRWzjdJXqZowkcRdDtjRduh43rBltnVKd0VFq839l1lJoDvGJb6gl7+4rTTCrPWu+YfujUL8Ug7w==} engines: {node: ^20.19.0 || >=22.12.0} @@ -464,6 +515,9 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + standard-as-callback@2.1.0: + resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==} + std-env@4.2.0: resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==} @@ -581,6 +635,8 @@ packages: snapshots: + '@ioredis/commands@1.10.0': {} + '@jridgewell/sourcemap-codec@1.5.5': {} '@oxc-project/types@0.144.0': {} @@ -751,8 +807,16 @@ snapshots: chai@6.2.2: {} + cluster-key-slot@1.1.1: {} + convert-source-map@2.0.0: {} + debug@4.4.3: + dependencies: + ms: 2.1.3 + + denque@2.1.0: {} + detect-libc@2.1.2: {} es-module-lexer@2.3.1: {} @@ -770,6 +834,18 @@ snapshots: fsevents@2.3.3: optional: true + ioredis@5.11.1: + dependencies: + '@ioredis/commands': 1.10.0 + cluster-key-slot: 1.1.1 + debug: 4.4.3 + denque: 2.1.0 + redis-errors: 1.2.0 + redis-parser: 3.0.0 + standard-as-callback: 2.1.0 + transitivePeerDependencies: + - supports-color + lightningcss-android-arm64@1.33.0: optional: true @@ -823,6 +899,8 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 + ms@2.1.3: {} + nanoid@3.3.18: {} obug@2.1.4: {} @@ -841,6 +919,12 @@ snapshots: prettier@3.9.6: {} + redis-errors@1.2.0: {} + + redis-parser@3.0.0: + dependencies: + redis-errors: 1.2.0 + rolldown@1.2.4: dependencies: '@oxc-project/types': 0.144.0 @@ -867,6 +951,8 @@ snapshots: stackback@0.0.2: {} + standard-as-callback@2.1.0: {} + std-env@4.2.0: {} tinybench@2.9.0: {} diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 5d45f41..a60d325 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -33,6 +33,10 @@ export const RELEASE_PACKAGES = [ directory: "cache-conformance", name: "@pegma/cache-conformance", }, + { + directory: "cache-redis", + name: "@pegma/cache-redis", + }, ]; const RELEASE_NAMES = new Set(RELEASE_PACKAGES.map(({ name }) => name)); diff --git a/tests/redis-server.ts b/tests/redis-server.ts new file mode 100644 index 0000000..a8f58db --- /dev/null +++ b/tests/redis-server.ts @@ -0,0 +1,82 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { connect } from "node:net"; + +/** + * Runs a real Redis for the adapter suite, so conformance is verified against + * the protocol rather than a hand-written fake. + * + * The port is deliberately not Redis's default, so a developer already + * running Redis for something else does not collide with this. + */ +export const REDIS_PORT = 16379; +export const REDIS_URL = `redis://127.0.0.1:${String(REDIS_PORT)}`; + +let child: ChildProcess | undefined; +let inherited = false; + +function portAccepting(port: number): Promise { + return new Promise((resolve) => { + const socket = connect({ port, host: "127.0.0.1" }); + const settle = (accepting: boolean) => { + socket.destroy(); + resolve(accepting); + }; + socket.once("connect", () => settle(true)); + socket.once("error", () => settle(false)); + socket.setTimeout(1000, () => settle(false)); + }); +} + +async function waitForPort(port: number, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await portAccepting(port)) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 200)); + } + throw new Error( + `Redis did not start listening on port ${String(port)} within ${String(timeoutMs)}ms.`, + ); +} + +export async function setup(): Promise { + if (await portAccepting(REDIS_PORT)) { + inherited = true; + return; + } + + child = spawn( + "redis-server", + [ + "--port", + String(REDIS_PORT), + "--bind", + "127.0.0.1", + "--save", + "", + "--appendonly", + "no", + "--protected-mode", + "no", + ], + { stdio: "ignore" }, + ); + + child.once("error", (error) => { + throw new Error( + `Could not start redis-server on port ${String(REDIS_PORT)}. Install Redis or set a service on that port.`, + { cause: error }, + ); + }); + + await waitForPort(REDIS_PORT, 30_000); +} + +export async function teardown(): Promise { + if (inherited) { + return; + } + child?.kill(); + child = undefined; +} diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 73e2713..16f4d16 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -37,6 +37,7 @@ describe("release package metadata", () => { expect(RELEASE_PACKAGES.map(({ name }) => name)).toEqual([ "@pegma/cache-core", "@pegma/cache-conformance", + "@pegma/cache-redis", ]); }); @@ -57,9 +58,12 @@ describe("release package metadata", () => { expect(manifests.map(({ name, version }) => ({ name, version }))).toEqual([ { name: "@pegma/cache-core", version: "0.1.0" }, { name: "@pegma/cache-conformance", version: "0.1.0" }, + { name: "@pegma/cache-redis", version: "0.1.0" }, ]); expect(manifests[1]?.dependencies?.["@pegma/cache-core"]).toBe("0.1.0"); + expect(manifests[2]?.dependencies?.["@pegma/cache-core"]).toBe("0.1.0"); expect(manifests[0]?.dependencies?.["@pegma/spine"]).toBe("0.1.2"); + expect(manifests[2]?.dependencies?.["@pegma/spine"]).toBe("0.1.2"); expect(packageVersion).toBe("0.1.0"); }); @@ -105,6 +109,22 @@ describe("release package metadata", () => { specifier: 0.1.2 version: 0.1.2 + packages/cache-redis: + dependencies: + '@pegma/cache-core': + specifier: 0.1.0 + version: link:../cache-core + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + ioredis: + specifier: ^5.8.2 + version: 5.8.2 + devDependencies: + '@pegma/cache-conformance': + specifier: 0.1.0 + version: link:../cache-conformance + packages: prettier@3.9.6: resolution: {integrity: sha512-example} @@ -113,6 +133,7 @@ packages: ".", "packages/cache-core", "packages/cache-conformance", + "packages/cache-redis", ]); expect(importers["packages/cache-core"]).toEqual({ dependencies: { @@ -153,6 +174,33 @@ packages: { workspace: true }, ), ).toBe(true); + expect( + live["packages/cache-redis"]?.dependencies?.["@pegma/cache-core"], + ).toEqual({ + specifier: "0.1.0", + version: "link:../cache-core", + }); + expect( + lockDependencyMatches( + live["packages/cache-redis"]?.dependencies?.["@pegma/spine"], + "0.1.2", + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/cache-redis"]?.devDependencies?.[ + "@pegma/cache-conformance" + ], + "0.1.0", + { workspace: true }, + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/cache-redis"]?.dependencies?.ioredis, + "^5.8.2", + ), + ).toBe(true); }); it("matches each lockfile dependency to its own specifier and resolved version", () => { @@ -235,6 +283,8 @@ describe("release source authentication", () => { expect(prepare).not.toContain("id-token: write"); expect(prepare).toContain("npm install --global npm@11.18.0"); expect(prepare).toContain("pnpm run release:pack"); + expect(prepare).toContain("pnpm run test:redis"); + expect(prepare).toContain("16379:6379"); expect(publish).toContain("id-token: write"); expect(publish).not.toContain("npm ci"); expect(publish).toContain("npm install --global npm@11.18.0"); diff --git a/tsconfig.json b/tsconfig.json index ea19186..579455e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,7 @@ "files": [], "references": [ { "path": "./packages/cache-core" }, - { "path": "./packages/cache-conformance" } + { "path": "./packages/cache-conformance" }, + { "path": "./packages/cache-redis" } ] } diff --git a/tsconfig.test.json b/tsconfig.test.json index 6f0b9d8..0624380 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -10,7 +10,8 @@ }, "include": [ "packages/*/src/**/*.test.ts", - "tests/**/*.test.ts", - "vitest.config.ts" + "tests/**/*.ts", + "vitest.config.ts", + "vitest.redis.config.ts" ] } diff --git a/vitest.config.ts b/vitest.config.ts index a191fca..d106d21 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,6 +3,6 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ test: { include: ["packages/**/*.test.ts", "tests/**/*.test.ts"], - exclude: ["**/dist/**", "**/node_modules/**"], + exclude: ["**/dist/**", "**/node_modules/**", "packages/cache-redis/**"], }, }); diff --git a/vitest.redis.config.ts b/vitest.redis.config.ts new file mode 100644 index 0000000..aaa6ccf --- /dev/null +++ b/vitest.redis.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["packages/cache-redis/**/*.test.ts"], + exclude: ["**/dist/**", "**/node_modules/**"], + globalSetup: ["./tests/redis-server.ts"], + }, +}); From 153279a06e7f4e4a6875a072c9a207f2c14ae092 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 17:13:22 +0000 Subject: [PATCH 2/4] Wait for Redis readiness before the adapter suite. The ioredis client is now pinged in beforeAll, and get treats a corrupt envelope separately from a backend I/O failure. Co-authored-by: Fly Over Coder --- packages/cache-redis/README.md | 2 +- packages/cache-redis/src/index.test.ts | 9 ++++++--- packages/cache-redis/src/index.ts | 15 +++++++++------ 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/cache-redis/README.md b/packages/cache-redis/README.md index 8187192..5b4d5e9 100644 --- a/packages/cache-redis/README.md +++ b/packages/cache-redis/README.md @@ -9,7 +9,7 @@ Intended future hosts: RetireGolden.org and Exsimplify. ```ts import { createControllableClock, jsonCodec } from "@pegma/cache-core"; import { createRedisCacheStore } from "@pegma/cache-redis"; -import Redis from "ioredis"; +import { Redis } from "ioredis"; const clock = createControllableClock("2026-08-15T16:00:00.000Z"); const cache = createRedisCacheStore({ diff --git a/packages/cache-redis/src/index.test.ts b/packages/cache-redis/src/index.test.ts index 9eec66a..16d2c8c 100644 --- a/packages/cache-redis/src/index.test.ts +++ b/packages/cache-redis/src/index.test.ts @@ -1,5 +1,5 @@ -import Redis from "ioredis"; -import { afterAll, describe, expect, it } from "vitest"; +import { Redis } from "ioredis"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { createControllableClock, jsonCodec } from "@pegma/cache-core"; import { conformanceCases } from "@pegma/cache-conformance"; @@ -12,7 +12,10 @@ const START = "2026-08-15T16:00:00.000Z"; const redis = new Redis(REDIS_URL, { maxRetriesPerRequest: 1, - enableOfflineQueue: false, +}); + +beforeAll(async () => { + await redis.ping(); }); afterAll(async () => { diff --git a/packages/cache-redis/src/index.ts b/packages/cache-redis/src/index.ts index 503f9fe..93c9838 100644 --- a/packages/cache-redis/src/index.ts +++ b/packages/cache-redis/src/index.ts @@ -236,19 +236,22 @@ export function createRedisCacheStore( async get(key, codec) { const formatted = formatCacheKey(key); try { - let entry: RedisEntry | null; + const raw = await redis.getBuffer(entryKey(formatted)); + if (raw === null) { + logOutcome(logger, "miss", key.namespace); + return { status: "miss" }; + } + let entry: RedisEntry; try { - entry = await readEntry(formatted); + entry = decodeEnvelope(raw); } catch (error) { await redis.del(entryKey(formatted)); logOutcome(logger, "error", key.namespace); return { status: "error", error }; } const nowMs = clockMs(clock); - if (entry === null || isExpired(entry, nowMs)) { - if (entry !== null) { - await purge(formatted, entry); - } + if (isExpired(entry, nowMs)) { + await purge(formatted, entry); logOutcome(logger, "miss", key.namespace); return { status: "miss" }; } From 4e180fd4a6e2a357e10397f423b8ba80684d4e74 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 17:18:34 +0000 Subject: [PATCH 3/4] Fix Redis sliding refresh and stale tag-index races. Sliding get now compare-and-sets the envelope it read so a concurrent set is not restored. invalidateTags drops stale tag memberships instead of deleting an entry that no longer carries that tag. Co-authored-by: Fly Over Coder --- packages/cache-redis/src/index.test.ts | 115 +++++++++++++++++++++++++ packages/cache-redis/src/index.ts | 41 ++++++++- 2 files changed, 154 insertions(+), 2 deletions(-) diff --git a/packages/cache-redis/src/index.test.ts b/packages/cache-redis/src/index.test.ts index 16d2c8c..67e52f8 100644 --- a/packages/cache-redis/src/index.test.ts +++ b/packages/cache-redis/src/index.test.ts @@ -29,6 +29,28 @@ function nextPrefix(): string { return `pegma-cache:t${String(process.pid)}:${String(prefixCounter)}:`; } +function proxyRedis( + client: Redis, + hooks: { + afterGetBuffer?: () => Promise; + } = {}, +): RedisCacheClient { + return { + async getBuffer(key) { + const raw = await client.getBuffer(key); + await hooks.afterGetBuffer?.(); + return raw; + }, + set: (key, value) => client.set(key, value), + del: (...keys) => client.del(...keys), + sadd: (key, ...members) => client.sadd(key, ...members), + srem: (key, ...members) => client.srem(key, ...members), + smembers: (key) => client.smembers(key), + ping: () => client.ping(), + eval: (script, numKeys, ...args) => client.eval(script, numKeys, ...args), + }; +} + function unavailableRedis(): RedisCacheClient { const down = new Error("cache backend unavailable"); const reject = async (): Promise => { @@ -42,6 +64,7 @@ function unavailableRedis(): RedisCacheClient { srem: reject, smembers: reject, ping: reject, + eval: reject, }; } @@ -220,6 +243,98 @@ describe("Redis adapter guarantees", () => { ).not.toBeNull(); }); + it("does not let a sliding refresh restore a concurrently written value", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "ttl", key: "race" }; + const writer = createRedisCacheStore({ clock, redis, keyPrefix }); + await writer.set(address, "old", codec, { ttl: { slidingMs: 1_000 } }); + clock.advance(600); + + let releaseRead = (): void => {}; + const holdRead = new Promise((resolve) => { + releaseRead = resolve; + }); + let sawRead = (): void => {}; + const startedRead = new Promise((resolve) => { + sawRead = resolve; + }); + const reader = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { + async afterGetBuffer() { + sawRead(); + await holdRead; + }, + }), + keyPrefix, + }); + + const pending = reader.get(address, codec); + await startedRead; + await writer.set(address, "new", codec, { ttl: { slidingMs: 1_000 } }); + releaseRead(); + await pending; + expect(await writer.get(address, codec)).toMatchObject({ + status: "hit", + value: "new", + }); + }); + + it("does not delete a winning entry when a stale tag is invalidated", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "tags", key: "race" }; + + let reads = 0; + let releaseReads = (): void => {}; + const bothRead = new Promise((resolve) => { + releaseReads = resolve; + }); + const afterGetBuffer = async (): Promise => { + reads += 1; + if (reads === 2) { + releaseReads(); + } + await bothRead; + }; + + const first = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { afterGetBuffer }), + keyPrefix, + }); + const second = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { afterGetBuffer }), + keyPrefix, + }); + + await Promise.all([ + first.set(address, "alpha", codec, { tags: ["alpha"] }), + second.set(address, "beta", codec, { tags: ["beta"] }), + ]); + + const observer = createRedisCacheStore({ clock, redis, keyPrefix }); + const current = await observer.get(address, codec); + expect(current.status).toBe("hit"); + if (current.status !== "hit") { + return; + } + const winner = current.value; + const staleTag = winner === "alpha" ? "beta" : "alpha"; + expect(await observer.invalidateTags([staleTag])).toEqual({ + status: "hit", + value: 0, + }); + expect(await observer.get(address, codec)).toMatchObject({ + status: "hit", + value: winner, + }); + }); + it("rejects a keyPrefix that would steal the hash tag", () => { expect(() => createRedisCacheStore({ diff --git a/packages/cache-redis/src/index.ts b/packages/cache-redis/src/index.ts index 93c9838..1cb1a79 100644 --- a/packages/cache-redis/src/index.ts +++ b/packages/cache-redis/src/index.ts @@ -28,6 +28,15 @@ export interface RedisCacheClient { srem(key: string, ...members: string[]): Promise; smembers(key: string): Promise; ping(): Promise; + /** + * Single-key script runner. Used so a sliding refresh can replace only the + * envelope it read, without a multi-key command. + */ + eval( + script: string, + numKeys: number, + ...args: readonly (string | Buffer | number)[] + ): Promise; } export interface RedisCacheStoreOptions extends CacheDependencies { @@ -43,6 +52,15 @@ export interface RedisCacheStoreOptions extends CacheDependencies { const ENVELOPE_VERSION = 1; const DEFAULT_PREFIX = "pegma-cache:"; +/** Replace KEYS[1] only when it still equals the envelope this get read. */ +const COMPARE_AND_SET = ` +if redis.call('GET', KEYS[1]) == ARGV[1] then + redis.call('SET', KEYS[1], ARGV[2]) + return 1 +end +return 0 +`; + interface RedisEntry { bytes: Uint8Array; tags: readonly string[]; @@ -227,6 +245,21 @@ export function createRedisCacheStore( await redis.set(entryKey(formatted), encodeEnvelope(entry)); } + async function compareAndSetEntry( + formatted: string, + expected: Uint8Array, + next: RedisEntry, + ): Promise { + const replaced = await redis.eval( + COMPARE_AND_SET, + 1, + entryKey(formatted), + Buffer.from(expected), + encodeEnvelope(next), + ); + return replaced === 1; + } + async function purge(formatted: string, entry: RedisEntry): Promise { await redis.del(entryKey(formatted)); await forgetTags(formatted, entry.tags); @@ -256,7 +289,7 @@ export function createRedisCacheStore( return { status: "miss" }; } if (refreshSliding(entry, nowMs)) { - await writeEntry(formatted, entry); + await compareAndSetEntry(formatted, raw, entry); } try { const value = codec.decode(entry.bytes); @@ -370,13 +403,17 @@ export function createRedisCacheStore( entry = null; } if (entry === null) { + await redis.srem(tagKey(tag), formatted); + continue; + } + if (!entry.tags.includes(tag)) { + await redis.srem(tagKey(tag), formatted); continue; } await redis.del(entryKey(formatted)); await forgetTags(formatted, entry.tags); removed += 1; } - await redis.del(tagKey(tag)); } return { status: "hit", value: removed }; } catch (error) { From 68b081c9c5027aa48190bacbddc64090835b511d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 17:26:05 +0000 Subject: [PATCH 4/4] Report sliding expiry only after a successful CAS. A lost compare-and-set no longer mutates the in-memory envelope, so get does not advertise an extended expiresAt that Redis never stored. Co-authored-by: Fly Over Coder --- packages/cache-redis/src/index.test.ts | 43 ++++++++++++++++++++++++++ packages/cache-redis/src/index.ts | 17 +++++----- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/packages/cache-redis/src/index.test.ts b/packages/cache-redis/src/index.test.ts index 67e52f8..cc13c22 100644 --- a/packages/cache-redis/src/index.test.ts +++ b/packages/cache-redis/src/index.test.ts @@ -282,6 +282,49 @@ describe("Redis adapter guarantees", () => { }); }); + it("does not advertise a sliding TTL that the CAS did not persist", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "ttl", key: "cas-expiry" }; + const writer = createRedisCacheStore({ clock, redis, keyPrefix }); + await writer.set(address, "old", codec, { ttl: { slidingMs: 1_000 } }); + clock.advance(600); + + let releaseRead = (): void => {}; + const holdRead = new Promise((resolve) => { + releaseRead = resolve; + }); + let sawRead = (): void => {}; + const startedRead = new Promise((resolve) => { + sawRead = resolve; + }); + const reader = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { + async afterGetBuffer() { + sawRead(); + await holdRead; + }, + }), + keyPrefix, + }); + + const pending = reader.get(address, codec); + await startedRead; + await writer.set(address, "new", codec, { ttl: { absoluteMs: 5_000 } }); + releaseRead(); + const lost = await pending; + expect(lost).toMatchObject({ + status: "hit", + value: "old", + expiresAt: "2026-08-15T16:00:01.000Z", + }); + expect(lost).not.toMatchObject({ + expiresAt: "2026-08-15T16:00:01.600Z", + }); + }); + it("does not delete a winning entry when a stale tag is invalidated", async () => { const clock = createControllableClock(START); const keyPrefix = nextPrefix(); diff --git a/packages/cache-redis/src/index.ts b/packages/cache-redis/src/index.ts index 1cb1a79..9de354b 100644 --- a/packages/cache-redis/src/index.ts +++ b/packages/cache-redis/src/index.ts @@ -106,19 +106,18 @@ function ttlDeadlines( return { absoluteDeadlineMs, slidingMs: sliding, expiresAtMs }; } -function refreshSliding(entry: RedisEntry, nowMs: number): boolean { +function slidingRefreshExpiry(entry: RedisEntry, nowMs: number): number | null { if (entry.slidingMs === null) { - return false; + return null; } let next = nowMs + entry.slidingMs; if (entry.absoluteDeadlineMs !== null) { next = Math.min(next, entry.absoluteDeadlineMs); } if (entry.expiresAtMs === next) { - return false; + return null; } - entry.expiresAtMs = next; - return true; + return next; } function requirePrefix(value: string | undefined): string { @@ -288,8 +287,12 @@ export function createRedisCacheStore( logOutcome(logger, "miss", key.namespace); return { status: "miss" }; } - if (refreshSliding(entry, nowMs)) { - await compareAndSetEntry(formatted, raw, entry); + const refreshedExpiresAtMs = slidingRefreshExpiry(entry, nowMs); + if (refreshedExpiresAtMs !== null) { + const refreshed = { ...entry, expiresAtMs: refreshedExpiresAtMs }; + if (await compareAndSetEntry(formatted, raw, refreshed)) { + entry = refreshed; + } } try { const value = codec.decode(entry.bytes);