Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/31597-settings-changes-reach-every-replica.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@objectstack/service-settings': patch
'@objectstack/service-cluster': patch
---

feat(cluster): a settings change on one replica reaches every replica

Clause-②: yes (widening)
Metadata-protocol: none

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.

`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.

- **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.
- **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()`.
- **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.
28 changes: 21 additions & 7 deletions content/docs/kernel/cluster.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ cache compare it on receipt.
### 6.2 The cluster-invalidation family

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

Expand All @@ -338,17 +338,20 @@ goes stale when a shared record changes on a different node:
| 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 |
| 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 |
| 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 |
| 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 |

Lanes 2 to 4 share one contract, stated once here rather than in each
Lanes 2 to 5 share one contract, stated once here rather than in each
channel's own doc comment:

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

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

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* without that control a guard is indistinguishable from "never say bridged".
*/

import { describe, it, expect, vi } from 'vitest';
import { afterEach, describe, it, expect, vi } from 'vitest';
import type { PluginContext } from '@objectstack/core';
import { MetadataClusterBridgePlugin } from './metadata-cluster-bridge-plugin.js';
import { ClusterDriverLiveness, offerClusterDriverLiveness } from './cluster-resync.js';
Expand Down Expand Up @@ -67,13 +67,23 @@ interface HarnessOptions {
automation?: 'none' | 'bare' | 'real';
/** When true, the automation seam throws on attach. */
automationAttachThrows?: boolean;
/**
* [#31597] The `settings` slot: `'none'` (getService throws — the default,
* so every earlier case reads exactly as it did), `'bare'` (present, no
* attachSettingsChangePubSub — an older implementation), or `'real'`
* (exposes attachSettingsChangePubSub).
*/
settings?: 'none' | 'bare' | 'real';
/** When true, the settings seam throws on attach. */
settingsAttachThrows?: boolean;
}

function makeHarness(opts: HarnessOptions = {}) {
const {
driver = 'redis', metadata = 'fallback', protocol = 'real',
datasourceAdmin = 'none', datasourceAttachThrows = false,
automation = 'none', automationAttachThrows = false,
settings = 'none', settingsAttachThrows = false,
} = opts;

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

const detachSettings = vi.fn();
const attachSettings = vi.fn((_pubsub: unknown, _nodeId: string) => {
if (settingsAttachThrows) throw new Error('settings attach exploded');
return detachSettings;
});

const pubsub = { publish: vi.fn(), subscribe: vi.fn(), close: vi.fn() };
const cluster =
driver === null
Expand All @@ -115,6 +131,10 @@ function makeHarness(opts: HarnessOptions = {}) {
automation === 'none' ? undefined
: automation === 'bare' ? { execute: vi.fn() }
: { attachConnectorCredentialPubSub: attachCredential };
const settingsService =
settings === 'none' ? undefined
: settings === 'bare' ? { get: vi.fn(), subscribe: vi.fn() }
: { attachSettingsChangePubSub: attachSettings };

const hooks = new Map<string, Array<() => Promise<void> | void>>();
const ctx = {
Expand Down Expand Up @@ -145,6 +165,10 @@ function makeHarness(opts: HarnessOptions = {}) {
if (!automationService) throw new Error('service not found: automation');
return automationService;
}
if (name === 'settings') {
if (!settingsService) throw new Error('service not found: settings');
return settingsService;
}
throw new Error(`service not found: ${name}`);
},
} as unknown as PluginContext;
Expand All @@ -158,6 +182,7 @@ function makeHarness(opts: HarnessOptions = {}) {
attachMetadata, detachMetadata, attachMutation, detachMutation,
attachDatasource, detachDatasource,
attachCredential, detachCredential,
attachSettings, detachSettings,
};
}

Expand Down Expand Up @@ -592,3 +617,156 @@ describe('cluster.resync — every attached lane re-reads what an outage made it
expect(h.resyncCredential).not.toHaveBeenCalled();
});
});

