Skip to content

Commit 01cbbba

Browse files
feat(cluster): settings changes reach every replica (settings lane) (#31785)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9AcJE5U3g9Ed3gpotcHp5B4)_ Fixes #31597 Clause-②: yes (widening) Metadata-protocol: none Measured on the built declarations at head: `@objectstack/service-settings` `dist/index.d.ts` gains `SETTINGS_CHANGE_CLUSTER_CHANNEL`, the `ClusterSettingsChangePayload` type and three public methods on `SettingsService` (`attachSettingsChangePubSub()`, `detachSettingsChangePubSub()`, `resyncSettingsChangePubSub()`); none of the five names occurs in that package's source at base `9e1f1f90`. `@objectstack/service-cluster` gains only private members. Nothing is removed, renamed or made required. The claim read `no`; the measurement says `yes (widening)`. No metadata an author writes changes. ## 维护者速读 - 改了什么:多副本(声明副本数大于 1 且使用 Redis 集群驱动)时,在一个副本上改了设置,其他副本也会立刻重新读取并生效,包括认证安全姿态。 - 为什么改:以前只有处理写请求的那个副本会重建配置,其他副本要到重启才看到新设置;实测一个副本已拒绝未验证邮箱的登录,另一个副本 95 秒后仍放行。 - 风险与回滚:单节点(未声明多副本或非 Redis 驱动)行为完全不变;广播消息只带命名空间和键,不带任何值或密钥。回滚即撤销本 PR。 - 先看:`service-settings/src/settings-service.ts` 的集群收发段(`attachSettingsChangePubSub` 起)、`service-cluster/src/metadata-cluster-bridge-plugin.ts` 的第五条通道 `attachSettingsLane`、新测试 `settings-cluster-lane.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/service-settings exec vitest run src/settings-cluster-lane.test.ts`,预期 10 个用例全部通过(两个内核共享一条总线,A 写入后 B 一秒内生效)。 - 需要你做的:无,席位落地。 ## What changes - **A fifth cluster lane (`@objectstack/service-cluster`).** `MetadataClusterBridgePlugin` gains `attachSettingsLane`, shaped like lanes 1 to 4: it duck-types the `settings` service's `attachSettingsChangePubSub(pubsub, nodeId)` seam at `kernel:bootstrapped` (one phase after lanes 1 to 4, because the settings service binds its engine at `kernel:ready` and a peer's change must not reach a subscriber before that; `check:settings-bind-window` caught the first spelling at `kernel:ready`), reports `bridged settings.changed → cluster.pubsub` at info, and detaches on `kernel:shutdown` (a throwing detach of another lane does not strand it). Unlike lanes 1 to 4, which skip only the in-process driver, lane 5 attaches only behind `declaresMultiReplicaOnRedis(process.env, cluster.driver)`: `OS_CLUSTER_REPLICAS` greater than 1 (or `OS_EXPECT_MULTI_NODE=true`) AND the `redis` driver (R3). The split-brain guard is untouched. - **Send and receive (`@objectstack/service-settings`).** The write door (`setMany`, which `set` and every reset go through) publishes after its local `settings:changed`. The payload is spelled field by field in `publishSettingsChange`: `{ originNode, namespace, key, scope, action, at }`, the fields the local event already carries, never a value, ciphertext handle or secret. A peer drops its own `originNode`, validates the address, and emits its own local `settings:changed`, so each subscriber re-reads the shared store. The receive path only emits; it never publishes, so there is no echo. A publish failure is a warning and never fails the write. Channel `settings.changed` (`SETTINGS_CHANGE_CLUSTER_CHANNEL`, in the new `settings-cluster-channel.ts`), partitioned per namespace. - **Joins F3a's `cluster.resync`.** The lane registers `resyncSettingsChangePubSub` through `registerLaneResync`, so when the driver's connection returns after an outage every registered namespace is announced locally once (`key: '*'`, the shape the engine bind already uses) and every subscriber re-reads. A no-op until a transport is attached; local only, never published. - **No single-node change.** The engine bind's per-namespace announcement moved into a private `emitEveryNamespace()` that the resync reuses; the events it emits are unchanged. Every other emit site is untouched. - **Docs.** `content/docs/kernel/cluster.mdx` §6.2 lists lane 5, its address-only payload, its resync, and its narrower attach condition. ## Tests - `service-settings/src/settings-cluster-lane.test.ts` (new): two `LiteKernel` replicas, each with its own `SettingsService` over its own real `ObjectQL` engine, both engines over one shared Map driver (the shared database), joined by one bus that delivers every publish to every subscriber (publisher included). Each kernel runs the real `MetadataClusterBridgePlugin` and a `cluster` service naming the `redis` driver. The auth-posture subscriber has plugin-auth's binding shape: `subscribe('auth')`, then re-read `require_email_verification`. - ⭐ A `set` on A turns B's posture within one second (`vi.waitFor`, 1000 ms), read from the shared store; a reset travels the same way. - The broadcast's keys are exactly `action, at, key, namespace, originNode, scope`, and the serialized payload does not contain the written value; B reads the value from the store. - No echo: one write puts exactly one message on the bus, and the writer and the peer each hear it once. - `cluster.resync`: a write lost during a bus outage reaches B on reconnect; nothing more goes on the wire. - After `kernel:shutdown` a replica neither publishes nor hears. - CONTROL: `redis` with no declaration emits exactly the events a lone `SettingsService` emits today and nothing crosses; declared replicas over `postgres` get no lane; a reconnect on an unattached replica and a resync with no transport announce nothing; own-origin and malformed messages are ignored. - `service-cluster/src/metadata-cluster-bridge-plugin.test.ts`: a lane-5 describe (binds at `kernel:bootstrapped`, not at `kernel:ready`; attach with the cluster's pubsub and node id; CONTROL undeclared on redis; one replica; a non-redis remote driver; the memory driver; missing service or seam; a throwing attach; shutdown detach; resync once per outage and CONTROL undeclared). The harness gains a `settings` slot defaulting to `none`, so every earlier case reads as before. - Forced test edits: none. - Test resolution: the new suite boots the cluster bridge, so `service-settings` gains `@objectstack/service-cluster` as a devDependency, aliased to source in its `vitest.config.ts` like its other workspace imports. - Ablations (each through `scripts/ablation-replace.mjs`; every mutation landed, went red, and every restore left `git diff HEAD` empty; the suites resolve the mutated files from source, so no rebuild leg): | Ablation | Red | | --- | --- | | A1: the write publishes the event plus its value | 1 (the payload key set) | | A2: the receive path publishes what it received (echo) | 4 (the bus storms; 683 local events) | | A3: the loopback guard removed | 2 (the writer hears itself twice) | | A4: lane 5's R3 guard replaced by the in-process guard | 3 of 10 in the two-kernel suite, 4 of 42 in the bridge suite | | A5: lane 5's shutdown detach removed | 1 in each suite | | A6: the resync no-transport guard removed | 1 | ## Acceptance notes - `SettingsService` holds no row cache (every read goes to the engine), so a receiver re-reads through its subscribers: each one calls `get` / `getNamespace` on the change, which reads the shared store. Nothing in the service needed invalidating. - The posture in the two-kernel test is a subscriber with plugin-auth's binding shape, not plugin-auth itself, which `service-settings` does not depend on. - New names are the seat's call: the channel `settings.changed` (the family's dot spelling, beside the local `settings:changed`), the constant `SETTINGS_CHANGE_CLUSTER_CHANNEL`, the type `ClusterSettingsChangePayload` and the three methods. - #31722 (lane 2 resync) edits the same bridge file and the same docs section; this PR lands first. ## Verification All on head `260046945` after a fresh `pnpm install --frozen-lockfile` and `turbo run build --filter='./packages/**'` (exit 0): - `pnpm --filter @objectstack/service-settings --filter @objectstack/service-cluster run test`: service-settings 75 files / 1430 tests, service-cluster 11 files / 154 tests, all passed. - `run typecheck` for both: exit 0 (service-cluster's `check:test-typecheck` included). - Lint: root eslint `--no-inline-config` on both package directories, exit 0. - `dispatch-gates.mjs --commands` derived 114 commands on the final head `260046945`; each was run, all 114 exited 0, and `--ran` reconciled: 114 derived, 114 run, 0 NOT-MEASURED, 0 UNRUN. The first round (on `a6384788`) went red on `check:settings-bind-window` (lane 5 read the `settings` service in a `kernel:ready` hook, inside the pre-bind window); the fix moved the attach to `kernel:bootstrapped`. `check-plugin-teardown-shape --self-test` needed its pinned fixture fetched (`git fetch origin 621a487…`) before it could run. - Ablations re-run on `260046945`: the table above holds on the final head. - `origin/main` moved to `c2bb879fe` during the round; none of its 43 files overlaps this diff, so main was not merged. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmNwiZZUkMiBsD19UEZ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ff8ef4c commit 01cbbba

11 files changed

Lines changed: 846 additions & 16 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/service-settings': patch
3+
'@objectstack/service-cluster': patch
4+
---
5+
6+
feat(cluster): a settings change on one replica reaches every replica
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
Multi-replica deployments on the `redis` cluster driver only. The single-node default (no declared replicas, or any driver but `redis`) emits exactly what it emitted before.
12+
13+
`settings:changed` is an in-process subscriber set, and its subscribers rebuild the auth posture, password / session / MFA policy, organization access policy, mail, SMS, storage and the AI provider. Under round-robin only the replica that took the write rebuilt; every peer kept the old configuration, security posture included, until it restarted.
14+
15+
- **A fifth cluster lane (`@objectstack/service-cluster`).** `MetadataClusterBridgePlugin` attaches the settings service to the cluster bus on the `settings.changed` channel, only where the deployment declares several replicas (`OS_CLUSTER_REPLICAS` greater than 1, or `OS_EXPECT_MULTI_NODE=true`) over the `redis` driver (`declaresMultiReplicaOnRedis`). The split-brain guard is unchanged.
16+
- **The message is an address, never a value (`@objectstack/service-settings`).** A write publishes the namespace, key, scope, action and time of the change. A peer emits its own local `settings:changed`, so each subscriber re-reads the shared store. A received change is never published again, and the writer's own message is dropped by its node id. New exports: `SETTINGS_CHANGE_CLUSTER_CHANNEL` and the `ClusterSettingsChangePayload` type; new methods `SettingsService.attachSettingsChangePubSub()`, `detachSettingsChangePubSub()` and `resyncSettingsChangePubSub()`.
17+
- **Joins `cluster.resync`.** When the cluster driver's connection returns after an outage, every registered namespace is announced locally once (`key: '*'`), so a change whose message was lost during the outage still takes effect without a restart.

‎content/docs/kernel/cluster.mdx‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ cache compare it on receipt.
328328
### 6.2 The cluster-invalidation family
329329

330330
Cross-node metadata invalidation is not one channel — it is a **family** of
331-
four independent PubSub lanes, late-bound by `MetadataClusterBridgePlugin`
331+
five independent PubSub lanes, late-bound by `MetadataClusterBridgePlugin`
332332
(`@objectstack/service-cluster`) at `kernel:ready`, one per state owner that
333333
goes stale when a shared record changes on a different node:
334334

@@ -338,17 +338,20 @@ goes stale when a shared record changes on a different node:
338338
| 2 — ObjectQL object registry | `metadata.mutated` (`METADATA_MUTATION_CLUSTER_CHANNEL`, #13331) | `ClusterMetadataMutationPayload` | `@objectstack/metadata-protocol` | ObjectQL's OBJECT registry, from a `sys_metadata` re-read; then, from the same replay, the automation service's armed flows and its materialized connectors (a `connector` mutation that is not a draft, #28002), each from the replica's own re-read |
339339
| 3 — ObjectQL driver registry | `datasource.mutated` (`DATASOURCE_MUTATION_CLUSTER_CHANNEL`, #13805) | `ClusterDatasourceMutationPayload` | `@objectstack/service-datasource` | ObjectQL's DRIVER registry, from a shared datasource-record re-read |
340340
| 4 — declarative connector instances | `connector-credential.mutated` (`CONNECTOR_CREDENTIAL_MUTATION_CLUSTER_CHANNEL`, #27428) | `ClusterConnectorCredentialMutationPayload` (`{ originNode, ref }`) | `@objectstack/service-automation` | the automation service's materialized connectors, from a reconcile that re-reads the shared `sys_connector_credential` rows; published by the credential door (`PUT` / `DELETE /api/v1/automation/connectors/credential-refs/:ref`) after the row is written or cleared |
341+
| 5 — settings subscribers | `settings.changed` (`SETTINGS_CHANGE_CLUSTER_CHANNEL`, #31597) | `ClusterSettingsChangePayload` (`{ originNode, namespace, key, scope, action, at }`) | `@objectstack/service-settings` | every local `settings:changed` subscriber (auth posture, password / session / MFA policy, organization access policy, mail, SMS, storage, the AI provider), each re-reading the shared settings store; published by `SettingsService` after a row is written or cleared. Attaches only where several replicas are declared over the `redis` driver |
341342

342-
Lanes 2 to 4 share one contract, stated once here rather than in each
343+
Lanes 2 to 5 share one contract, stated once here rather than in each
343344
channel's own doc comment:
344345

345346
- **Address-only signal.** No message body ever rides these channels — the
346347
payload names only what changed (a metadata address, a datasource name,
347-
or a connector credential reference), never the changed value.
348+
a connector credential reference, or a settings namespace and key), never
349+
the changed value.
348350
- **Receipt runs convergence, not trust.** A peer that receives a signal does
349351
not apply the payload as content; it re-reads its OWN copy of the source of
350352
truth (`sys_metadata` for lane 2, the shared datasource record for lane 3,
351-
the shared credential rows for lane 4) and converges its local registry
353+
the shared credential rows for lane 4, the shared settings store for
354+
lane 5) and converges its local registry
352355
from that read. A duplicate or re-ordered
353356
delivery converges to the same state as a single one.
354357
- **`originNode` loopback suppression.** Every payload carries the publishing
@@ -376,17 +379,28 @@ channel's own doc comment:
376379
datasource and every held pool
377380
(`DatasourceAdminService.resyncDatasourceMutationPubSub()`), and lane 4
378381
runs the connector reconcile
379-
(`AutomationEngine.resyncConnectorCredentialPubSub()`).
382+
(`AutomationEngine.resyncConnectorCredentialPubSub()`), and lane 5
383+
announces every settings namespace locally so each subscriber re-reads it
384+
(`SettingsService.resyncSettingsChangePubSub()`).
380385
`AuthzClusterBridgePlugin` advances the engine's write epoch, which retires
381386
cached grants. **Lane 2 has no resync yet**: it converges per item on the
382387
signals that are delivered, and fully at boot. A cache of your own
383388
subscribes with `onClusterResync(cluster, handler)` from
384389
`@objectstack/service-cluster`. On the `memory` driver that subscription is
385390
a no-op, because nothing there can lose a connection.
386391

387-
All four lanes skip their fan-out on the same condition — the in-process
392+
Lanes 1 to 4 skip their fan-out on the same condition — the in-process
388393
`memory` cluster driver, described for lane 1 immediately below, applies
389-
identically to lanes 2 to 4 (#14021).
394+
identically to lanes 2 to 4 (#14021). Lane 5 is narrower: it attaches only
395+
where the deployment declares several replicas (`OS_CLUSTER_REPLICAS` greater
396+
than 1, or `OS_EXPECT_MULTI_NODE=true`) over the `redis` driver
397+
(`declaresMultiReplicaOnRedis`, cloud#3814 R3), so a single node emits
398+
exactly the local `settings:changed` events it always did. It binds at
399+
`kernel:bootstrapped`, one phase after the others, because the settings
400+
service binds its engine at `kernel:ready` and a peer's change must not reach
401+
a subscriber before that. A received
402+
settings change is announced locally and never published again, so no
403+
replica echoes it.
390404

391405
#### Lane 1 — `metadata.changed` (the metadata service cache)
392406

‎packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts‎

Lines changed: 179 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
* without that control a guard is indistinguishable from "never say bridged".
2525
*/
2626

27-
import { describe, it, expect, vi } from 'vitest';
27+
import { afterEach, describe, it, expect, vi } from 'vitest';
2828
import type { PluginContext } from '@objectstack/core';
2929
import { MetadataClusterBridgePlugin } from './metadata-cluster-bridge-plugin.js';
3030
import { ClusterDriverLiveness, offerClusterDriverLiveness } from './cluster-resync.js';
@@ -67,13 +67,23 @@ interface HarnessOptions {
6767
automation?: 'none' | 'bare' | 'real';
6868
/** When true, the automation seam throws on attach. */
6969
automationAttachThrows?: boolean;
70+
/**
71+
* [#31597] The `settings` slot: `'none'` (getService throws — the default,
72+
* so every earlier case reads exactly as it did), `'bare'` (present, no
73+
* attachSettingsChangePubSub — an older implementation), or `'real'`
74+
* (exposes attachSettingsChangePubSub).
75+
*/
76+
settings?: 'none' | 'bare' | 'real';
77+
/** When true, the settings seam throws on attach. */
78+
settingsAttachThrows?: boolean;
7079
}
7180

7281
function makeHarness(opts: HarnessOptions = {}) {
7382
const {
7483
driver = 'redis', metadata = 'fallback', protocol = 'real',
7584
datasourceAdmin = 'none', datasourceAttachThrows = false,
7685
automation = 'none', automationAttachThrows = false,
86+
settings = 'none', settingsAttachThrows = false,
7787
} = opts;
7888

7989
const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
@@ -93,6 +103,12 @@ function makeHarness(opts: HarnessOptions = {}) {
93103
return detachCredential;
94104
});
95105

106+
const detachSettings = vi.fn();
107+
const attachSettings = vi.fn((_pubsub: unknown, _nodeId: string) => {
108+
if (settingsAttachThrows) throw new Error('settings attach exploded');
109+
return detachSettings;
110+
});
111+
96112
const pubsub = { publish: vi.fn(), subscribe: vi.fn(), close: vi.fn() };
97113
const cluster =
98114
driver === null
@@ -115,6 +131,10 @@ function makeHarness(opts: HarnessOptions = {}) {
115131
automation === 'none' ? undefined
116132
: automation === 'bare' ? { execute: vi.fn() }
117133
: { attachConnectorCredentialPubSub: attachCredential };
134+
const settingsService =
135+
settings === 'none' ? undefined
136+
: settings === 'bare' ? { get: vi.fn(), subscribe: vi.fn() }
137+
: { attachSettingsChangePubSub: attachSettings };
118138

119139
const hooks = new Map<string, Array<() => Promise<void> | void>>();
120140
const ctx = {
@@ -145,6 +165,10 @@ function makeHarness(opts: HarnessOptions = {}) {
145165
if (!automationService) throw new Error('service not found: automation');
146166
return automationService;
147167
}
168+
if (name === 'settings') {
169+
if (!settingsService) throw new Error('service not found: settings');
170+
return settingsService;
171+
}
148172
throw new Error(`service not found: ${name}`);
149173
},
150174
} as unknown as PluginContext;
@@ -158,6 +182,7 @@ function makeHarness(opts: HarnessOptions = {}) {
158182
attachMetadata, detachMetadata, attachMutation, detachMutation,
159183
attachDatasource, detachDatasource,
160184
attachCredential, detachCredential,
185+
attachSettings, detachSettings,
161186
};
162187
}
163188

@@ -592,3 +617,156 @@ describe('cluster.resync — every attached lane re-reads what an outage made it
592617
expect(h.resyncCredential).not.toHaveBeenCalled();
593618
});
594619
});
620+
621+
describe('[#31597] lane 5 — the settings service’s settings.changed fan-out, behind declared replicas over redis', () => {
622+
afterEach(() => {
623+
vi.unstubAllEnvs();
624+
});
625+
/** Declare (or not) several replicas, the R3 switch the lane keys on. */
626+
const declare = (replicas: string) => {
627+
vi.stubEnv('OS_CLUSTER_REPLICAS', replicas);
628+
vi.stubEnv('OS_EXPECT_MULTI_NODE', '');
629+
};
630+
631+
it('⭐ attaches with the cluster’s pubsub and node id when 2 replicas are declared over redis, and reports it', async () => {
632+
declare('2');
633+
const h = makeHarness({ settings: 'real' });
634+
await new MetadataClusterBridgePlugin().init(h.ctx);
635+
await h.fire('kernel:ready');
636+
await h.fire('kernel:bootstrapped');
637+
expect(h.attachSettings).toHaveBeenCalledTimes(1);
638+
expect(h.attachSettings).toHaveBeenCalledWith(h.pubsub, 'node-a');
639+
expect(infoLines(h).some((l) => l.includes('bridged settings.changed'))).toBe(true);
640+
});
641+
642+
it('binds at kernel:bootstrapped, after the settings service bound its engine at kernel:ready', async () => {
643+
declare('2');
644+
const h = makeHarness({ settings: 'real' });
645+
await new MetadataClusterBridgePlugin().init(h.ctx);
646+
await h.fire('kernel:ready');
647+
expect(h.attachSettings).not.toHaveBeenCalled();
648+
await h.fire('kernel:bootstrapped');
649+
expect(h.attachSettings).toHaveBeenCalledTimes(1);
650+
});
651+
652+
it('CONTROL — the redis driver with no declaration attaches nothing and says nothing above debug', async () => {
653+
declare('');
654+
const h = makeHarness({ settings: 'real' });
655+
await new MetadataClusterBridgePlugin().init(h.ctx);
656+
await h.fire('kernel:ready');
657+
await h.fire('kernel:bootstrapped');
658+
expect(h.attachSettings).not.toHaveBeenCalled();
659+
expect(infoLines(h).some((l) => l.includes('settings.changed'))).toBe(false);
660+
expect(warnLines(h).some((l) => l.includes('settings'))).toBe(false);
661+
expect(debugLines(h).some((l) => l.includes('settings fan-out skipped'))).toBe(true);
662+
// The other lanes keep their own guard: lane 2 still attaches on redis.
663+
expect(h.attachMutation).toHaveBeenCalledTimes(1);
664+
});
665+
666+
it('one declared replica is a single node: no lane', async () => {
667+
declare('1');
668+
const h = makeHarness({ settings: 'real' });
669+
await new MetadataClusterBridgePlugin().init(h.ctx);
670+
await h.fire('kernel:ready');
671+
await h.fire('kernel:bootstrapped');
672+
expect(h.attachSettings).not.toHaveBeenCalled();
673+
});
674+
675+
it('declared replicas over a driver other than redis: no lane', async () => {
676+
declare('3');
677+
const h = makeHarness({ settings: 'real', driver: 'postgres' });
678+
await new MetadataClusterBridgePlugin().init(h.ctx);
679+
await h.fire('kernel:ready');
680+
await h.fire('kernel:bootstrapped');
681+
expect(h.attachSettings).not.toHaveBeenCalled();
682+
});
683+
684+
it('declared replicas over the in-process memory driver: no lane', async () => {
685+
declare('3');
686+
const h = makeHarness({ settings: 'real', driver: 'memory' });
687+
await new MetadataClusterBridgePlugin().init(h.ctx);
688+
await h.fire('kernel:ready');
689+
await h.fire('kernel:bootstrapped');
690+
expect(h.attachSettings).not.toHaveBeenCalled();
691+
});
692+
693+
it('skips quietly when no settings service is registered, or it does not expose the seam', async () => {
694+
declare('2');
695+
for (const settings of ['none', 'bare'] as const) {
696+
const h = makeHarness({ settings });
697+
await new MetadataClusterBridgePlugin().init(h.ctx);
698+
await h.fire('kernel:ready');
699+
await h.fire('kernel:bootstrapped');
700+
expect(h.attachSettings).not.toHaveBeenCalled();
701+
expect(warnLines(h).some((l) => l.includes('settings'))).toBe(false);
702+
expect(debugLines(h).some((l) => l.includes('settings fan-out'))).toBe(true);
703+
}
704+
});
705+
706+
it('a throwing attach is reported and does not take the other lanes down', async () => {
707+
declare('2');
708+
const h = makeHarness({ settings: 'real', settingsAttachThrows: true, automation: 'real' });
709+
await new MetadataClusterBridgePlugin().init(h.ctx);
710+
await h.fire('kernel:ready');
711+
await h.fire('kernel:bootstrapped');
712+
expect(h.logger.error).toHaveBeenCalledWith(
713+
'MetadataClusterBridgePlugin: settings-lane attach failed',
714+
expect.any(Error),
715+
);
716+
expect(h.attachMutation).toHaveBeenCalledTimes(1);
717+
expect(h.attachCredential).toHaveBeenCalledTimes(1);
718+
});
719+
720+
it('kernel:shutdown detaches lane 5, and a throwing lane-4 detach does not strand it', async () => {
721+
declare('2');
722+
const h = makeHarness({ settings: 'real', automation: 'real' });
723+
h.detachCredential.mockImplementation(() => {
724+
throw new Error('credential detach exploded');
725+
});
726+
await new MetadataClusterBridgePlugin().init(h.ctx);
727+
await h.fire('kernel:ready');
728+
await h.fire('kernel:bootstrapped');
729+
await h.fire('kernel:shutdown');
730+
expect(h.detachSettings).toHaveBeenCalledTimes(1);
731+
});
732+
733+
describe('cluster.resync', () => {
734+
function resyncHarness() {
735+
const h = makeHarness({ settings: 'real' });
736+
const resyncSettings = vi.fn(async () => {});
737+
Object.assign(h.ctx.getService<Record<string, unknown>>('settings'), {
738+
resyncSettingsChangePubSub: resyncSettings,
739+
});
740+
const liveness = new ClusterDriverLiveness({ driver: 'redis', nodeId: 'node-a', logger: { warn: vi.fn(), info: vi.fn() } });
741+
offerClusterDriverLiveness(h.ctx.getService<object>('cluster'), liveness);
742+
const outage = async () => {
743+
liveness.reportUp('command');
744+
liveness.reportDown('command', new Error('ECONNREFUSED'));
745+
liveness.reportUp('command');
746+
await new Promise((r) => setTimeout(r, 0));
747+
};
748+
return { ...h, outage, resyncSettings };
749+
}
750+
751+
it('the settings lane re-reads once per recovered outage', async () => {
752+
declare('2');
753+
const h = resyncHarness();
754+
await new MetadataClusterBridgePlugin().init(h.ctx);
755+
await h.fire('kernel:ready');
756+
await h.fire('kernel:bootstrapped');
757+
await h.outage();
758+
expect(h.resyncSettings).toHaveBeenCalledTimes(1);
759+
expect(infoLines(h).some((l) => l.includes('resynced settings.changed'))).toBe(true);
760+
});
761+
762+
it('CONTROL — undeclared, the lane never attached, so a reconnect calls nothing', async () => {
763+
declare('');
764+
const h = resyncHarness();
765+
await new MetadataClusterBridgePlugin().init(h.ctx);
766+
await h.fire('kernel:ready');
767+
await h.fire('kernel:bootstrapped');
768+
await h.outage();
769+
expect(h.resyncSettings).not.toHaveBeenCalled();
770+
});
771+
});
772+
});

0 commit comments

Comments
 (0)