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
21 changes: 21 additions & 0 deletions .changeset/31596-redis-outage-no-crash-resync.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/service-cluster': patch
'@objectstack/service-cluster-redis': patch
'@objectstack/service-job': patch
'@objectstack/metadata': patch
'@objectstack/service-datasource': patch
'@objectstack/service-automation': patch
---

fix(cluster): a Redis outage no longer crashes replicas, is logged once, and caches re-read on reconnect

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

Every API addition below is a new export or an optional member (a widening). The one new default is the bounded command time on the redis driver. Multi-replica deployments on the `redis` cluster driver only. The single-node default (the in-process `memory` driver, no declared replicas) behaves exactly as before: it never loses a connection, so none of the paths below runs on it.

- **No crash on a dead lock (`@objectstack/service-job`).** `CronJobAdapter` leader-elects every scheduled fire on the cluster lock. When the lock store was unreachable, `acquire` rejected inside a timer callback, the rejection went unhandled, and every replica exited at its next tick. A failed `acquire` now skips that fire (no node can prove it alone runs it) and the next tick asks again; a failed `release` after the fire ran is absorbed (the lease expires on its TTL). The adapter logs ONE warning per lock outage — not one per tick — and one info line when the lock answers again. No process-wide `unhandledRejection` handler is added.
- **The driver watches its connections (`@objectstack/service-cluster-redis`).** Every ioredis client the driver holds (the command connection and the pub/sub subscriber) now has an `error` listener, so ioredis no longer prints `[ioredis] Unhandled error event` with a stack per reconnect attempt. The driver logs one warning when the store becomes unreachable (naming `host:port`, never the URL or a password) and one info line when it returns. New option: `driverOptions.logger` (`{ warn, info? }`, default `console`).
- **Bounded commands.** `createRedisClient()` now sets `commandTimeout: REDIS_COMMAND_TIMEOUT_MS` (2000 ms; exported). A black-holed Redis (a socket that accepts and never answers) used to hold a caller about 30 s — a sign-in counting through the shared cache included, since the cache derives its connection with `client.duplicate()`, which inherits the bound. Every command the driver and the shared cache issue is O(1); a caller that needs longer passes its own `options.commandTimeout`, or its own client through `driverOptions.client`.
- **`cluster.resync` (`@objectstack/service-cluster`).** Cross-node cache hints ride at-most-once pub/sub, so a hint published during an outage was lost and a peer kept serving what it had cached until restart. When the driver's connection returns after an outage it now emits ONE local `cluster.resync` event (never published to peers). New exports: `onClusterResync(cluster, handler)` to subscribe (a no-op on the memory driver), `readClusterDriverHealth(cluster)` (a passive reading of the driver's connection state, type `ClusterDriverLivenessHealth`: `{ driver, nodeId, state: 'unknown' | 'up' | 'down', since, outages, lastError? }`, `undefined` on the memory driver; the active store probe `/ready` uses is `probeClusterDriverHealth()`), and `ClusterDriverLiveness` / `offerClusterDriverLiveness` for driver authors, plus `CLUSTER_RESYNC_EVENT`, `describeConnectionError` and `redactCredentials`.
- **The caches re-read on it.** `MetadataClusterBridgePlugin` calls each attached lane's resync seam: `MetadataManager.resyncClusterPubSub()` (`@objectstack/metadata`: drops every list cache and the endpoint index, so the next `list()` re-reads the loaders; registry entries are kept), `DatasourceAdminService.resyncDatasourceMutationPubSub()` (`@objectstack/service-datasource`: re-converges every stored datasource and every held pool from this replica's own read), and `AutomationEngine.resyncConnectorCredentialPubSub()` (`@objectstack/service-automation`: the connector reconcile a peer's signal runs; the connector-credential door gains an optional `resyncFromCluster()`). `AuthzClusterBridgePlugin` advances the engine's write epoch (reason `remote`), retiring cached grants. The `metadata.mutated` registry lane has no resync yet; it still converges per item on delivered signals and fully at boot.
46 changes: 46 additions & 0 deletions content/docs/kernel/cluster.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,24 @@ channel's own doc comment:
exceeds at-most-once delivery (§4.2), so a lost message is not retried.
Each lane narrows the staleness window this always had — "until the next
full reload on restart" — to "one network hop"; it does not promise more.
- **Resync after a driver outage.** A message lost while the store is
unreachable is not retried, but a replica no longer waits for its restart
to recover it. When a remote driver's connection returns after an outage,
the driver emits ONE local `cluster.resync` event on that replica. The
event is never published to peers; each replica emits its own when its own
connection returns. `MetadataClusterBridgePlugin` re-reads every attached
lane on it: lane 1 drops the metadata list caches
(`MetadataManager.resyncClusterPubSub()`), lane 3 re-converges every stored
datasource and every held pool
(`DatasourceAdminService.resyncDatasourceMutationPubSub()`), and lane 4
runs the connector reconcile
(`AutomationEngine.resyncConnectorCredentialPubSub()`).
`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
`memory` cluster driver, described for lane 1 immediately below, applies
Expand Down Expand Up @@ -703,6 +721,34 @@ membership view exists at boot. It is the right input for telling an operator
about the configuration they wrote, and is deliberately not sufficient for
enforcement.

The `redis` driver has two outage settings:

- `driverOptions.logger` (`{ warn, info? }`, default `console`): where the driver writes
its outage lines. It logs ONE warning when the store becomes unreachable,
naming `host:port` and never the URL or a password, and one info line when
the store returns. It does not log a line per failed command.
- Every connection the driver creates is built with `commandTimeout` set to
`REDIS_COMMAND_TIMEOUT_MS` (2000 ms, exported by
`@objectstack/service-cluster-redis`). A command, queued or sent, fails
after 2 s instead of hanging on a black-holed store. The shared cache
derives its connection with `client.duplicate()` and inherits the same
bound. To run longer commands, pass your own client through
`driverOptions.client`.

Two readings of the same driver answer different questions:

- `readClusterDriverHealth(cluster)` is **passive**. It reports what the
driver's connections last said (`error`, `close`, `ready`), sends nothing to
the store, and costs nothing. It returns a `ClusterDriverLivenessHealth`:
`{ driver, nodeId, state: 'unknown' | 'up' | 'down', since, outages, lastError? }`.
A black-holed store whose socket never errors still reads as `up`.
- `probeClusterDriverHealth(cluster, driver)` is **active**. It sends a
bounded `PING` to the store, and it is what `/ready` reports. It returns a
`ClusterDriverHealth`: `{ driver, reachable, reason? }`. It does see a
black-holed store, because the `PING` times out.

Both return `undefined` on the `memory` driver.

Every cluster primitive selects its implementation from `cluster.driver`.
When the field is absent, `Runtime` auto-registers the in-memory, single-node
driver (pass `cluster: false` to skip that auto-registration). No production
Expand Down
54 changes: 54 additions & 0 deletions packages/metadata/src/metadata-manager-cluster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -511,3 +511,57 @@ describe('MetadataManager — default `memory` cluster driver does not cross OS
}
});
});

describe('MetadataManager — resyncClusterPubSub() converges a hint lost in a cluster outage', () => {
const view = (name: string, title: string) => ({ name, title, object: 'account' });

/** `makeCluster()` over a bus that drops every publish while `down` — the at-most-once loss. */
function makeLossyCluster() {
const bus = new TestPubSub();
const state = { down: false };
const publish = bus.publish.bind(bus);
bus.publish = (async (channel: string, payload: unknown) => {
if (state.down) return;
await publish(channel, payload);
}) as typeof bus.publish;
const store = new SharedStoreLoader();
const a = new MetadataManager({ formats: ['json'], loaders: [store] });
const b = new MetadataManager({ formats: ['json'], loaders: [store] });
a.attachClusterPubSub(bus, 'node-A');
b.attachClusterPubSub(bus, 'node-B');
return { store, a, b, state };
}

it('a peer write whose hint was lost stays invisible until the resync, then list() re-reads it', async () => {
const { store, a, b, state } = makeLossyCluster();
await store.save('view', 'v_existing', view('v_existing', 'existing'));
expect(viewNames(await b.list('view'))).toEqual(['v_existing']);

state.down = true;
await a.register('view', 'v_new', view('v_new', 'new'));
state.down = false;
// The loss: B still serves its pre-write list (the 30s TTL has not lapsed).
expect(viewNames(await b.list('view'))).toEqual(['v_existing']);

b.resyncClusterPubSub();
expect(cachedTypes(b)).toEqual([]);
expect(viewNames(await b.list('view'))).toEqual(['v_existing', 'v_new']);
});

it('keeps registerInMemory() artefacts, which no loader can restore', async () => {
const { b } = makeLossyCluster();
b.registerInMemory('datasource', 'code_ds', { name: 'code_ds', origin: 'code' });
await b.list('datasource');
b.resyncClusterPubSub();
expect(await b.get('datasource', 'code_ds')).toEqual({ name: 'code_ds', origin: 'code' });
});

it('CONTROL — no transport attached (single node): resync drops nothing', async () => {
const store = new SharedStoreLoader();
const solo = new MetadataManager({ formats: ['json'], loaders: [store] });
await store.save('view', 'v1', view('v1', 'one'));
await solo.list('view');
solo.resyncClusterPubSub();
expect(cachedTypes(solo)).toEqual(['view']);
});
});
30 changes: 30 additions & 0 deletions packages/metadata/src/metadata-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3433,6 +3433,36 @@ export class MetadataManager implements IMetadataService {
return () => this.detachClusterPubSub();
}

/**
* The `cluster.resync` answer for this lane: the cluster driver's connection
* came back after an outage, during which any `metadata.changed` a peer
* published was lost (the bus is at-most-once). Called by
* `MetadataClusterBridgePlugin` in `@objectstack/service-cluster` on the
* driver's local `cluster.resync` event; a no-op until a transport is
* attached.
*
* The receipt of a nameless event, for every type this manager holds a
* list for: {@link invalidateForForeignWrite} with no name drops the list
* cache (and the endpoint index), so the next `list()` re-reads the loaders
* — where a write the lost hint announced already is. Registry ENTRIES are
* kept, for the reason that method gives: which names a peer wrote is
* exactly what the lost hints carried, and dropping a whole type store would
* evict `registerInMemory()` artefacts no loader can restore.
*/
resyncClusterPubSub(): void {
if (!this.clusterPubSub) return;
const types = new Set<string>([
...this.listCache.keys(),
...this.inflightListReads.keys(),
MetadataManager.ENDPOINT_METADATA_TYPE,
]);
for (const type of types) this.invalidateForForeignWrite(type);
this.logger.info('MetadataManager resynced after a cluster outage: list caches dropped', {
nodeId: this.clusterNodeId,
types: types.size,
});
}

/** Tear down cluster wiring. Safe to call multiple times. */
detachClusterPubSub(): void {
if (this.clusterUnsubscribe) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,3 +301,60 @@ describe('[#27428] the lane carries an address, and the publisher drops its own'
expect(out.text()).toContain(`connector credential '${REF}' was written on node 'node-b'; reconciling the connectors on node 'node-a'`);
});
});

describe('resyncConnectorCredentialPubSub() — a credential write whose signal an outage lost converges on the resync', () => {
/** `sharedBus()` that drops every publish while `down`: the at-most-once loss an outage causes. */
function lossyBus() {
const shared = sharedBus();
const state = { down: false };
const publish = shared.bus.publish.bind(shared.bus);
shared.bus.publish = (async (channel: string, payload: unknown, opts?: never) => {
if (state.down) return;
await publish(channel, payload, opts);
}) as typeof shared.bus.publish;
return { ...shared, state };
}

it('B holds its refused instance while A’s correction is lost, and re-materializes on the resync', async () => {
const ql = await sharedDatabase();
const { bus, state } = lossyBus();
const a = await replica(ql, 'node-a', bus);
const b = await replica(ql, 'node-b', bus);
a.provider.state.reject = true;
b.provider.state.reject = true;
await a.engine.setConnectorCredential({ ref: REF, value: DUMMY_VALUE, context: ADMIN });
await vi.waitFor(() => expect(b.held()).toContain('refused'));

a.provider.state.reject = false;
b.provider.state.reject = false;
state.down = true;
await a.engine.setConnectorCredential({ ref: REF, value: DUMMY_VALUE_2, context: ADMIN });
state.down = false;
for (let i = 0; i < 5; i++) await flush();
expect(b.held()).toContain('refused');

await b.engine.resyncConnectorCredentialPubSub();
expect(b.held()).toBeUndefined();
expect(b.provider.last()).toBe(DUMMY_VALUE_2);
});

it('CONTROL — no transport attached (single node): the resync reconciles nothing', async () => {
// The same lost-correction shape as above, with no transport on either
// replica: B's resync is inert, so B keeps its refused instance (it
// converges on its own reload or restart, as before this change).
const ql = await sharedDatabase();
const a = await replica(ql, 'node-a', undefined);
const b = await replica(ql, 'node-b', undefined);
b.provider.state.reject = true;
await b.engine.setConnectorCredential({ ref: REF, value: DUMMY_VALUE, context: ADMIN });
expect(b.held()).toContain('refused');

b.provider.state.reject = false;
await a.engine.setConnectorCredential({ ref: REF, value: DUMMY_VALUE_2, context: ADMIN });
const before = b.provider.state.materialized.length;
await b.engine.resyncConnectorCredentialPubSub();
for (let i = 0; i < 5; i++) await flush();
expect(b.held()).toContain('refused');
expect(b.provider.state.materialized).toHaveLength(before);
});
});
20 changes: 20 additions & 0 deletions packages/services/service-automation/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2616,6 +2616,13 @@ export interface ConnectorCredentialDoor {
* {@link AutomationEngine.attachConnectorCredentialPubSub}.
*/
attachClusterPubSub(pubsub: IPubSub, nodeId: string): () => void;
/**
* The `cluster.resync` answer: reconcile from the shared rows after a
* cluster outage lost peer writes — see
* {@link AutomationEngine.resyncConnectorCredentialPubSub}. Optional, so a
* door written before it still attaches; without it a resync does nothing.
*/
resyncFromCluster?(): Promise<void>;
}

/**
Expand Down Expand Up @@ -5025,6 +5032,19 @@ export class AutomationEngine implements IAutomationService {
return this.requireConnectorCredentialDoor('attachConnectorCredentialPubSub()').attachClusterPubSub(pubsub, nodeId);
}

/**
* The `cluster.resync` answer for lane 4: the cluster driver's connection
* came back after an outage, during which any `connector-credential.mutated`
* a peer published was lost (the bus is at-most-once). Called by
* `MetadataClusterBridgePlugin` on the driver's local `cluster.resync`
* event. Runs the reconcile a received signal runs — it re-reads the shared
* credential rows, so every instance naming a reference that changed during
* the outage re-materializes. A no-op until a transport is attached.
*/
async resyncConnectorCredentialPubSub(): Promise<void> {
await this.requireConnectorCredentialDoor('resyncConnectorCredentialPubSub()').resyncFromCluster?.();
}

/** [#27237] `IAutomationService.listConnectorCredentialRefs` — references and states, never a value. */
async listConnectorCredentialRefs(): Promise<ConnectorCredentialRef[]> {
return this.requireConnectorCredentialDoor('listConnectorCredentialRefs()').list();
Expand Down
17 changes: 17 additions & 0 deletions packages/services/service-automation/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1729,6 +1729,7 @@ export class AutomationServicePlugin implements Plugin {
set: (request) => this.setConnectorCredential(ctx, request),
clear: (request) => this.clearConnectorCredential(ctx, request),
attachClusterPubSub: (pubsub, nodeId) => this.attachCredentialClusterPubSub(ctx, pubsub, nodeId),
resyncFromCluster: () => this.resyncCredentialClusterPubSub(ctx),
});

// [ADR-0015 D7] The connector credential source: a datasource that
Expand Down Expand Up @@ -4803,6 +4804,22 @@ export class AutomationServicePlugin implements Plugin {
return () => this.detachCredentialClusterPubSub();
}

/**
* The `cluster.resync` answer for the credential lane: the reconcile a
* peer's signal runs, once, because which references changed during the
* outage is what the lost signals carried. A no-op until a transport is
* attached. A failure is the caller's to log (the bridge does).
*/
private async resyncCredentialClusterPubSub(ctx: PluginContext): Promise<void> {
const cluster = this.credentialCluster;
if (!cluster) return;
ctx.logger.info(
`[Automation] the cluster connection returned after an outage; reconciling the connectors on node '${cluster.nodeId}' `
+ 'in case a peer wrote a connector credential meanwhile.',
);
await this.materializeDeclaredConnectors(ctx, { fatal: false });
}

/** [#27428] Tear down the credential cluster wiring. Safe to call multiple times. */
private detachCredentialClusterPubSub(): void {
const current = this.credentialCluster;
Expand Down
2 changes: 2 additions & 0 deletions packages/services/service-cluster-redis/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
"ioredis": "^6.0.0"
},
"devDependencies": {
"@objectstack/core": "workspace:*",
"@objectstack/service-job": "workspace:*",
"@types/node": "^26.6.5",
"ioredis-mock": "^8.13.1",
"typescript": "^6.0.3",
Expand Down
Loading
Loading