describe('[#31597] lane 5 — the settings service’s settings.changed fan-out, behind declared replicas over redis', () => {
afterEach(() => {
vi.unstubAllEnvs();
});
/** Declare (or not) several replicas, the R3 switch the lane keys on. */
const declare = (replicas: string) => {
vi.stubEnv('OS_CLUSTER_REPLICAS', replicas);
vi.stubEnv('OS_EXPECT_MULTI_NODE', '');
};

it('⭐ attaches with the cluster’s pubsub and node id when 2 replicas are declared over redis, and reports it', async () => {
declare('2');
const h = makeHarness({ settings: 'real' });
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
expect(h.attachSettings).toHaveBeenCalledTimes(1);
expect(h.attachSettings).toHaveBeenCalledWith(h.pubsub, 'node-a');
expect(infoLines(h).some((l) => l.includes('bridged settings.changed'))).toBe(true);
});

it('binds at kernel:bootstrapped, after the settings service bound its engine at kernel:ready', async () => {
declare('2');
const h = makeHarness({ settings: 'real' });
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
expect(h.attachSettings).not.toHaveBeenCalled();
await h.fire('kernel:bootstrapped');
expect(h.attachSettings).toHaveBeenCalledTimes(1);
});

it('CONTROL — the redis driver with no declaration attaches nothing and says nothing above debug', async () => {
declare('');
const h = makeHarness({ settings: 'real' });
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
expect(h.attachSettings).not.toHaveBeenCalled();
expect(infoLines(h).some((l) => l.includes('settings.changed'))).toBe(false);
expect(warnLines(h).some((l) => l.includes('settings'))).toBe(false);
expect(debugLines(h).some((l) => l.includes('settings fan-out skipped'))).toBe(true);
// The other lanes keep their own guard: lane 2 still attaches on redis.
expect(h.attachMutation).toHaveBeenCalledTimes(1);
});

it('one declared replica is a single node: no lane', async () => {
declare('1');
const h = makeHarness({ settings: 'real' });
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
expect(h.attachSettings).not.toHaveBeenCalled();
});

it('declared replicas over a driver other than redis: no lane', async () => {
declare('3');
const h = makeHarness({ settings: 'real', driver: 'postgres' });
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
expect(h.attachSettings).not.toHaveBeenCalled();
});

it('declared replicas over the in-process memory driver: no lane', async () => {
declare('3');
const h = makeHarness({ settings: 'real', driver: 'memory' });
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
expect(h.attachSettings).not.toHaveBeenCalled();
});

it('skips quietly when no settings service is registered, or it does not expose the seam', async () => {
declare('2');
for (const settings of ['none', 'bare'] as const) {
const h = makeHarness({ settings });
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
expect(h.attachSettings).not.toHaveBeenCalled();
expect(warnLines(h).some((l) => l.includes('settings'))).toBe(false);
expect(debugLines(h).some((l) => l.includes('settings fan-out'))).toBe(true);
}
});

it('a throwing attach is reported and does not take the other lanes down', async () => {
declare('2');
const h = makeHarness({ settings: 'real', settingsAttachThrows: true, automation: 'real' });
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
expect(h.logger.error).toHaveBeenCalledWith(
'MetadataClusterBridgePlugin: settings-lane attach failed',
expect.any(Error),
);
expect(h.attachMutation).toHaveBeenCalledTimes(1);
expect(h.attachCredential).toHaveBeenCalledTimes(1);
});

it('kernel:shutdown detaches lane 5, and a throwing lane-4 detach does not strand it', async () => {
declare('2');
const h = makeHarness({ settings: 'real', automation: 'real' });
h.detachCredential.mockImplementation(() => {
throw new Error('credential detach exploded');
});
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
await h.fire('kernel:shutdown');
expect(h.detachSettings).toHaveBeenCalledTimes(1);
});

describe('cluster.resync', () => {
function resyncHarness() {
const h = makeHarness({ settings: 'real' });
const resyncSettings = vi.fn(async () => {});
Object.assign(h.ctx.getService<Record<string, unknown>>('settings'), {
resyncSettingsChangePubSub: resyncSettings,
});
const liveness = new ClusterDriverLiveness({ driver: 'redis', nodeId: 'node-a', logger: { warn: vi.fn(), info: vi.fn() } });
offerClusterDriverLiveness(h.ctx.getService<object>('cluster'), liveness);
const outage = async () => {
liveness.reportUp('command');
liveness.reportDown('command', new Error('ECONNREFUSED'));
liveness.reportUp('command');
await new Promise((r) => setTimeout(r, 0));
};
return { ...h, outage, resyncSettings };
}

it('the settings lane re-reads once per recovered outage', async () => {
declare('2');
const h = resyncHarness();
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
await h.outage();
expect(h.resyncSettings).toHaveBeenCalledTimes(1);
expect(infoLines(h).some((l) => l.includes('resynced settings.changed'))).toBe(true);
});

it('CONTROL — undeclared, the lane never attached, so a reconnect calls nothing', async () => {
declare('');
const h = resyncHarness();
await new MetadataClusterBridgePlugin().init(h.ctx);
await h.fire('kernel:ready');
await h.fire('kernel:bootstrapped');
await h.outage();
expect(h.resyncSettings).not.toHaveBeenCalled();
});
});
});
Loading
Loading