diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eeb7206..0c7a3d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -177,3 +177,46 @@ jobs: - name: Run ElastiCache adapter tests run: pnpm run test:elasticache + + upstash-redis: + name: Upstash 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 Upstash Redis adapter tests + run: pnpm run test:upstash-redis diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 8946178..f36114b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -90,6 +90,9 @@ jobs: - name: Run ElastiCache adapter tests run: pnpm run test:elasticache + - name: Run Upstash Redis adapter tests + run: pnpm run test:upstash-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 5cb344a..86b87d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,7 +78,9 @@ against a real Redis (CI starts one; locally `redis-server` on port 16379 or a service already bound there). Changes to `@pegma/cache-azure-redis` also run `pnpm run test:azure-redis` against the same Redis. Changes to `@pegma/cache-elasticache` also run `pnpm run test:elasticache` against -the same Redis. +the same Redis. Changes to `@pegma/cache-upstash-redis` also run +`pnpm run test:upstash-redis` against the same Redis through an injected +client that matches the Upstash REST command surface. 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 @@ -86,11 +88,11 @@ protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by ## Where things stand -Phase 4: `@pegma/cache-core`, `@pegma/cache-conformance`, -`@pegma/cache-redis`, `@pegma/cache-azure-redis`, and -`@pegma/cache-elasticache` (thin composition of the generic Redis -adapter; cluster hash-tag colocation is proven). The Upstash adapter is -a later phase — do not create that package here yet. +Phase 5: `@pegma/cache-core`, `@pegma/cache-conformance`, +`@pegma/cache-redis`, `@pegma/cache-azure-redis`, +`@pegma/cache-elasticache`, and `@pegma/cache-upstash-redis` (Upstash +REST/SDK client, reusing the generic Redis store after adapting the HTTP +command surface). Do not create further adapter packages here. 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 c372403..a8fbca3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,6 +25,7 @@ pnpm test pnpm run test:redis pnpm run test:azure-redis pnpm run test:elasticache +pnpm run test:upstash-redis pnpm run format:check ``` diff --git a/README.md b/README.md index 850a689..0e14f83 100644 --- a/README.md +++ b/README.md @@ -38,14 +38,15 @@ and a conformance suite every adapter must pass. | `@pegma/cache-redis` | Generic Redis adapter | 2 | | `@pegma/cache-azure-redis` | Azure Cache for Redis adapter | 3 | | `@pegma/cache-elasticache` | Amazon ElastiCache adapter | 4 | -| `@pegma/cache-upstash-redis` | Upstash Redis adapter | later | +| `@pegma/cache-upstash-redis` | Upstash Redis adapter | 5 | `@pegma/cache-redis` is the generic Redis adapter. `@pegma/cache-azure-redis` and `@pegma/cache-elasticache` are thin compositions of it: Azure Cache for Redis and ElastiCache speak Redis. -Intended future hosts: RetireGolden.org and Exsimplify. Remaining -adapter packages wait until implementation begins and a named consumer -exists. +`@pegma/cache-upstash-redis` wraps the Upstash serverless REST client +and reuses that store after adapting the HTTP command surface. Intended +future hosts: RetireGolden.org and Exsimplify. Do not create further +adapter packages here. ## Constraint that shapes everything @@ -73,12 +74,15 @@ pnpm test pnpm run test:redis pnpm run test:azure-redis pnpm run test:elasticache +pnpm run test:upstash-redis ``` `pnpm test` is the Phase 1 gate and does not need Redis. `pnpm run test:redis`, -`pnpm run test:azure-redis`, and `pnpm run test:elasticache` start a local -`redis-server` on port 16379 when that port is free, or use whatever is -already listening there. +`pnpm run test:azure-redis`, `pnpm run test:elasticache`, and +`pnpm run test:upstash-redis` start a local `redis-server` on port 16379 +when that port is free, or use whatever is already listening there. The +Upstash suite injects a REST-shaped client; `@upstash/redis` cannot speak +the Redis protocol to that service. ## License diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index c40c79e..19645d6 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,10 +2,10 @@ ## Status -**Stage:** Phase 4 — Amazon ElastiCache adapter, in-tree, unpublished. +**Stage:** Phase 5 — Upstash Redis adapter, in-tree, unpublished. `@pegma/cache-core`, `@pegma/cache-conformance`, `@pegma/cache-redis`, -`@pegma/cache-azure-redis`, and `@pegma/cache-elasticache` are `0.1.0` -and not published. +`@pegma/cache-azure-redis`, `@pegma/cache-elasticache`, and +`@pegma/cache-upstash-redis` are `0.1.0` and not published. **License:** MIT @@ -98,15 +98,16 @@ those land with a later adapter, named, tested, and never smuggled into The Pegma rule: do not create an adapter package until implementation begins and a named consumer exists. Phase 2 created `@pegma/cache-redis`, -Phase 3 created `@pegma/cache-azure-redis`, and Phase 4 creates -`@pegma/cache-elasticache` because RetireGolden.org and Exsimplify are -named future hosts. `cache-upstash-redis` waits. +Phase 3 created `@pegma/cache-azure-redis`, Phase 4 created +`@pegma/cache-elasticache`, and Phase 5 creates +`@pegma/cache-upstash-redis` because RetireGolden.org and Exsimplify are +named future hosts. ### Vendor clients stay behind the port Application code depends on `CacheStore`. An adapter may import `ioredis` -or a vendor SDK; a host must not. The memory store exists so tests and -local composition never take a network client. +or a vendor SDK such as `@upstash/redis`; a host must not. The memory +store exists so tests and local composition never take a network client. ## Scope @@ -128,8 +129,7 @@ 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.** -- **Upstash package in Phase 4.** - That remains a later phase. +- **Further adapter packages beyond Phase 5.** ## Package architecture @@ -167,7 +167,7 @@ Thin adapter over the same port. Azure Cache for Redis speaks Redis, so `@pegma/cache-azure-redis` composes `@pegma/cache-redis` rather than wrapping a data-plane Azure SDK. Real backend, same suite. -### Phase 4 — Amazon ElastiCache (this PR) +### Phase 4 — Amazon ElastiCache Thin adapter over the same port. ElastiCache speaks Redis, so `@pegma/cache-elasticache` composes `@pegma/cache-redis` rather than @@ -175,9 +175,16 @@ wrapping a data-plane AWS SDK. Cluster hash-tag behaviour is proven here, not implied: `formatCacheKey` embeds `{tag}`, and tagged wire keys share a Redis Cluster slot. Real backend, same suite. -### Phase 5 — Upstash Redis +### Phase 5 — Upstash Redis (this PR) -Thin adapter for the serverless Redis client. Same suite. +Thin adapter over the same port. Upstash's serverless client is HTTP +REST (`@upstash/redis`), not the ioredis TCP surface, so +`@pegma/cache-upstash-redis` wraps that client and reuses +`@pegma/cache-redis` store logic after adapting the REST command shape. +It does not pretend the HTTP client is ioredis, and it does not invent +implicit cross-partition multi-key ops. CI has no live Upstash; +conformance runs against an injected client that implements the Upstash +command surface and talks to the same Redis the other adapters use. ## Open questions diff --git a/docs/RELEASING.md b/docs/RELEASING.md index b833e06..d9ab1e0 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,8 +1,8 @@ # Release operations `@pegma/cache-core`, `@pegma/cache-conformance`, `@pegma/cache-redis`, -`@pegma/cache-azure-redis`, and `@pegma/cache-elasticache` publish only -from a stable GitHub release. +`@pegma/cache-azure-redis`, `@pegma/cache-elasticache`, and +`@pegma/cache-upstash-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. @@ -11,10 +11,11 @@ manual-dispatch or npm-token fallback. Before the first release through this workflow: - configure `@pegma/cache-core`, `@pegma/cache-conformance`, - `@pegma/cache-redis`, `@pegma/cache-azure-redis`, and - `@pegma/cache-elasticache` on npm with the GitHub Actions trusted - publisher `pegma-dev/cache-core`, workflow `publish.yml`, environment - `npm-publish`, and allowed action `npm publish`; + `@pegma/cache-redis`, `@pegma/cache-azure-redis`, + `@pegma/cache-elasticache`, and `@pegma/cache-upstash-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 @@ -32,12 +33,13 @@ remaining traditional npm publish tokens. The version in `packages/cache-core/package.json`, `packages/cache-conformance/package.json`, `packages/cache-redis/package.json`, -`packages/cache-azure-redis/package.json`, and -`packages/cache-elasticache/package.json` is the release version. All +`packages/cache-azure-redis/package.json`, +`packages/cache-elasticache/package.json`, and +`packages/cache-upstash-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`, `pnpm run test:azure-redis`, and -`pnpm run test:elasticache`. +including `pnpm run test:redis`, `pnpm run test:azure-redis`, +`pnpm run test:elasticache`, and `pnpm run test:upstash-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 cd1e3e5..aed5f22 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "test": "pnpm run build && vitest run", "test:redis": "pnpm run build && vitest run --config vitest.redis.config.ts", "test:azure-redis": "pnpm run build && vitest run --config vitest.azure-redis.config.ts", - "test:elasticache": "pnpm run build && vitest run --config vitest.elasticache.config.ts" + "test:elasticache": "pnpm run build && vitest run --config vitest.elasticache.config.ts", + "test:upstash-redis": "pnpm run build && vitest run --config vitest.upstash-redis.config.ts" }, "devDependencies": { "@types/node": "^26.1.1", diff --git a/packages/cache-upstash-redis/LICENSE b/packages/cache-upstash-redis/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/cache-upstash-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-upstash-redis/README.md b/packages/cache-upstash-redis/README.md new file mode 100644 index 0000000..812436a --- /dev/null +++ b/packages/cache-upstash-redis/README.md @@ -0,0 +1,53 @@ +# `@pegma/cache-upstash-redis` + +Upstash Redis adapter for [`@pegma/cache-core`](https://github.com/pegma-dev/cache-core). +Wraps the Upstash serverless Redis client (`@upstash/redis`): that client is +HTTP REST, not the ioredis TCP surface, so this package adapts the REST +command shape and reuses [`@pegma/cache-redis`](https://github.com/pegma-dev/cache-core/tree/main/packages/cache-redis) +store logic. It does not pretend the HTTP client is ioredis. 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 { createUpstashRedisCacheStore } from "@pegma/cache-upstash-redis"; +import { Redis } from "@upstash/redis"; + +const clock = createControllableClock("2026-08-15T16:00:00.000Z"); +const cache = createUpstashRedisCacheStore({ + clock, + redis: new Redis({ + url: process.env.UPSTASH_REDIS_REST_URL, + token: process.env.UPSTASH_REDIS_REST_TOKEN, + }), +}); +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 Upstash REST client at the +composition root and hand it to this adapter. Application code does not +import `@upstash/redis`. + +TTL, sliding refresh, and XFetch still read the injected Spine `Clock`. +Tag invalidation still uses a sidecar index — one key at a time — and +hash tags stay formatting. Envelopes travel as base64 strings because the +REST client is JSON-over-HTTP, not a binary Redis connection. + +This adapter passes `@pegma/cache-conformance`. CI has no live Upstash +account; the suite injects a client with the Upstash command surface +(`get` / `set` / `eval(script, keys, args)`) that talks to the same Redis +the other adapters use. Point `UPSTASH_REDIS_REST_URL` and +`UPSTASH_REDIS_REST_TOKEN` at a real Upstash database to run the same +cases through `@upstash/redis`. diff --git a/packages/cache-upstash-redis/package.json b/packages/cache-upstash-redis/package.json new file mode 100644 index 0000000..3e781a5 --- /dev/null +++ b/packages/cache-upstash-redis/package.json @@ -0,0 +1,46 @@ +{ + "name": "@pegma/cache-upstash-redis", + "version": "0.1.0", + "description": "Upstash 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-upstash-redis" + }, + "dependencies": { + "@pegma/cache-core": "0.1.0", + "@pegma/cache-redis": "0.1.0", + "@pegma/spine": "0.1.2", + "@upstash/redis": "^1.38.2" + }, + "devDependencies": { + "@pegma/cache-conformance": "0.1.0", + "ioredis": "^5.8.2" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run build" + } +} diff --git a/packages/cache-upstash-redis/src/index.test.ts b/packages/cache-upstash-redis/src/index.test.ts new file mode 100644 index 0000000..ad15e01 --- /dev/null +++ b/packages/cache-upstash-redis/src/index.test.ts @@ -0,0 +1,211 @@ +import { Redis } from "ioredis"; +import { Redis as UpstashRedis } from "@upstash/redis"; +import { afterAll, beforeAll, 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 { + createUpstashRedisCacheStore, + type UpstashRedisCacheClient, +} from "./index.js"; + +const START = "2026-08-15T16:00:00.000Z"; + +const tcp = new Redis(REDIS_URL, { + maxRetriesPerRequest: 1, +}); + +/** + * `@upstash/redis` speaks HTTP REST, not the Redis protocol, so it cannot + * use the CI Redis service. This stand-in is that client's command surface + * over the same Redis the other adapters use. A live Upstash pair in + * `UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` replaces it. + */ +function createRedisStandIn(client: Redis): UpstashRedisCacheClient { + return { + get: (key) => client.get(key), + set: (key, value) => client.set(key, String(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, keys, args) => + client.eval( + script, + keys.length, + ...keys, + ...args.map((arg) => { + if (typeof arg === "string" || typeof arg === "number") { + return arg; + } + return String(arg); + }), + ), + }; +} + +function createLiveUpstashClient(): UpstashRedisCacheClient | undefined { + const url = process.env.UPSTASH_REDIS_REST_URL; + const token = process.env.UPSTASH_REDIS_REST_TOKEN; + if (url === undefined || token === undefined || url === "" || token === "") { + return undefined; + } + return new UpstashRedis({ url, token }); +} + +const redis = createLiveUpstashClient() ?? createRedisStandIn(tcp); + +beforeAll(async () => { + await redis.ping(); +}); + +afterAll(async () => { + await tcp.quit(); +}); + +let prefixCounter = 0; + +function nextPrefix(): string { + prefixCounter += 1; + return `pegma-cache:up${String(process.pid)}:${String(prefixCounter)}:`; +} + +function unavailableUpstash(): UpstashRedisCacheClient { + const down = new Error("cache backend unavailable"); + const reject = async (): Promise => { + throw down; + }; + return { + get: reject, + set: reject, + del: reject, + sadd: reject, + srem: reject, + smembers: reject, + ping: reject, + eval: reject, + }; +} + +describe("createUpstashRedisCacheStore", () => { + 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: () => + createUpstashRedisCacheStore({ clock, logger, redis, keyPrefix }), + createUnavailableStore: () => + createUpstashRedisCacheStore({ + clock, + logger, + redis: unavailableUpstash(), + keyPrefix, + }), + }); + }); + } +}); + +describe("Upstash Redis adapter", () => { + it("accepts the @upstash/redis client type at the composition root", () => { + const client = new UpstashRedis({ + url: "https://example.upstash.io", + token: "test", + }); + expect(() => + createUpstashRedisCacheStore({ + clock: createControllableClock(START), + redis: client, + }), + ).not.toThrow(); + }); + + it("shares entries and tag index across store handles", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const first = createUpstashRedisCacheStore({ clock, redis, keyPrefix }); + const second = createUpstashRedisCacheStore({ 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("keeps the CacheKey hash tag as the first brace pair on the wire", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const store = createUpstashRedisCacheStore({ clock, redis, keyPrefix }); + const codec = jsonCodec(); + await store.set( + { namespace: "sessions", key: "one", hashTag: "user-1" }, + "tagged", + codec, + ); + expect( + await redis.get(`${keyPrefix}e:{user-1}sessions:one`), + ).not.toBeNull(); + }); + + it("calls eval with the Upstash keys-and-args signature", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "ttl", key: "slide" }; + let seen: { keys: string[]; args: unknown[] } | undefined; + const observing: UpstashRedisCacheClient = { + get: (key) => redis.get(key), + set: (key, value) => redis.set(key, value), + del: (...keys) => redis.del(...keys), + sadd: (key, ...members) => redis.sadd(key, ...members), + srem: (key, ...members) => redis.srem(key, ...members), + smembers: (key) => redis.smembers(key), + ping: () => redis.ping(), + async eval(script, keys, args) { + const argv = [...args]; + seen = { keys, args: argv }; + return redis.eval(script, keys, argv); + }, + }; + const store = createUpstashRedisCacheStore({ + clock, + redis: observing, + keyPrefix, + }); + await store.set(address, "old", codec, { ttl: { slidingMs: 1_000 } }); + clock.advance(600); + expect(await store.get(address, codec)).toMatchObject({ + status: "hit", + value: "old", + }); + expect(seen?.keys).toEqual([`${keyPrefix}e:ttl:slide`]); + expect(seen?.args).toHaveLength(2); + expect(typeof seen?.args[0]).toBe("string"); + expect(typeof seen?.args[1]).toBe("string"); + }); + + it("rejects a keyPrefix that would steal the hash tag", () => { + expect(() => + createUpstashRedisCacheStore({ + clock: createControllableClock(START), + redis, + keyPrefix: "pre{fix}:", + }), + ).toThrow(/braces/u); + }); +}); diff --git a/packages/cache-upstash-redis/src/index.ts b/packages/cache-upstash-redis/src/index.ts new file mode 100644 index 0000000..77901d1 --- /dev/null +++ b/packages/cache-upstash-redis/src/index.ts @@ -0,0 +1,108 @@ +import type { CacheDependencies, CacheStore } from "@pegma/cache-core"; +import { + createRedisCacheStore, + type RedisCacheClient, +} from "@pegma/cache-redis"; + +/** + * Narrow command surface of `@upstash/redis`. That client is HTTP REST, not + * the ioredis TCP surface; hosts construct it at the composition root. + * + * `eval` takes `(script, keys, args)` — not ioredis `(script, numKeys, ...)`. + */ +export interface UpstashRedisCacheClient { + get(key: string): Promise; + set(key: string, value: unknown): Promise; + del(...keys: string[]): Promise; + sadd(key: string, ...members: string[]): Promise; + srem(key: string, ...members: string[]): Promise; + smembers(key: string): Promise; + ping(): Promise; + eval( + script: string, + keys: string[], + args: readonly unknown[], + ): Promise; +} + +/** + * Same injected clock, logger, and optional key prefix as the generic Redis + * adapter. The client is the Upstash REST surface, not `RedisCacheClient`. + */ +export interface UpstashRedisCacheStoreOptions extends CacheDependencies { + readonly redis: UpstashRedisCacheClient; + /** + * 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; +} + +function asWireArg(value: string | Buffer | number): string { + if (typeof value === "number") { + return String(value); + } + if (typeof value === "string") { + return value; + } + return value.toString("base64"); +} + +/** + * REST/JSON cannot carry the binary envelope ioredis `getBuffer` / `set` + * use. Encode on the wire as base64 so Lua CAS still compares the same + * bytes the HTTP client stored. + */ +function adaptUpstashRedisClient( + redis: UpstashRedisCacheClient, +): RedisCacheClient { + return { + async getBuffer(key) { + const raw = await redis.get(key); + if (raw === null) { + return null; + } + if (typeof raw !== "string") { + throw new Error("invalid upstash envelope"); + } + return Buffer.from(raw, "base64"); + }, + set(key, value) { + return redis.set(key, value.toString("base64")); + }, + del: (...keys) => redis.del(...keys), + sadd: (key, ...members) => redis.sadd(key, ...members), + srem: (key, ...members) => redis.srem(key, ...members), + smembers: (key) => redis.smembers(key), + ping: () => redis.ping(), + eval(script, numKeys, ...args) { + const keys = args.slice(0, numKeys).map((arg) => String(arg)); + const rest = args.slice(numKeys).map(asWireArg); + return redis.eval(script, keys, rest); + }, + }; +} + +/** + * {@link CacheStore} backed by Upstash Redis. + * + * This wraps the serverless REST client and forwards to + * {@link createRedisCacheStore} after adapting that client's command shape. + * Expiry stays on the injected Clock, tag invalidation stays a sidecar + * index — one key at a time — and a `CacheKey.hashTag` remains the first + * brace pair on the wire. + */ +export function createUpstashRedisCacheStore( + options: UpstashRedisCacheStoreOptions, +): CacheStore { + return createRedisCacheStore({ + clock: options.clock, + redis: adaptUpstashRedisClient(options.redis), + ...(options.logger === undefined ? {} : { logger: options.logger }), + ...(options.random === undefined ? {} : { random: options.random }), + ...(options.keyPrefix === undefined + ? {} + : { keyPrefix: options.keyPrefix }), + }); +} diff --git a/packages/cache-upstash-redis/tsconfig.json b/packages/cache-upstash-redis/tsconfig.json new file mode 100644 index 0000000..63b27dd --- /dev/null +++ b/packages/cache-upstash-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" }, { "path": "../cache-redis" }] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d2ccccd..8e9b3a6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -90,6 +90,28 @@ importers: specifier: 0.1.0 version: link:../cache-conformance + packages/cache-upstash-redis: + dependencies: + '@pegma/cache-core': + specifier: 0.1.0 + version: link:../cache-core + '@pegma/cache-redis': + specifier: 0.1.0 + version: link:../cache-redis + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + '@upstash/redis': + specifier: ^1.38.2 + version: 1.38.2 + devDependencies: + '@pegma/cache-conformance': + specifier: 0.1.0 + version: link:../cache-conformance + ioredis: + specifier: ^5.8.2 + version: 5.11.1 + packages: '@ioredis/commands@1.10.0': @@ -333,6 +355,9 @@ packages: cpu: [x64] os: [win32] + '@upstash/redis@1.38.2': + resolution: {integrity: sha512-RZ+JaRCVIS+ZTGnjOnDMr+/0aqDxsBb5rV6aW+Pys4SGELwr5lwE3UbLHRCHqMQ5Ulxj0b/CFBHfbmE175Otog==} + '@vitest/expect@4.1.10': resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==} @@ -579,6 +604,9 @@ packages: engines: {node: '>=16.20.0'} hasBin: true + uncrypto@0.1.3: + resolution: {integrity: sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==} + undici-types@8.3.0: resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==} @@ -800,6 +828,10 @@ snapshots: '@typescript/typescript-win32-x64@7.0.2': optional: true + '@upstash/redis@1.38.2': + dependencies: + uncrypto: 0.1.3 + '@vitest/expect@4.1.10': dependencies: '@standard-schema/spec': 1.1.0 @@ -1027,6 +1059,8 @@ snapshots: '@typescript/typescript-win32-arm64': 7.0.2 '@typescript/typescript-win32-x64': 7.0.2 + uncrypto@0.1.3: {} + undici-types@8.3.0: {} vite@8.2.1(@types/node@26.2.0): diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 44ca4d8..ba892a7 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -45,6 +45,10 @@ export const RELEASE_PACKAGES = [ directory: "cache-elasticache", name: "@pegma/cache-elasticache", }, + { + directory: "cache-upstash-redis", + name: "@pegma/cache-upstash-redis", + }, ]; const RELEASE_NAMES = new Set(RELEASE_PACKAGES.map(({ name }) => name)); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index dce995d..f6137ce 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -40,6 +40,7 @@ describe("release package metadata", () => { "@pegma/cache-redis", "@pegma/cache-azure-redis", "@pegma/cache-elasticache", + "@pegma/cache-upstash-redis", ]); }); @@ -63,6 +64,7 @@ describe("release package metadata", () => { { name: "@pegma/cache-redis", version: "0.1.0" }, { name: "@pegma/cache-azure-redis", version: "0.1.0" }, { name: "@pegma/cache-elasticache", version: "0.1.0" }, + { name: "@pegma/cache-upstash-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"); @@ -70,10 +72,13 @@ describe("release package metadata", () => { expect(manifests[3]?.dependencies?.["@pegma/cache-redis"]).toBe("0.1.0"); expect(manifests[4]?.dependencies?.["@pegma/cache-core"]).toBe("0.1.0"); expect(manifests[4]?.dependencies?.["@pegma/cache-redis"]).toBe("0.1.0"); + expect(manifests[5]?.dependencies?.["@pegma/cache-core"]).toBe("0.1.0"); + expect(manifests[5]?.dependencies?.["@pegma/cache-redis"]).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(manifests[3]?.dependencies?.["@pegma/spine"]).toBe("0.1.2"); expect(manifests[4]?.dependencies?.["@pegma/spine"]).toBe("0.1.2"); + expect(manifests[5]?.dependencies?.["@pegma/spine"]).toBe("0.1.2"); expect(packageVersion).toBe("0.1.0"); }); @@ -173,6 +178,28 @@ describe("release package metadata", () => { specifier: ^5.8.2 version: 5.8.2 + packages/cache-upstash-redis: + dependencies: + '@pegma/cache-core': + specifier: 0.1.0 + version: link:../cache-core + '@pegma/cache-redis': + specifier: 0.1.0 + version: link:../cache-redis + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + '@upstash/redis': + specifier: ^1.38.2 + version: 1.38.2 + devDependencies: + '@pegma/cache-conformance': + specifier: 0.1.0 + version: link:../cache-conformance + ioredis: + specifier: ^5.8.2 + version: 5.8.2 + packages: prettier@3.9.6: resolution: {integrity: sha512-example} @@ -184,6 +211,7 @@ packages: "packages/cache-redis", "packages/cache-azure-redis", "packages/cache-elasticache", + "packages/cache-upstash-redis", ]); expect(importers["packages/cache-core"]).toEqual({ dependencies: { @@ -305,6 +333,41 @@ packages: "^5.8.2", ), ).toBe(true); + expect( + live["packages/cache-upstash-redis"]?.dependencies?.[ + "@pegma/cache-redis" + ], + ).toEqual({ + specifier: "0.1.0", + version: "link:../cache-redis", + }); + expect( + lockDependencyMatches( + live["packages/cache-upstash-redis"]?.dependencies?.["@pegma/spine"], + "0.1.2", + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/cache-upstash-redis"]?.devDependencies?.[ + "@pegma/cache-conformance" + ], + "0.1.0", + { workspace: true }, + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/cache-upstash-redis"]?.dependencies?.["@upstash/redis"], + "^1.38.2", + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/cache-upstash-redis"]?.devDependencies?.ioredis, + "^5.8.2", + ), + ).toBe(true); }); it("matches each lockfile dependency to its own specifier and resolved version", () => { @@ -390,6 +453,7 @@ describe("release source authentication", () => { expect(prepare).toContain("pnpm run test:redis"); expect(prepare).toContain("pnpm run test:azure-redis"); expect(prepare).toContain("pnpm run test:elasticache"); + expect(prepare).toContain("pnpm run test:upstash-redis"); expect(prepare).toContain("16379:6379"); expect(publish).toContain("id-token: write"); expect(publish).not.toContain("npm ci"); diff --git a/tsconfig.json b/tsconfig.json index 95ca89f..75a5908 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,7 @@ { "path": "./packages/cache-conformance" }, { "path": "./packages/cache-redis" }, { "path": "./packages/cache-azure-redis" }, - { "path": "./packages/cache-elasticache" } + { "path": "./packages/cache-elasticache" }, + { "path": "./packages/cache-upstash-redis" } ] } diff --git a/tsconfig.test.json b/tsconfig.test.json index 454af4b..bc84d4b 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -14,6 +14,7 @@ "vitest.config.ts", "vitest.redis.config.ts", "vitest.azure-redis.config.ts", - "vitest.elasticache.config.ts" + "vitest.elasticache.config.ts", + "vitest.upstash-redis.config.ts" ] } diff --git a/vitest.config.ts b/vitest.config.ts index 629b0e0..bc65a2f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -9,6 +9,7 @@ export default defineConfig({ "packages/cache-redis/**", "packages/cache-azure-redis/**", "packages/cache-elasticache/**", + "packages/cache-upstash-redis/**", ], }, }); diff --git a/vitest.upstash-redis.config.ts b/vitest.upstash-redis.config.ts new file mode 100644 index 0000000..9fc8f0a --- /dev/null +++ b/vitest.upstash-redis.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["packages/cache-upstash-redis/**/*.test.ts"], + exclude: ["**/dist/**", "**/node_modules/**"], + globalSetup: ["./tests/redis-server.ts"], + }, +});