diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4da8741..eeb7206 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -134,3 +134,46 @@ jobs: - name: Run Azure Redis adapter tests run: pnpm run test:azure-redis + + elasticache: + name: ElastiCache 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 ElastiCache adapter tests + run: pnpm run test:elasticache diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d483106..8946178 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -87,6 +87,9 @@ jobs: - name: Run Azure Redis adapter tests run: pnpm run test:azure-redis + - name: Run ElastiCache adapter tests + run: pnpm run test:elasticache + - 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 3e0748d..5cb344a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,9 @@ Work on a `claude/*` branch and open a pull request. The gate is 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). Changes to `@pegma/cache-azure-redis` -also run `pnpm run test:azure-redis` against the same 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. 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 @@ -84,10 +86,11 @@ protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by ## Where things stand -Phase 3: `@pegma/cache-core`, `@pegma/cache-conformance`, -`@pegma/cache-redis`, and `@pegma/cache-azure-redis` (thin composition of -the generic Redis adapter). ElastiCache / Upstash adapters are later -phases — do not create those packages here yet. +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. 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 bdb9b79..c372403 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,6 +24,7 @@ pnpm run check pnpm test pnpm run test:redis pnpm run test:azure-redis +pnpm run test:elasticache pnpm run format:check ``` diff --git a/README.md b/README.md index 654ef12..850a689 100644 --- a/README.md +++ b/README.md @@ -37,14 +37,15 @@ and a conformance suite every adapter must pass. | `@pegma/cache-conformance` | Executable suite every adapter must pass | 1 | | `@pegma/cache-redis` | Generic Redis adapter | 2 | | `@pegma/cache-azure-redis` | Azure Cache for Redis adapter | 3 | -| `@pegma/cache-elasticache` | Amazon ElastiCache adapter | later | +| `@pegma/cache-elasticache` | Amazon ElastiCache adapter | 4 | | `@pegma/cache-upstash-redis` | Upstash Redis adapter | later | `@pegma/cache-redis` is the generic Redis adapter. -`@pegma/cache-azure-redis` is a thin composition of it: Azure Cache for -Redis speaks Redis. Intended future hosts: RetireGolden.org and -Exsimplify. Remaining adapter packages wait until implementation begins -and a named consumer exists. +`@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. ## Constraint that shapes everything @@ -71,11 +72,13 @@ pnpm run check pnpm test pnpm run test:redis pnpm run test:azure-redis +pnpm run test:elasticache ``` -`pnpm test` is the Phase 1 gate and does not need Redis. `pnpm run test:redis` -and `pnpm run test:azure-redis` start a local `redis-server` on port 16379 -when that port is free, or use whatever is already listening there. +`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. ## License diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 9ccdcbd..c40c79e 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,9 +2,10 @@ ## Status -**Stage:** Phase 3 — Azure Cache for Redis adapter, in-tree, unpublished. -`@pegma/cache-core`, `@pegma/cache-conformance`, `@pegma/cache-redis`, and -`@pegma/cache-azure-redis` are `0.1.0` and not published. +**Stage:** Phase 4 — Amazon ElastiCache 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. **License:** MIT @@ -96,15 +97,15 @@ those land with a later adapter, named, tested, and never smuggled into ### No adapter package without a consumer The Pegma rule: do not create an adapter package until implementation -begins and a named consumer exists. Phase 2 created `@pegma/cache-redis` -and Phase 3 creates `@pegma/cache-azure-redis` because RetireGolden.org -and Exsimplify are named future hosts. `cache-elasticache` and -`cache-upstash-redis` wait. +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. ### Vendor clients stay behind the port Application code depends on `CacheStore`. An adapter may import `ioredis` -or the Azure SDK; a host must not. The memory store exists so tests and +or a vendor SDK; a host must not. The memory store exists so tests and local composition never take a network client. ## Scope @@ -127,8 +128,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.** -- **ElastiCache / Upstash packages in Phase 3.** - Those remain later phases. +- **Upstash package in Phase 4.** + That remains a later phase. ## Package architecture @@ -160,15 +161,19 @@ 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 (this PR) +### Phase 3 — Azure Cache for Redis 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 +### Phase 4 — Amazon ElastiCache (this PR) -Thin adapter. Cluster hash-tag behaviour is proven here, not implied. +Thin adapter over the same port. ElastiCache speaks Redis, so +`@pegma/cache-elasticache` composes `@pegma/cache-redis` rather than +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 diff --git a/docs/RELEASING.md b/docs/RELEASING.md index ba90d09..b833e06 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,7 +1,8 @@ # Release operations -`@pegma/cache-core`, `@pegma/cache-conformance`, `@pegma/cache-redis`, and -`@pegma/cache-azure-redis` publish only from a stable GitHub release. +`@pegma/cache-core`, `@pegma/cache-conformance`, `@pegma/cache-redis`, +`@pegma/cache-azure-redis`, and `@pegma/cache-elasticache` publish only +from a stable GitHub release. Merging a pull request never publishes, and the workflow has no manual-dispatch or npm-token fallback. @@ -10,10 +11,10 @@ manual-dispatch or npm-token fallback. Before the first release through this workflow: - configure `@pegma/cache-core`, `@pegma/cache-conformance`, - `@pegma/cache-redis`, and `@pegma/cache-azure-redis` 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`, 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`; - 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 @@ -30,11 +31,13 @@ remaining traditional npm publish tokens. The version in `packages/cache-core/package.json`, `packages/cache-conformance/package.json`, -`packages/cache-redis/package.json`, and -`packages/cache-azure-redis/package.json` is the release version. All +`packages/cache-redis/package.json`, +`packages/cache-azure-redis/package.json`, and +`packages/cache-elasticache/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` and `pnpm run test:azure-redis`. +including `pnpm run test:redis`, `pnpm run test:azure-redis`, and +`pnpm run test:elasticache`. 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 0f6826f..cd1e3e5 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,8 @@ "release:publish": "node scripts/release-packages.mjs publish", "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: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" }, "devDependencies": { "@types/node": "^26.1.1", diff --git a/packages/cache-elasticache/LICENSE b/packages/cache-elasticache/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/cache-elasticache/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-elasticache/README.md b/packages/cache-elasticache/README.md new file mode 100644 index 0000000..767afd5 --- /dev/null +++ b/packages/cache-elasticache/README.md @@ -0,0 +1,55 @@ +# `@pegma/cache-elasticache` + +Amazon ElastiCache adapter for [`@pegma/cache-core`](https://github.com/pegma-dev/cache-core). +A thin composition of [`@pegma/cache-redis`](https://github.com/pegma-dev/cache-core/tree/main/packages/cache-redis): +ElastiCache speaks Redis, so this package does not invent a second store. +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 { createElastiCacheCacheStore } from "@pegma/cache-elasticache"; +import { Redis } from "ioredis"; + +const clock = createControllableClock("2026-08-15T16:00:00.000Z"); +const cache = createElastiCacheCacheStore({ + clock, + // Primary endpoint. A cluster-mode configuration endpoint needs Redis.Cluster. + redis: new Redis({ + host: process.env.ELASTICACHE_HOST ?? "127.0.0.1", + port: Number(process.env.ELASTICACHE_PORT ?? "6379"), + password: process.env.ELASTICACHE_AUTH_TOKEN, + tls: {}, + }), +}); +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 — typically TLS to the primary endpoint, with the ElastiCache AUTH +token as the password — and hand it to this adapter. A cluster-mode +configuration endpoint is not a standalone host: inject `Redis.Cluster` (or +another cluster-aware client) so slot redirects are handled there. +Application code does not import `ioredis` or an AWS data-plane SDK. + +There is no ElastiCache data-plane Redis SDK to wrap. This factory forwards +to `createRedisCacheStore`, so TTL, sliding refresh, and XFetch still read +the injected Spine `Clock`, tag invalidation still uses a sidecar index, and +hash tags stay formatting. `formatCacheKey` embeds `{tag}` as the first +brace pair on the wire so Redis Cluster (and ElastiCache cluster mode) +colocates those keys. The port still refuses implicit cross-partition +multi-key operations. + +This adapter passes `@pegma/cache-conformance` against a real Redis. diff --git a/packages/cache-elasticache/package.json b/packages/cache-elasticache/package.json new file mode 100644 index 0000000..976e3a3 --- /dev/null +++ b/packages/cache-elasticache/package.json @@ -0,0 +1,45 @@ +{ + "name": "@pegma/cache-elasticache", + "version": "0.1.0", + "description": "Amazon ElastiCache 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-elasticache" + }, + "dependencies": { + "@pegma/cache-core": "0.1.0", + "@pegma/cache-redis": "0.1.0", + "@pegma/spine": "0.1.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-elasticache/src/index.test.ts b/packages/cache-elasticache/src/index.test.ts new file mode 100644 index 0000000..f5493e9 --- /dev/null +++ b/packages/cache-elasticache/src/index.test.ts @@ -0,0 +1,204 @@ +import { Redis } from "ioredis"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import { + createControllableClock, + formatCacheKey, + jsonCodec, +} from "@pegma/cache-core"; +import { conformanceCases } from "@pegma/cache-conformance"; +import { + createRedisCacheStore, + type RedisCacheClient, +} from "@pegma/cache-redis"; +import { noopLogger } from "@pegma/spine"; + +import { REDIS_URL } from "../../../tests/redis-server.js"; +import { createElastiCacheCacheStore } from "./index.js"; + +const START = "2026-08-15T16:00:00.000Z"; + +const redis = new Redis(REDIS_URL, { + maxRetriesPerRequest: 1, +}); + +beforeAll(async () => { + await redis.ping(); +}); + +afterAll(async () => { + await redis.quit(); +}); + +let prefixCounter = 0; + +function nextPrefix(): string { + prefixCounter += 1; + return `pegma-cache:ec${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, + eval: reject, + }; +} + +/** + * Redis Cluster CRC-16 (XMODEM, poly 0x1021) as used by `CLUSTER KEYSLOT`. + * Lives in the test so production code does not grow a multi-key helper. + */ +function redisCrc16(bytes: Uint8Array): number { + let crc = 0; + for (const byte of bytes) { + crc ^= byte << 8; + for (let bit = 0; bit < 8; bit += 1) { + crc = (crc & 0x8000) !== 0 ? (crc << 1) ^ 0x1021 : crc << 1; + crc &= 0xffff; + } + } + return crc; +} + +/** + * Slot of a Redis Cluster wire key. The first non-empty `{tag}` is hashed; + * otherwise the whole key is. Matches `keyHashSlot` in Redis. + */ +function redisClusterSlot(wireKey: string): number { + const start = wireKey.indexOf("{"); + if (start !== -1) { + const end = wireKey.indexOf("}", start + 1); + if (end > start + 1) { + return ( + redisCrc16(new TextEncoder().encode(wireKey.slice(start + 1, end))) & + 0x3fff + ); + } + } + return redisCrc16(new TextEncoder().encode(wireKey)) & 0x3fff; +} + +describe("createElastiCacheCacheStore", () => { + 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: () => + createElastiCacheCacheStore({ clock, logger, redis, keyPrefix }), + createUnavailableStore: () => + createElastiCacheCacheStore({ + clock, + logger, + redis: unavailableRedis(), + keyPrefix, + }), + }); + }); + } +}); + +describe("ElastiCache adapter composition", () => { + it("shares the generic Redis envelope and tag index", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const elasticache = createElastiCacheCacheStore({ + clock, + redis, + keyPrefix, + }); + const generic = createRedisCacheStore({ clock, redis, keyPrefix }); + const codec = jsonCodec(); + const address = { namespace: "ns", key: "shared" }; + await elasticache.set(address, "value", codec, { tags: ["group"] }); + expect(await generic.get(address, codec)).toMatchObject({ + status: "hit", + value: "value", + }); + expect(await generic.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 1, + }); + expect(await elasticache.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 = createElastiCacheCacheStore({ 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(() => + createElastiCacheCacheStore({ + clock: createControllableClock(START), + redis, + keyPrefix: "pre{fix}:", + }), + ).toThrow(/braces/u); + }); +}); + +describe("ElastiCache cluster hash-tag colocation", () => { + it("matches Redis CLUSTER KEYSLOT on published vectors", () => { + expect(redisClusterSlot("foo")).toBe(12182); + expect(redisClusterSlot("somekey")).toBe(11058); + expect(redisClusterSlot("foo{hash_tag}")).toBe(2515); + expect(redisClusterSlot("bar{hash_tag}")).toBe(2515); + expect(redisClusterSlot("{user1000}.following")).toBe( + redisClusterSlot("{user1000}.followers"), + ); + }); + + it("embeds {tag} so tagged wire keys share a Redis Cluster slot", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const store = createElastiCacheCacheStore({ clock, redis, keyPrefix }); + const codec = jsonCodec(); + const first = { namespace: "sessions", key: "one", hashTag: "user-1" }; + const second = { namespace: "profile", key: "two", hashTag: "user-1" }; + const other = { namespace: "sessions", key: "one", hashTag: "user-2" }; + + expect(formatCacheKey(first)).toBe("{user-1}sessions:one"); + expect(formatCacheKey(second)).toBe("{user-1}profile:two"); + expect(formatCacheKey(other)).toBe("{user-2}sessions:one"); + + await store.set(first, "a", codec); + await store.set(second, "b", codec); + await store.set(other, "c", codec); + + const firstWire = `${keyPrefix}e:{user-1}sessions:one`; + const secondWire = `${keyPrefix}e:{user-1}profile:two`; + const otherWire = `${keyPrefix}e:{user-2}sessions:one`; + expect(await redis.getBuffer(firstWire)).not.toBeNull(); + expect(await redis.getBuffer(secondWire)).not.toBeNull(); + expect(await redis.getBuffer(otherWire)).not.toBeNull(); + + expect(redisClusterSlot(firstWire)).toBe(redisClusterSlot(secondWire)); + expect(redisClusterSlot(firstWire)).toBe(redisClusterSlot("{user-1}")); + expect(redisClusterSlot(firstWire)).not.toBe(redisClusterSlot(otherWire)); + expect(keyPrefix.includes("{") || keyPrefix.includes("}")).toBe(false); + }); +}); diff --git a/packages/cache-elasticache/src/index.ts b/packages/cache-elasticache/src/index.ts new file mode 100644 index 0000000..2deba45 --- /dev/null +++ b/packages/cache-elasticache/src/index.ts @@ -0,0 +1,28 @@ +import type { CacheStore } from "@pegma/cache-core"; +import { + createRedisCacheStore, + type RedisCacheStoreOptions, +} from "@pegma/cache-redis"; + +export type { RedisCacheClient } from "@pegma/cache-redis"; + +/** + * Same injected client, clock, and optional key prefix as the generic Redis + * adapter. ElastiCache speaks Redis; hosts construct the TLS client at the + * composition root. + */ +export type ElastiCacheCacheStoreOptions = RedisCacheStoreOptions; + +/** + * {@link CacheStore} backed by Amazon ElastiCache. + * + * This is a thin composition of {@link createRedisCacheStore}. 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 so Redis Cluster slots colocate. + */ +export function createElastiCacheCacheStore( + options: ElastiCacheCacheStoreOptions, +): CacheStore { + return createRedisCacheStore(options); +} diff --git a/packages/cache-elasticache/tsconfig.json b/packages/cache-elasticache/tsconfig.json new file mode 100644 index 0000000..63b27dd --- /dev/null +++ b/packages/cache-elasticache/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 c9f5630..d2ccccd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -55,6 +55,25 @@ importers: specifier: 0.1.2 version: 0.1.2 + packages/cache-elasticache: + 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 + devDependencies: + '@pegma/cache-conformance': + specifier: 0.1.0 + version: link:../cache-conformance + ioredis: + specifier: ^5.8.2 + version: 5.11.1 + packages/cache-redis: dependencies: '@pegma/cache-core': diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 6b544a0..44ca4d8 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -41,6 +41,10 @@ export const RELEASE_PACKAGES = [ directory: "cache-azure-redis", name: "@pegma/cache-azure-redis", }, + { + directory: "cache-elasticache", + name: "@pegma/cache-elasticache", + }, ]; 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 b19e374..dce995d 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -39,6 +39,7 @@ describe("release package metadata", () => { "@pegma/cache-conformance", "@pegma/cache-redis", "@pegma/cache-azure-redis", + "@pegma/cache-elasticache", ]); }); @@ -61,14 +62,18 @@ describe("release package metadata", () => { { name: "@pegma/cache-conformance", version: "0.1.0" }, { 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" }, ]); expect(manifests[1]?.dependencies?.["@pegma/cache-core"]).toBe("0.1.0"); expect(manifests[2]?.dependencies?.["@pegma/cache-core"]).toBe("0.1.0"); expect(manifests[3]?.dependencies?.["@pegma/cache-core"]).toBe("0.1.0"); 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[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(packageVersion).toBe("0.1.0"); }); @@ -149,6 +154,25 @@ describe("release package metadata", () => { specifier: ^5.8.2 version: 5.8.2 + packages/cache-elasticache: + 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 + 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} @@ -159,6 +183,7 @@ packages: "packages/cache-conformance", "packages/cache-redis", "packages/cache-azure-redis", + "packages/cache-elasticache", ]); expect(importers["packages/cache-core"]).toEqual({ dependencies: { @@ -253,6 +278,33 @@ packages: "^5.8.2", ), ).toBe(true); + expect( + live["packages/cache-elasticache"]?.dependencies?.["@pegma/cache-redis"], + ).toEqual({ + specifier: "0.1.0", + version: "link:../cache-redis", + }); + expect( + lockDependencyMatches( + live["packages/cache-elasticache"]?.dependencies?.["@pegma/spine"], + "0.1.2", + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/cache-elasticache"]?.devDependencies?.[ + "@pegma/cache-conformance" + ], + "0.1.0", + { workspace: true }, + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/cache-elasticache"]?.devDependencies?.ioredis, + "^5.8.2", + ), + ).toBe(true); }); it("matches each lockfile dependency to its own specifier and resolved version", () => { @@ -337,6 +389,7 @@ describe("release source authentication", () => { expect(prepare).toContain("pnpm run release:pack"); 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("16379:6379"); expect(publish).toContain("id-token: write"); expect(publish).not.toContain("npm ci"); diff --git a/tsconfig.json b/tsconfig.json index ec056b2..95ca89f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,7 @@ { "path": "./packages/cache-core" }, { "path": "./packages/cache-conformance" }, { "path": "./packages/cache-redis" }, - { "path": "./packages/cache-azure-redis" } + { "path": "./packages/cache-azure-redis" }, + { "path": "./packages/cache-elasticache" } ] } diff --git a/tsconfig.test.json b/tsconfig.test.json index 28d1741..454af4b 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -13,6 +13,7 @@ "tests/**/*.ts", "vitest.config.ts", "vitest.redis.config.ts", - "vitest.azure-redis.config.ts" + "vitest.azure-redis.config.ts", + "vitest.elasticache.config.ts" ] } diff --git a/vitest.config.ts b/vitest.config.ts index 3501b87..629b0e0 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -8,6 +8,7 @@ export default defineConfig({ "**/node_modules/**", "packages/cache-redis/**", "packages/cache-azure-redis/**", + "packages/cache-elasticache/**", ], }, }); diff --git a/vitest.elasticache.config.ts b/vitest.elasticache.config.ts new file mode 100644 index 0000000..80e9e88 --- /dev/null +++ b/vitest.elasticache.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["packages/cache-elasticache/**/*.test.ts"], + exclude: ["**/dist/**", "**/node_modules/**"], + globalSetup: ["./tests/redis-server.ts"], + }, +});