Repository navigation
Commit dc79e38
feat(service-cache)!: a declared multi-node deployment on the redis cluster driver shares one Redis cache, so cache-backed limits hold across replicas (#31624)
<!-- claude-projects-attribution: {"github_login":"os-zhuang"} -->
_Requested by **Sam** · [project
thread](https://claude.ai/code/project/chan_01GsBogozeZG5sdpAARrN7HP?thread=cmsg_01GsBogozeZG5sdpAARrN7HP7y9t5c78P1x2XisqWTYqrR)_
Closes #31553
Clause-②: yes (narrowing) — new exports and options widen the public
surface, and one configuration that used to boot is now refused:
`CacheServicePlugin({ adapter: 'memory' })` in a deployment that
declares multi-node (`OS_EXPECT_MULTI_NODE=true` / `OS_CLUSTER_REPLICAS`
> 1) over the `redis` cluster driver.
Metadata-protocol: none
Skills-docs: updated here — the service-cache README,
`content/docs/kernel/contracts/cache-service.mdx`,
`content/docs/kernel/cluster.mdx`, `content/docs/plugins/packages.mdx`
and `docs/HARDENING.md`; `skills/**` teaches no cache adapter choice (an
operator setting, nothing a metadata author writes).
## 维护者速读
- **改了什么**:缓存服务有了真正能用的 Redis 适配器。部署声明多副本、并且集群驱动是 Redis 时,缓存自动改用驱动连着的那台
Redis(复用驱动的连接设置,不另配一套),所有副本共用一个缓存。
- **为什么改**:登录限流、入站 API 预算、短信每日配额、通知节点按地址的邮件限额,计数都存在缓存里。以前每个副本各数各的,N
个副本就是 N 倍上限,攻击者轮换副本就能绕过(ADR-0069 D2
点名的洞)。这些计数器本身不用改代码,缓存换成共享的就自动共用;其中登录限流、短信配额、通知限额各有一个两副本测试。
- **风险与回滚**:单节点路径不变,启动日志逐字钉在测试里;只有"声明多副本 + Redis
驱动"才走新路径。唯一会被拒绝启动的配置,是在这种部署里显式写 `adapter: 'memory'`。Redis
宕机时登录接口会报错(better-auth 不吞错),入站限流放行。回滚 = revert 本 PR。
- **先看**:① `packages/services/service-cache/src/cache-service-plugin.ts`
的 `planCacheAdapter` 决策表和 `init`;②
`packages/services/service-cache/src/redis-cache-adapter.ts` 的
`clear`/`stats` 命名空间限定与失败直接抛出;③
`packages/services/service-cluster-redis/src/index.ts` 里驱动交出连接的那一处调用。
- **两分钟验证**:`pnpm --filter @objectstack/plugin-auth exec vitest run
--maxWorkers=2 src/rate-limit-storage.shared-redis.test.ts`,预期 3
passed:两个副本合计只放行 5 次(上限 5),未声明多副本的对照组放行 10 次;本机有 `redis-server`
时还会跑两个真进程连真 Redis 的一腿。
- **需要你做的**:无,席位落地。
## What changes
**`@objectstack/service-cache` — the adapter is chosen by topology.**
With `adapter` unset (the default, and how `os serve` and the cloud
control plane mount it), `CacheServicePlugin.init` decides through a
pure function, `planCacheAdapter`:
| Deployment | Cache |
|:---|:---|
| Single node (no multi-node declaration) | `MemoryCacheAdapter`. The
cluster service is not read; the boot, including its one info line, is
byte-identical. |
| Multi-node declared over the `redis` cluster driver |
`RedisCacheAdapter`, on `duplicate()` of the driver's ioredis client
(same Redis, same key prefix, its own connection), closed at
`kernel:shutdown`. |
| The same, with `adapter: 'memory'`, or with a redis driver that offers
no connection | `init` throws, naming the fix (the card's "refuse boot
loudly"). |
| Multi-node declared over any other driver, or with no cluster service
| `MemoryCacheAdapter`, plus one `warn` that cache-backed limits
multiply by the replica count. |
`adapter: 'redis'` now works (over `redis.client`, else the driver's
connection, else `init` throws). The plugin declares
`com.objectstack.service.cluster` an optional dependency, so it reads
the driver after the driver started, in either registration order
(pinned with the cache plugin registered first).
**`RedisCacheAdapter` is implemented.** Entries live at `PREFIX` +
`cache:` + `KEY` (default prefix `os:`, the driver's). Values are JSON
(a `Date` reads back as its ISO string; `undefined`, functions and
`bigint` are refused with a `TypeError`). Redis expires entries itself
(`SET … PX`; `ttl` in seconds, `0` = no expiry). A Redis failure is
thrown, never answered as a miss, because an outage read as "not found"
would silently reset every counter. `clear()` and `stats().keyCount`
touch only the cache namespace, never the driver's `kv:` / `ctr:` / lock
keys under the same prefix; SCAN uses a widened pattern plus an exact
prefix filter, so a prefix containing glob characters is still matched
literally. `hits` / `misses` stay per process. The adapter takes no
Redis library dependency: the client is a structural `RedisCacheClient`.
**`@objectstack/service-cluster` — the connection seam.**
`offerClusterDriverConnection(cluster, { driver, client, keyPrefix })`
and `readClusterDriverConnection(cluster, driver)`. It is a
framework-internal handshake between a driver package and the cache
package: nothing is added to the spec `IClusterService` contract, and
`packages/spec` is untouched. Two design choices, both pinned in
`driver-connection.test.ts`:
- **Non-enumerable**, so the offer never shows up in `Object.keys`, a
spread, a log line or `JSON.stringify` of the cluster facade (it holds a
live client), and it is written once: a second offer throws.
- **Under a `Symbol.for` key**, so two copies of
`@objectstack/service-cluster` in one process (the ESM and CJS builds,
or two resolved versions) read the same offer: the driver may offer
through one copy and the cache read through the other. A module-local
`Symbol()` or a `WeakMap` would make the offer invisible across copies
and the cache would silently stay per-process. The key's spelling is
pinned in the test, because renaming it would break every
already-published driver.
**`@objectstack/service-cluster-redis`** makes one call, offering its
client and key prefix. Its own behaviour is unchanged.
**Every cache-backed counter shares the same store, with no change of
its own.** The sign-in limits, the inbound API budget, the OTP send
budget, the daily SMS quota (`service-sms`, `SmsDailyQuota`) and the
`notify` node's per-address email-field limit (`service-automation`) all
count through `createLazyCounterStore` /
`createLazyCacheRateLimitStorage` over `resolveKernelCache`, i.e. in
whatever the `cache` slot holds. So the topology choice above makes each
of them one counter across replicas; none of them needed a production
change, and each now has a two-replica test (below).
**Red line held.** The counters reach the cache only through better-auth
`rateLimit.customStorage` (`createLazyCacheRateLimitStorage`);
`secondaryStorage` is not enabled, so sessions stay in `sys_session` and
revocation is untouched.
**Docs.** The README, the cache contract page, the cluster page, the
packages page and `docs/HARDENING.md` stop calling the adapter a
skeleton and state which cache a deployment gets.
## Tests
- `service-cache/src/redis-cache-adapter.test.ts`: the same contract
battery runs against `MemoryCacheAdapter` and `RedisCacheAdapter`
(get/set, objects, delete, has, TTL, `defaultTtl` and `ttl` 0, clear,
stats, the counter string envelope). Redis-only cases: two clients share
one cache; keys land under `os:cache:` with `PX`; `clear`/`stats` leave
the driver's keys alone; a glob-character prefix matches literally; JSON
semantics; a foreign non-JSON value reads as a miss; failures are
thrown; metric labels; `close()` ownership; the constructor refuses a
URL-only option set.
- `service-cache/src/cache-service-plugin.topology.test.ts`: the
decision table on `planCacheAdapter`; `init` against a context double
(the single-node info line pinned verbatim, no warn, no cluster read;
the optional-dependency pin; multi-node redis registers Redis and closes
it at shutdown; `OS_EXPECT_MULTI_NODE` equals `OS_CLUSTER_REPLICAS>1`;
`adapter: 'memory'` throws; the memory driver warns); and real
`ObjectKernel` boots with the cluster plugin and the redis driver on
`ioredis-mock` (two multi-node kernels share one cache even with the
cache plugin registered first; a single-node kernel stays memory;
multi-node with `adapter: 'memory'` refuses to boot).
- `service-cluster/src/driver-connection.test.ts` (4) and two cases in
`service-cluster-redis/src/redis.contract.test.ts`: the offer reads back
for its driver only, never throws on non-objects, is invisible to
enumeration and serialisation, cannot be replaced, and lives under the
pinned `Symbol.for` key; the redis driver offers its client and its
prefix (`os:` by default).
- `plugin-auth/src/rate-limit-storage.shared-redis.test.ts`: one sign-in
key, rule `{ window: 60, max: 5 }`, 10 alternating attempts through
`createLazyCacheRateLimitStorage({ resolveCache: () =>
resolveKernelCache(ctx) })`, the seam `AuthPlugin` wires into
better-auth.
- Leg 1 (runs everywhere): two kernels on separate mock clients.
Declared multi-node: both caches are `RedisCacheAdapter`, 5 admitted in
total. Control without the declaration: `MemoryCacheAdapter`, 10
admitted.
- Leg 2 (skipped when `redis-server` is not on PATH; the replica process
is `src/__fixtures__/rate-limit-storage.shared-redis.replica.ts`): a
real `redis-server` on a free port and four forked replica processes,
two declared and two not. Declared: `['redis','redis']`, 5 admitted in
total. Undeclared: `['memory','memory']`, 10 admitted. Separate
processes on purpose: inside one process `serializePerKey` orders every
limiter's read-modify-write through one module-level queue, so
in-process "nodes" cannot interleave the way replicas do.
- `service-sms/src/sms-daily-quota.shared-redis.test.ts`: two kernels,
each with the cluster plugin on the redis driver (separate mock clients,
one keyspace), `CacheServicePlugin`, a settings host serving
`daily_quota: 3`, and the real `SmsServicePlugin`. 8 alternating sends:
declared multi-node admits 3 in total; the undeclared control admits 6
(3 per replica).
-
`service-automation/src/builtin/notify-email-field.shared-redis.integration.test.ts`:
the same two-kernel composition with the real `notify` node and an
email-field recipient. 12 alternating runs to one address: declared
multi-node sends 5 in total (`EMAIL_FIELD_SENDS_PER_WINDOW`); the
undeclared control sends 10.
## Acceptance notes
- **The seam absent, or the memory driver: resolution as today, with one
stated exception.** Single node, any driver: memory, no cluster read,
the same info line (`init — the single-node default is unchanged ›
registers a MemoryCacheAdapter, logs the one line it always logged,
warns nothing, reads no cluster`; `planCacheAdapter › single node over
the redis driver stays memory`). Multi-node over the memory driver (only
reachable past the split-brain guard's override) or with no cluster
service: memory, as today, plus one new `warn` line (`planCacheAdapter ›
multi-node over the memory driver …`, `› multi-node with no cluster
service at all …`, `init › over the memory driver: registers memory and
warns once, after the unchanged info line`). The exception: multi-node
over a driver named `redis` that offers no connection (an older or
third-party redis driver) is **refused**, not memory, because that is
the card's "multi-replica declared and no shared cache" case
(`planCacheAdapter › multi-node over a redis driver that offers no
connection: refused, naming the version to install`).
- **A Redis outage fails sign-in requests.** better-auth calls
`customStorage` with no catch, so a thrown Redis error fails the auth
request; the inbound limiter catches and lets the request through. Kept
as is: under rule R2 Redis is a hard requirement of multi-replica, and
answering a miss would reset the counter. The status code an outage
produces at the auth endpoint is NOT MEASURED.
- **The boundary race stays.** `ICacheService` has no atomic increment,
so two nodes counting one key in the same instant can both be admitted
at the limit's boundary: the bounded over-admit ADR-0069 D2 accepts,
never a per-node limit.
- **The inbound limiter** reads the same `cache` slot and stores JSON
strings, so it is shared under the same declaration; it has no test of
its own in this PR.
- **The refusal lives in `CacheServicePlugin`.** A composition that
mounts no cache plugin gets the kernel's in-process fallback, which
plugin-auth already ignores as degraded. `os serve` always mounts the
plugin, without options; so does the cloud control plane.
- **The daily SMS quota and the notify per-address limit** were added to
this card's scope by the dispatching seat. Both already lived in the
framework and already counted in the kernel `cache`, so the change for
them is tests only:
`service-sms/src/sms-daily-quota.shared-redis.test.ts` and
`service-automation/src/builtin/notify-email-field.shared-redis.integration.test.ts`.
- **Leg 2 of the two-process test is NOT MEASURED in CI** unless the
runner has `redis-server` on PATH; it ran locally (Redis 7.0.15) and
passed.
## Verification
Local, on head `820d1fb9` unless a line says otherwise. Every exit code
below was captured before any pipe.
<details><summary>Package tests and typechecks — all exit 0</summary>
| Package | `vitest run` | `typecheck` |
|:---|:---|:---|
| `@objectstack/service-cache` | 5 files, 74 passed | exit 0 (`tsc`
covers all 5 test files) |
| `@objectstack/service-cluster` | 8 files, 115 passed | exit 0,
test-typecheck ledger 0 errors |
| `@objectstack/service-cluster-redis` | 3 files, 39 passed | exit 0 |
| `@objectstack/plugin-auth` | 242 files, 4318 passed, 10 skipped;
`rate-limit-storage.shared-redis.test.ts` alone: 3 passed, 0 skipped
(the two-process leg ran, `redis-server` 7.0.15 on PATH) | exit 0
(`tsc`, examples, test-typecheck ledger unchanged) |
| `@objectstack/service-sms` | 10 files, 121 passed (on `3523290e`) |
exit 0, ledger unchanged |
| `@objectstack/service-automation` | 265 files, 3433 passed (on
`3523290e`, under the verify lock, VERDICT command-exit 0) | exit 0,
ledger 0 errors |
`3523290e` → `820d1fb9` adds one row to
`scripts/engine-double-contract.pinned.json` and nothing else.
</details>
<details><summary>Derived gates — 121 of 121 exit 0</summary>
`node scripts/pm/dispatch-gates.mjs --commands` derived 114 families on
`3523290e`; all 114 ran there and exited 0 after one real finding was
fixed: `check:undeclared-dep-imports` read the replica fixture as
published source (it imports devDependencies), so it moved to
`src/__fixtures__/`. Three first-run exit-3 readings were prerequisites,
not findings (`check:dual-build-cjs-loads` and `spec
check:skill-examples` need built output; `check-plugin-teardown-shape
--self-test` needs a commit a shallow clone lacks); each exited 0 once
the dogfood closure was built and the commit fetched.
`check:engine-double-contract` asked for the ledger row the new notify
test's double needs, written with `--write` in `820d1fb9`. That commit's
`scripts/` path adds 7 families (`agent-test-spelling`, `bash32-floor`,
`cli-command-ids`, `entry-guard`, `parse-guard`, `pnpm-filter-targets`,
`scripts-symbol-anchors`); they and 8 re-runs (`engine-double-contract`,
`test-source-alias`, `type-check-debt`, `cross-package-test-inputs`,
`undeclared-dep-imports`, `startup-registry-verdict`,
`check-empty-changeset`, `check-adr-0087-registration`) exited 0 on
`820d1fb9`. `--ran` with every exit code recorded: `121 derived
famil(ies) accounted for — 121 run, 0 NOT-MEASURED (a DERIVED zero)`.
`check-adr-0087-registration`: `1 declared-breaking changeset(s), each
carrying an ADR-0087 disposition` — `[BREAKING+bang+clause-②-narrowing]
not-required (no-migration-prescription)`.
</details>
<details><summary>Full dogfood (owed by the narrowing arm) —
green</summary>
On `3523290e` (the later head differs by one ledger row the battery does
not read): dependency closure built (`pnpm --filter
'@objectstack/dogfood^...' build`, VERDICT command-exit 0), then `pnpm
--filter @objectstack/dogfood test` under the verify lock: `VERDICT
command-exit 0`, Test Files 440 passed, 3 skipped (443); Tests 3633
passed, 41 skipped (3674). No failure.
</details>
---
_Generated by [Claude
Code](https://claude.ai/code/session_01QUs3BtX26kRDtX1TcPPLn1)_
---------
Co-authored-by: Claude <noreply@anthropic.com>1 parent 8784ccb commit dc79e38
30 files changed
Lines changed: 2125 additions & 84 deletions
File tree
- .changeset
- content/docs
- kernel
- contracts
- plugins
- docs
- packages
- plugins/plugin-auth
- src
- __fixtures__
- services
- service-automation
- src/builtin
- service-cache
- src
- service-cluster-redis/src
- service-cluster/src
- service-sms
- src
- scripts
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
86 | 86 | | |
87 | 87 | | |
88 | 88 | | |
89 | | - | |
90 | | - | |
91 | | - | |
92 | | - | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
93 | 95 | | |
94 | 96 | | |
95 | 97 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
179 | 179 | | |
180 | 180 | | |
181 | 181 | | |
182 | | - | |
183 | | - | |
| 182 | + | |
| 183 | + | |
| 184 | + | |
| 185 | + | |
| 186 | + | |
| 187 | + | |
| 188 | + | |
| 189 | + | |
| 190 | + | |
| 191 | + | |
| 192 | + | |
| 193 | + | |
| 194 | + | |
| 195 | + | |
| 196 | + | |
| 197 | + | |
| 198 | + | |
| 199 | + | |
| 200 | + | |
| 201 | + | |
| 202 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
229 | 229 | | |
230 | 230 | | |
231 | 231 | | |
232 | | - | |
| 232 | + | |
233 | 233 | | |
234 | | - | |
| 234 | + | |
235 | 235 | | |
236 | 236 | | |
237 | 237 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
144 | 144 | | |
145 | 145 | | |
146 | 146 | | |
147 | | - | |
148 | | - | |
149 | | - | |
150 | | - | |
151 | | - | |
152 | | - | |
153 | | - | |
| 147 | + | |
| 148 | + | |
| 149 | + | |
| 150 | + | |
| 151 | + | |
| 152 | + | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
| 162 | + | |
154 | 163 | | |
155 | 164 | | |
156 | | - | |
157 | | - | |
158 | | - | |
159 | | - | |
160 | | - | |
161 | | - | |
162 | | - | |
163 | | - | |
| 165 | + | |
| 166 | + | |
| 167 | + | |
| 168 | + | |
| 169 | + | |
| 170 | + | |
164 | 171 | | |
165 | 172 | | |
166 | 173 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
68 | 68 | | |
69 | 69 | | |
70 | 70 | | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
71 | 74 | | |
72 | 75 | | |
73 | 76 | | |
| 77 | + | |
74 | 78 | | |
75 | 79 | | |
76 | 80 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
0 commit comments