diff --git a/.changeset/31596-redis-outage-no-crash-resync.md b/.changeset/31596-redis-outage-no-crash-resync.md new file mode 100644 index 00000000000..0280f42cf42 --- /dev/null +++ b/.changeset/31596-redis-outage-no-crash-resync.md @@ -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. diff --git a/content/docs/kernel/cluster.mdx b/content/docs/kernel/cluster.mdx index 099ef159d85..1ea44980893 100644 --- a/content/docs/kernel/cluster.mdx +++ b/content/docs/kernel/cluster.mdx @@ -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 @@ -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 diff --git a/packages/metadata/src/metadata-manager-cluster.test.ts b/packages/metadata/src/metadata-manager-cluster.test.ts index 1b702e6c0c4..33772eb95f0 100644 --- a/packages/metadata/src/metadata-manager-cluster.test.ts +++ b/packages/metadata/src/metadata-manager-cluster.test.ts @@ -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']); + }); +}); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index 11d0f3c5638..e86efc1b2f8 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -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([ + ...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) { diff --git a/packages/services/service-automation/src/connector-credential-cluster.test.ts b/packages/services/service-automation/src/connector-credential-cluster.test.ts index 467a2a84f93..a7107482214 100644 --- a/packages/services/service-automation/src/connector-credential-cluster.test.ts +++ b/packages/services/service-automation/src/connector-credential-cluster.test.ts @@ -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); + }); +}); diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 0d024d71bbc..c735ddae032 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -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; } /** @@ -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 { + await this.requireConnectorCredentialDoor('resyncConnectorCredentialPubSub()').resyncFromCluster?.(); + } + /** [#27237] `IAutomationService.listConnectorCredentialRefs` — references and states, never a value. */ async listConnectorCredentialRefs(): Promise { return this.requireConnectorCredentialDoor('listConnectorCredentialRefs()').list(); diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 2ff161ede91..0b320c15542 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -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 @@ -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 { + 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; diff --git a/packages/services/service-cluster-redis/package.json b/packages/services/service-cluster-redis/package.json index 9efd0a0d264..2e6d6d90947 100644 --- a/packages/services/service-cluster-redis/package.json +++ b/packages/services/service-cluster-redis/package.json @@ -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", diff --git a/packages/services/service-cluster-redis/src/client.ts b/packages/services/service-cluster-redis/src/client.ts index cc2429d512f..aed728cee60 100644 --- a/packages/services/service-cluster-redis/src/client.ts +++ b/packages/services/service-cluster-redis/src/client.ts @@ -1,6 +1,23 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { Redis, type RedisOptions } from 'ioredis'; +import type { ClusterDriverLiveness } from '@objectstack/service-cluster'; + +/** + * The longest one Redis command may take before it fails: 2 s. + * + * Without a bound a black-holed Redis (a socket that accepts and never + * answers) holds every caller until ioredis' own connection limits give up — + * measured at about 30 s for a sign-in counting through the shared cache. + * Every command this driver and the cache it shares its connection with issue + * is O(1) (GET/SET/INCR/EVAL of a short script/PUBLISH), answered in well under + * a millisecond by a healthy server, so 2 s leaves three orders of magnitude + * for a loaded server or a cross-zone hop while keeping a request that touches + * an unreachable store to about 2 s. The bound applies to commands queued + * while the connection is down too (ioredis arms the timer before queueing). + * It is a default: `options.commandTimeout` overrides it. + */ +export const REDIS_COMMAND_TIMEOUT_MS = 2_000; /** * Options accepted by {@link createRedisClient}. @@ -40,6 +57,9 @@ export interface CreateRedisOptions { * Defaults applied when `existing` is absent: * - `lazyConnect: true` — don't crash boot if Redis is briefly down * - `maxRetriesPerRequest: 3` — bound the failure window before surfacing + * - `commandTimeout: REDIS_COMMAND_TIMEOUT_MS` — bound a black-holed server + * (see {@link REDIS_COMMAND_TIMEOUT_MS}); `client.duplicate()` inherits it, + * so the shared cache's derived connection is bounded the same way * - `enableAutoPipelining: true` — modest throughput boost for batch workloads * * @example @@ -56,6 +76,7 @@ export function createRedisClient(opts: CreateRedisOptions = {}): Redis { const base: RedisOptions = { lazyConnect: opts.lazyConnect ?? true, maxRetriesPerRequest: 3, + commandTimeout: REDIS_COMMAND_TIMEOUT_MS, enableAutoPipelining: true, }; @@ -73,3 +94,47 @@ export function createRedisClient(opts: CreateRedisOptions = {}): Redis { export function duplicateForPubSub(client: Redis): Redis { return client.duplicate(); } + +/** + * Report `client`'s connection transitions to `liveness` under `source`: an + * `error` or an unexpected `close` is a failure, `ready` is a recovery. + * + * Attaching the `error` listener is also what keeps ioredis from printing + * `[ioredis] Unhandled error event` with a stack per reconnect attempt: the + * liveness logs the outage once instead, credential-free. + * + * @returns a disposer that removes the three listeners — call it BEFORE a + * deliberate `quit()`, so the close that follows is not reported as an outage. + */ +export function watchRedisConnection( + client: Redis, + liveness: ClusterDriverLiveness, + source: string, +): () => void { + const onError = (err: unknown): void => liveness.reportDown(source, err); + const onClose = (): void => liveness.reportDown(source); + const onReady = (): void => liveness.reportUp(source); + client.on('error', onError); + client.on('close', onClose); + client.on('ready', onReady); + if (client.status === 'ready') liveness.reportUp(source); + let watching = true; + return () => { + if (!watching) return; + watching = false; + client.off('error', onError); + client.off('close', onClose); + client.off('ready', onReady); + }; +} + +/** + * `host:port` of `client`'s server — never the URL, which can carry a password. + * `undefined` when the client does not say (a mock, a socket path). + */ +export function describeRedisTarget(client: Redis): string | undefined { + const options = (client as { options?: { host?: unknown; port?: unknown; path?: unknown } }).options; + if (!options) return undefined; + if (typeof options.host === 'string' && options.port !== undefined) return `${options.host}:${String(options.port)}`; + return undefined; +} diff --git a/packages/services/service-cluster-redis/src/index.ts b/packages/services/service-cluster-redis/src/index.ts index be444f1fe04..cdc811a0a42 100644 --- a/packages/services/service-cluster-redis/src/index.ts +++ b/packages/services/service-cluster-redis/src/index.ts @@ -23,19 +23,29 @@ import type { Redis } from 'ioredis'; import { + ClusterDriverLiveness, ComposedClusterService, offerClusterDriverConnection, + offerClusterDriverLiveness, registerClusterDriver, + type ClusterDriverLivenessLogger, type DriverFactoryConfig, } from '@objectstack/service-cluster'; -import { createRedisClient } from './client.js'; +import { createRedisClient, describeRedisTarget, watchRedisConnection } from './client.js'; import { RedisPubSub } from './pubsub.js'; import { RedisLock } from './lock.js'; import { RedisKV } from './kv.js'; import { RedisCounter } from './counter.js'; // Re-exports for advanced composition. -export { createRedisClient, duplicateForPubSub, type CreateRedisOptions } from './client.js'; +export { + createRedisClient, + duplicateForPubSub, + watchRedisConnection, + describeRedisTarget, + REDIS_COMMAND_TIMEOUT_MS, + type CreateRedisOptions, +} from './client.js'; export { RedisPubSub, type RedisPubSubOptions } from './pubsub.js'; export { RedisLock, type RedisLockOptions } from './lock.js'; export { RedisKV, VersionMismatchError, type RedisKVOptions } from './kv.js'; @@ -55,6 +65,8 @@ export interface RedisDriverOptions { lockTtlMs?: number; /** Pub/sub subscriber error sink. */ onError?: (err: unknown, channel: string) => void; + /** Where the connection-outage lines go (one warning per outage). Default: `console`. */ + logger?: ClusterDriverLivenessLogger; } /** @@ -72,11 +84,22 @@ function redisDriverFactory(config: DriverFactoryConfig) { const keyPrefix = driverOpts.keyPrefix ?? 'os:'; const ttlMs = config.lockTtlMs ?? driverOpts.lockTtlMs; + // One liveness for both connections (command + subscriber): the outage is + // the store's, logged once; its end emits `cluster.resync` once. + const liveness = new ClusterDriverLiveness({ + driver: 'redis', + nodeId: config.nodeId, + target: describeRedisTarget(client), + logger: driverOpts.logger, + }); + const unwatchCommand = watchRedisConnection(client, liveness, 'command'); + const pubsub = new RedisPubSub({ client, nodeId: config.nodeId, keyPrefix, onError: driverOpts.onError, + liveness, }); const lock = new RedisLock({ client, @@ -104,10 +127,18 @@ function redisDriverFactory(config: DriverFactoryConfig) { // (`client.duplicate()`) and writes under `cache:`; this facade // keeps owning `client` and is the only one that closes it. offerClusterDriverConnection(facade, { driver: 'redis', client, keyPrefix }); + // Offer the liveness: `readClusterDriverHealth(cluster)` for a passive + // reading of the connection state (the active store probe is + // `probeClusterDriverHealth()`), `onClusterResync(cluster, …)` for every + // cache holding cross-node state. + offerClusterDriverLiveness(facade, liveness); // Wrap close() so we also tear down the publisher client if we own it. const originalClose = facade.close.bind(facade); facade.close = async () => { + // A deliberate close is not an outage: stop reporting before anything quits. + liveness.close(); + unwatchCommand(); await originalClose(); if (ownsClient) { try { await client.quit(); } catch { /* swallow */ } diff --git a/packages/services/service-cluster-redis/src/pubsub.ts b/packages/services/service-cluster-redis/src/pubsub.ts index 9818f2aed7c..26a8dc0cbdf 100644 --- a/packages/services/service-cluster-redis/src/pubsub.ts +++ b/packages/services/service-cluster-redis/src/pubsub.ts @@ -8,7 +8,8 @@ import type { SubscribeOptions, Unsubscribe, } from '@objectstack/spec/contracts'; -import { duplicateForPubSub } from './client.js'; +import { ClusterDriverLiveness } from '@objectstack/service-cluster'; +import { duplicateForPubSub, watchRedisConnection } from './client.js'; /** * Wire-format envelope sent over Redis. Adds `fromNode` and @@ -31,6 +32,13 @@ export interface RedisPubSubOptions { keyPrefix?: string; /** Error sink for subscriber handler exceptions. */ onError?: (err: unknown, channel: string) => void; + /** + * The driver's connection liveness, which the subscriber connection reports + * to (source `'subscriber'`). The driver factory passes its own; a pub/sub + * composed by hand gets one of its own, so its subscriber still has an + * `error` listener and logs an outage once. + */ + liveness?: ClusterDriverLiveness; } /** @@ -56,6 +64,7 @@ export class RedisPubSub implements IPubSub { private readonly keyPrefix: string; private readonly onError: (err: unknown, channel: string) => void; private readonly subs = new Map>>(); + private readonly unwatchSubscriber: () => void; private closed = false; constructor(opts: RedisPubSubOptions) { @@ -72,6 +81,11 @@ export class RedisPubSub implements IPubSub { this.subscriber.on('message', (raw: string, data: string) => { this.dispatch(raw, data); }); + this.unwatchSubscriber = watchRedisConnection( + this.subscriber, + opts.liveness ?? new ClusterDriverLiveness({ driver: 'redis', nodeId: this.nodeId ?? 'node' }), + 'subscriber', + ); } /** @@ -140,6 +154,8 @@ export class RedisPubSub implements IPubSub { if (this.closed) return; this.closed = true; this.subs.clear(); + // Stop reporting first: the close `quit()` causes is not an outage. + this.unwatchSubscriber(); try { await this.subscriber.quit(); } catch { /* swallow */ } // We don't quit `publisher` — caller owns it. } diff --git a/packages/services/service-cluster-redis/src/redis-outage.real-redis.test.ts b/packages/services/service-cluster-redis/src/redis-outage.real-redis.test.ts new file mode 100644 index 00000000000..76ba448439b --- /dev/null +++ b/packages/services/service-cluster-redis/src/redis-outage.real-redis.test.ts @@ -0,0 +1,283 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A Redis outage under two running kernels, against a real `redis-server` + * (skipped, and saying so, where the binary is not on PATH — the in-process + * pins of every piece below run everywhere: `cluster-resync.test.ts` and the + * bridge tests in `@objectstack/service-cluster`, the lock latch in + * `@objectstack/service-job`'s `cron-job-adapter.leader.test.ts`). + * + * Two replicas — two kernels, each a cluster plugin on the redis driver and a + * cron job service whose scheduled fire is leader-elected on the cluster lock — + * share one password-protected Redis. Redis is stopped and started again + * under them. Pinned: + * + * - no unhandled rejection (before the fix: an unhandled lock rejection at + * the next tick, which ends the process), and one outage warning per + * replica, with no credential in it; + * - the next scheduled fire after Redis returns runs; + * - a cache hint published DURING the outage is lost (at-most-once), and the + * peer converges anyway, on the one `cluster.resync` its driver emits; + * - a hint published after Redis returns reaches the peer (resubscribed). + * + * And the scope-note pin: against a black-holed Redis (a socket that accepts + * and never answers) a command on the connection the shared cache derives + * from the driver's (`client.duplicate()`, as `CacheServicePlugin` does) fails + * within the driver's command bound instead of hanging. + */ + +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { connect, createServer, type AddressInfo, type Server, type Socket } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import type { Redis } from 'ioredis'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import type { IClusterService, IJobService } from '@objectstack/spec/contracts'; +import { + ClusterServicePlugin, + defineCluster, + onClusterResync, + readClusterDriverConnection, + readClusterDriverHealth, +} from '@objectstack/service-cluster'; +import { JobServicePlugin } from '@objectstack/service-job'; +// Registers the `redis` cluster driver with `defineCluster()`. +import { REDIS_COMMAND_TIMEOUT_MS } from './index.js'; + +const REDIS_SERVER = spawnSync('redis-server', ['--version'], { stdio: 'ignore' }).status === 0; +const PASSWORD = 'outage-pin-s3cret'; + +/** A TCP port nothing on 127.0.0.1 is listening on right now. */ +function freePort(): Promise { + return new Promise((answer, fail) => { + const probe = createServer(); + probe.once('error', fail); + probe.listen(0, '127.0.0.1', () => { + const { port } = probe.address() as AddressInfo; + probe.close(() => answer(port)); + }); + }); +} + +/** One authenticated PING to 127.0.0.1:`port`; true on `+PONG`. */ +function pongs(port: number): Promise { + return new Promise((answer) => { + const conn = connect(port, '127.0.0.1'); + let reply = ''; + const done = (ok: boolean): void => { conn.destroy(); answer(ok); }; + conn.setTimeout(500, () => done(false)); + conn.once('error', () => done(false)); + conn.once('connect', () => conn.write(`AUTH ${PASSWORD}\r\nPING\r\n`)); + conn.on('data', (chunk: Buffer) => { + reply += chunk.toString(); + if (reply.includes('PONG')) done(true); + else if (reply.includes('-')) done(false); + }); + }); +} + +async function waitFor(what: string, predicate: () => boolean, timeoutMs = 8_000): Promise { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + await new Promise((r) => setTimeout(r, 25)); + } +} + +describe.skipIf(!REDIS_SERVER)( + 'a Redis outage under two running kernels — real redis-server (skipped when redis-server is not on PATH)', + () => { + let dir = ''; + let port = 0; + let server: ChildProcess | undefined; + + async function startRedis(): Promise { + server = spawn( + 'redis-server', + ['--port', String(port), '--bind', '127.0.0.1', '--requirepass', PASSWORD, + '--save', '', '--appendonly', 'no', '--dir', dir], + { stdio: ['ignore', 'ignore', 'ignore'] }, + ); + const deadline = Date.now() + 10_000; + while (!(await pongs(port))) { + if (server.exitCode !== null) throw new Error(`redis-server exited (${server.exitCode})`); + if (Date.now() > deadline) throw new Error('redis-server did not answer PING within 10s'); + await new Promise((r) => setTimeout(r, 25)); + } + } + + async function stopRedis(): Promise { + const proc = server; + server = undefined; + if (!proc || proc.exitCode !== null) return; + const exited = new Promise((r) => proc.once('exit', r)); + proc.kill('SIGKILL'); + await exited; + } + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'os-redis-outage-')); + port = await freePort(); + await startRedis(); + }, 15_000); + + afterAll(async () => { + await stopRedis(); + if (dir) rmSync(dir, { recursive: true, force: true }); + }); + + it('replicas stay up, warn once, resume firing, and converge a hint lost during the outage', async () => { + const url = `redis://:${PASSWORD}@127.0.0.1:${port}`; + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown): void => { unhandled.push(reason); }; + process.on('unhandledRejection', onUnhandled); + + // What the kernels' logger writes (the cron adapter's lines). + const written: string[] = []; + const write = process.stdout.write.bind(process.stdout); + const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, ...rest: unknown[]) => { + written.push(String(chunk)); + return (write as (...a: unknown[]) => boolean)(chunk, ...rest); + }) as typeof process.stdout.write); + + const driverLines: Record = { A: [], B: [] }; + let runs = 0; + const kernels: LiteKernel[] = []; + const boot = async (nodeId: 'A' | 'B') => { + const kernel = new LiteKernel({ logger: { level: 'warn', format: 'text' } }); + kernel.use(new ClusterServicePlugin({ + config: { + driver: 'redis', + url, + nodeId, + driverOptions: { + logger: { + warn: (m: string) => driverLines[nodeId]!.push(m), + info: (m: string) => driverLines[nodeId]!.push(m), + }, + }, + }, + })); + kernel.use(new JobServicePlugin({ adapter: 'cron' })); + await kernel.bootstrap(); + kernels.push(kernel); + const job = kernel.getService('job'); + await job.schedule('probe', { type: 'interval', intervalMs: 100 }, async () => { runs += 1; }); + return kernel.getService('cluster'); + }; + + try { + const a = await boot('A'); + const b = await boot('B'); + + // The peer's cache: it holds what it last read from the shared + // source of truth, re-reads on a hint, and on a resync. + let truth = 'v1'; + let peerView = truth; + const resyncs = { A: 0, B: 0 }; + b.pubsub.subscribe('cache.hint', () => { peerView = truth; }); + onClusterResync(a, () => { resyncs.A += 1; }); + onClusterResync(b, () => { resyncs.B += 1; peerView = truth; }); + + await waitFor('a first scheduled fire', () => runs > 0); + // Both connections of both replicas are up before the outage. + await a.pubsub.publish('cache.hint', {}); + await waitFor('replica health up', () => + readClusterDriverHealth(a)?.state === 'up' && readClusterDriverHealth(b)?.state === 'up'); + + // ── Outage ─────────────────────────────────────────────── + await stopRedis(); + await waitFor('replica A to see the outage', () => readClusterDriverHealth(a)?.state === 'down'); + truth = 'v2'; + await expect(a.pubsub.publish('cache.hint', {})).rejects.toThrow(); + const runsDuringOutage = runs; + // Several ticks of every job against the dead lock. + await new Promise((r) => setTimeout(r, 800)); + expect(runs).toBe(runsDuringOutage); + expect(peerView).toBe('v1'); + + // ── Redis returns ──────────────────────────────────────── + await startRedis(); + await waitFor('both replicas to resync', () => resyncs.A === 1 && resyncs.B === 1); + // The hint published during the outage was lost; the peer converged on the resync. + expect(peerView).toBe('v2'); + expect(readClusterDriverHealth(b)).toMatchObject({ state: 'up', outages: 1 }); + + // The next scheduled fire runs. + const runsAtReturn = runs; + await waitFor('a scheduled fire after Redis returned', () => runs > runsAtReturn); + + // A hint published now reaches the peer (the subscriber resubscribed). + await waitFor('the subscriber to be back', () => readClusterDriverHealth(b)?.state === 'up'); + truth = 'v3'; + await a.pubsub.publish('cache.hint', {}); + await waitFor('the peer to receive the hint', () => peerView === 'v3'); + + // ── What was said ──────────────────────────────────────── + expect(unhandled).toEqual([]); + for (const node of ['A', 'B'] as const) { + const lost = driverLines[node]!.filter((l) => l.includes('lost its connection')); + expect(lost, `replica ${node}'s outage lines`).toHaveLength(1); + expect(lost[0]).toContain(`127.0.0.1:${port}`); + expect(driverLines[node]!.filter((l) => l.includes('reconnected'))).toHaveLength(1); + for (const line of driverLines[node]!) expect(line).not.toContain(PASSWORD); + } + const cronWarnings = written.filter((l) => l.includes('CronJobAdapter: the cluster lock could not')); + // At most one per replica (a replica whose ticks all landed between + // health flips may have none), never one per tick. + expect(cronWarnings.length).toBeLessThanOrEqual(2); + for (const line of written) expect(line).not.toContain(PASSWORD); + expect(resyncs).toEqual({ A: 1, B: 1 }); + } finally { + stdoutSpy.mockRestore(); + process.off('unhandledRejection', onUnhandled); + await Promise.all(kernels.map((k) => k.shutdown())); + } + }, 30_000); + }, +); + +describe('a black-holed Redis fails a cache call within the command bound', () => { + let blackHole: Server | undefined; + const sockets: Socket[] = []; + + afterAll(async () => { + for (const s of sockets) s.destroy(); + await new Promise((r) => (blackHole ? blackHole.close(() => r()) : r())); + }); + + it(`a GET on the cache's derived connection rejects within ${REDIS_COMMAND_TIMEOUT_MS} ms (+ slack), not ~30 s`, async () => { + // Accepts the TCP connection and never answers a byte: the + // network-partition shape, where connection refused never arrives. + blackHole = createServer((socket) => { sockets.push(socket); socket.on('data', () => {}); }); + await new Promise((r) => blackHole!.listen(0, '127.0.0.1', () => r())); + const { port } = blackHole.address() as AddressInfo; + + const cluster = defineCluster({ driver: 'redis', url: `redis://:${PASSWORD}@127.0.0.1:${port}`, nodeId: 'bh' }); + try { + const offered = readClusterDriverConnection(cluster, 'redis'); + expect(offered).toBeDefined(); + // Exactly how `CacheServicePlugin` derives the shared cache's connection. + const derived = offered!.client.duplicate(); + // The handshake times out too, and ioredis reports that as a + // connection `error`; the cache's own derived connection is the + // cache plugin's to listen on. Here only the command's bound is + // under test. + derived.on('error', () => {}); + try { + const started = Date.now(); + await expect(derived.get('os:cache:probe')).rejects.toThrow(/timed out/i); + const elapsed = Date.now() - started; + expect(elapsed).toBeGreaterThanOrEqual(REDIS_COMMAND_TIMEOUT_MS - 100); + expect(elapsed).toBeLessThan(REDIS_COMMAND_TIMEOUT_MS + 1_500); + } finally { + derived.disconnect(); + } + } finally { + await cluster.close(); + } + }, 10_000); +}); diff --git a/packages/services/service-cluster-redis/vitest.config.ts b/packages/services/service-cluster-redis/vitest.config.ts index 092f3349553..e725e8feae0 100644 --- a/packages/services/service-cluster-redis/vitest.config.ts +++ b/packages/services/service-cluster-redis/vitest.config.ts @@ -1,4 +1,32 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// This package needs nothing beyond the shared preset; see its header. -export { default } from '../../../vitest.preset.mts'; +// This config exists for exactly two settings; everything else stays on +// vitest's defaults, deliberately — a key added here re-specifies behaviour +// for every test file in the package (packages/cli/vitest.config.ts's header +// records the incident that taught that). +import { defineConfig } from 'vitest/config'; +import path from 'node:path'; + +export default defineConfig({ + test: { + // A late console.* must not redden a green suite (#10374): vitest's worker + // forwards console output over RPC and discards the promise, and a write + // landing after teardown's rpcDone() snapshot is rejected into an unhandled + // error — a fully green run that exits 1. Disarming removes the mechanism. + // Mechanism + measured costs: examples/app-showcase/vitest.config.ts. + // Enforced repo-wide by scripts/check-console-intercept-disarm.mjs. + disableConsoleIntercept: true, + }, + resolve: { + alias: [ + // `redis-outage.real-redis.test.ts` boots `LiteKernel` and the cron job + // service against a real Redis. Unaliased, the workspace links resolve + // both to `dist/`, and the verdict becomes a function of build state. + // `pnpm check:test-source-alias` is the gate; aliasing is its intended + // repair. ANCHORED regexes, array form: a bare string `find` matches by + // PREFIX and would also swallow a published subpath. + { find: /^@objectstack\/core$/, replacement: path.resolve(__dirname, '../../core/src/index.ts') }, + { find: /^@objectstack\/service-job$/, replacement: path.resolve(__dirname, '../service-job/src/index.ts') }, + ], + }, +}); diff --git a/packages/services/service-cluster/src/authz-cluster-bridge-plugin.test.ts b/packages/services/service-cluster/src/authz-cluster-bridge-plugin.test.ts index 7dc659bd30a..2a6ee93a18a 100644 --- a/packages/services/service-cluster/src/authz-cluster-bridge-plugin.test.ts +++ b/packages/services/service-cluster/src/authz-cluster-bridge-plugin.test.ts @@ -23,6 +23,7 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import type { PluginContext } from '@objectstack/core'; import { AuthzClusterBridgePlugin } from './authz-cluster-bridge-plugin.js'; +import { ClusterDriverLiveness, offerClusterDriverLiveness } from './cluster-resync.js'; const TTL_ENV = 'OS_AUTHZ_GRANTS_CACHE_TTL_MS'; @@ -54,6 +55,9 @@ function makeHarness(opts: HarnessOptions = {}) { const detach = vi.fn(); const pubsub = { publish: vi.fn(), subscribe: vi.fn(), close: vi.fn() }; + // The engine's write epoch — what the bridge advances on `cluster.resync`. + const bump = vi.fn((_reason: string) => 7); + const engineService = { attachAuthzInvalidationPubSub: attach, writeEpoch: { current: 6, bump, subscribe: vi.fn() } }; const cluster = driver === undefined ? undefined @@ -74,7 +78,7 @@ function makeHarness(opts: HarnessOptions = {}) { } if (name === 'objectql') { if (!engine) throw new Error('service not found: objectql'); - return { attachAuthzInvalidationPubSub: attach }; + return engineService; } throw new Error(`service not found: ${name}`); }, @@ -84,7 +88,7 @@ function makeHarness(opts: HarnessOptions = {}) { for (const h of hooks.get(name) ?? []) await h(); }; - return { ctx, logger, attach, detach, fire, pubsub }; + return { ctx, logger, attach, detach, fire, pubsub, bump, cluster }; } afterEach(() => { @@ -215,3 +219,43 @@ describe('[#11968] the bridged arm — enabled cache, remote driver', () => { expect(h.logger.error).not.toHaveBeenCalled(); }); }); + +describe('cluster.resync — cached grants are retired after an outage that may have lost hints', () => { + function withLiveness(h: ReturnType) { + const liveness = new ClusterDriverLiveness({ driver: 'redis', nodeId: 'node-a', logger: { warn: vi.fn() } }); + offerClusterDriverLiveness(h.cluster!, liveness); + return () => { + liveness.reportUp('command'); + liveness.reportDown('command', new Error('ECONNREFUSED')); + liveness.reportUp('command'); + }; + } + + it('while bridged, a recovered outage advances the write epoch once, as a remote hint does', async () => { + vi.stubEnv(TTL_ENV, '5000'); + const h = makeHarness({ driver: 'redis' }); + const outage = withLiveness(h); + await new AuthzClusterBridgePlugin().init(h.ctx); + await h.fire('kernel:ready'); + expect(h.bump).not.toHaveBeenCalled(); + + outage(); + expect(h.bump).toHaveBeenCalledTimes(1); + // `remote`: the bridge must not echo the bump onto the bus. + expect(h.bump).toHaveBeenCalledWith('remote'); + + await h.fire('kernel:shutdown'); + outage(); + expect(h.bump).toHaveBeenCalledTimes(1); + }); + + it('CONTROL — cache off (the shipped default): nothing is bridged, so nothing listens', async () => { + vi.stubEnv(TTL_ENV, '0'); + const h = makeHarness({ driver: 'redis' }); + const outage = withLiveness(h); + await new AuthzClusterBridgePlugin().init(h.ctx); + await h.fire('kernel:ready'); + outage(); + expect(h.bump).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/services/service-cluster/src/authz-cluster-bridge-plugin.ts b/packages/services/service-cluster/src/authz-cluster-bridge-plugin.ts index b19e10341c9..4c46945c640 100644 --- a/packages/services/service-cluster/src/authz-cluster-bridge-plugin.ts +++ b/packages/services/service-cluster/src/authz-cluster-bridge-plugin.ts @@ -9,6 +9,7 @@ import { } from '@objectstack/core'; import type { IClusterService } from '@objectstack/spec/contracts'; import { isInProcessClusterDriver } from './split-brain-guard.js'; +import { onClusterResync } from './cluster-resync.js'; /** * ── `authz.invalidated` bridge + the boot-time posture statement (#11968) ──── @@ -46,6 +47,16 @@ import { isInProcessClusterDriver } from './split-brain-guard.js'; * publishes no message and logs no posture line. That is the substrate's * acceptance criterion: with no cache consumers, runtime behaviour is * unchanged. + * + * ## Resync after an outage + * + * An `authz.invalidated` hint published while the shared store is unreachable + * is lost, and without this the peer kept its grants until the TTL lapsed. So + * while bridged, this plugin also listens for the driver's local + * `cluster.resync` event (`onClusterResync`, emitted once when the connection + * returns after an outage) and answers it the way the bridge answers a peer's + * hint: it advances the engine's write epoch with reason `remote` (so the bump + * is not echoed onto the bus), and every consumer retires what it holds. */ export class AuthzClusterBridgePlugin implements Plugin { name = 'com.objectstack.service.authz-cluster-bridge'; @@ -53,6 +64,7 @@ export class AuthzClusterBridgePlugin implements Plugin { type = 'standard' as const; private detach?: () => void; + private detachResync?: () => void; async init(ctx: PluginContext): Promise { ctx.hook('kernel:ready', async () => { @@ -88,6 +100,13 @@ export class AuthzClusterBridgePlugin implements Plugin { cluster.nodeId, ); bus = 'bridged'; + this.detachResync = onClusterResync(cluster, (event) => { + const epoch = engine.bumpWriteEpoch(); + ctx.logger.info( + `AuthzClusterBridgePlugin: retired cached grants after a ${event.outageMs} ms ` + + `cluster outage (node=${event.nodeId}, epoch=${String(epoch)})`, + ); + }); } catch (err) { ctx.logger.error( 'AuthzClusterBridgePlugin: attach failed', @@ -120,6 +139,8 @@ export class AuthzClusterBridgePlugin implements Plugin { ); } this.detach = undefined; + this.detachResync?.(); + this.detachResync = undefined; }); } @@ -145,6 +166,12 @@ export class AuthzClusterBridgePlugin implements Plugin { pubsub: IClusterService['pubsub'], nodeId: string, ) => () => void; + /** + * Advance the engine's write epoch as a peer's hint does + * (reason `remote`, never echoed); `undefined` when the engine + * carries no epoch seam. + */ + bumpWriteEpoch: () => number | undefined; } | undefined { let svc: unknown; @@ -163,6 +190,13 @@ export class AuthzClusterBridgePlugin implements Plugin { pubsub, nodeId, ), + bumpWriteEpoch: () => { + const epoch = (svc as { writeEpoch?: unknown }).writeEpoch as + | { bump?: unknown } + | undefined; + if (!epoch || typeof epoch.bump !== 'function') return undefined; + return (epoch.bump as (reason: string) => number).call(epoch, 'remote'); + }, }; } } diff --git a/packages/services/service-cluster/src/cluster-resync.test.ts b/packages/services/service-cluster/src/cluster-resync.test.ts new file mode 100644 index 00000000000..888ae360075 --- /dev/null +++ b/packages/services/service-cluster/src/cluster-resync.test.ts @@ -0,0 +1,166 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The driver-agnostic half of the outage story: `ClusterDriverLiveness` logs an + * outage ONCE, reports health, and emits ONE local `cluster.resync` when every + * failed connection is back. The Redis driver feeds it from ioredis events; the + * end-to-end leg against a real `redis-server` lives in + * `@objectstack/service-cluster-redis` (`redis-outage.real-redis.test.ts`). + */ + +import { describe, expect, it, vi } from 'vitest'; +import { + CLUSTER_RESYNC_EVENT, + ClusterDriverLiveness, + describeConnectionError, + offerClusterDriverLiveness, + onClusterResync, + readClusterDriverHealth, + redactCredentials, +} from './cluster-resync.js'; +import { defineCluster } from './cluster.js'; + +function makeLiveness() { + let clock = 1_000; + const logger = { warn: vi.fn(), info: vi.fn() }; + const liveness = new ClusterDriverLiveness({ + driver: 'redis', + nodeId: 'n1', + target: '127.0.0.1:6379', + logger, + now: () => clock, + }); + return { liveness, logger, tick: (ms: number) => { clock += ms; } }; +} + +describe('ClusterDriverLiveness — one warning per outage, one resync per recovery', () => { + it('warns once for a whole outage, however many failures it sees', () => { + const { liveness, logger } = makeLiveness(); + liveness.reportUp('command'); + for (let i = 0; i < 25; i++) liveness.reportDown('command', new Error('connect ECONNREFUSED 127.0.0.1:6379')); + liveness.reportDown('subscriber'); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn.mock.calls[0]![0]).toContain('lost its connection to 127.0.0.1:6379'); + expect(liveness.health()).toMatchObject({ state: 'down', outages: 1, lastError: 'connect ECONNREFUSED 127.0.0.1:6379' }); + }); + + it('emits cluster.resync once, only when EVERY failed connection is back', () => { + const { liveness, logger, tick } = makeLiveness(); + const handler = vi.fn(); + liveness.onResync(handler); + liveness.reportUp('command'); + liveness.reportDown('command', new Error('boom')); + liveness.reportDown('subscriber', new Error('boom')); + tick(16_000); + liveness.reportUp('command'); + expect(handler).not.toHaveBeenCalled(); + expect(liveness.health().state).toBe('down'); + liveness.reportUp('subscriber'); + liveness.reportUp('subscriber'); + liveness.reportUp('command'); + expect(handler).toHaveBeenCalledTimes(1); + expect(handler).toHaveBeenCalledWith({ + event: CLUSTER_RESYNC_EVENT, + driver: 'redis', + nodeId: 'n1', + outageMs: 16_000, + at: 17_000, + }); + expect(logger.info).toHaveBeenCalledTimes(1); + expect(liveness.health()).toEqual({ driver: 'redis', nodeId: 'n1', state: 'up', since: 17_000, outages: 1 }); + }); + + it('does NOT resync on the first connect (nothing was missed) and warns again on the NEXT outage', () => { + const { liveness, logger } = makeLiveness(); + const handler = vi.fn(); + liveness.onResync(handler); + expect(liveness.health().state).toBe('unknown'); + liveness.reportUp('command'); + expect(handler).not.toHaveBeenCalled(); + liveness.reportDown('command', new Error('a')); + liveness.reportUp('command'); + liveness.reportDown('command', new Error('b')); + liveness.reportUp('command'); + expect(logger.warn).toHaveBeenCalledTimes(2); + expect(handler).toHaveBeenCalledTimes(2); + expect(liveness.health().outages).toBe(2); + }); + + it('isolates a throwing or rejecting handler: the others still run, one warning names it', async () => { + const { liveness, logger } = makeLiveness(); + const after = vi.fn(); + liveness.onResync(() => { throw new Error('sync'); }); + liveness.onResync(async () => { throw new Error('async'); }); + liveness.onResync(after); + liveness.reportDown('command', new Error('x')); + liveness.reportUp('command'); + await new Promise((r) => setTimeout(r, 0)); + expect(after).toHaveBeenCalledTimes(1); + // 1 outage line + 2 handler-failure lines. + expect(logger.warn).toHaveBeenCalledTimes(3); + }); + + it('after close() a deliberate disconnect is not an outage and nothing fires', () => { + const { liveness, logger } = makeLiveness(); + const handler = vi.fn(); + liveness.onResync(handler); + liveness.reportUp('command'); + liveness.close(); + liveness.reportDown('command'); + liveness.reportUp('command'); + expect(logger.warn).not.toHaveBeenCalled(); + expect(handler).not.toHaveBeenCalled(); + }); +}); + +describe('the outage line never carries a credential', () => { + it('masks the userinfo of any URL in the error text', () => { + expect(redactCredentials('dial redis://default:s3cr3t@cache.internal:6379 failed')).toBe( + 'dial redis://***@cache.internal:6379 failed', + ); + expect(redactCredentials('rediss://:onlypass@h:1 and redis://u:p@h2')).toBe('rediss://***@h:1 and redis://***@h2'); + expect(describeConnectionError(Object.assign(new Error('getaddrinfo redis://u:pw@x'), { code: 'ENOTFOUND' }))).toBe( + 'ENOTFOUND: getaddrinfo redis://***@x', + ); + }); + + it('the logged line is redacted end to end', () => { + const { liveness, logger } = makeLiveness(); + liveness.reportDown('command', new Error('could not reach redis://admin:hunter2@10.0.0.5:6379')); + const line = String(logger.warn.mock.calls[0]![0]); + expect(line).not.toContain('hunter2'); + expect(line).toContain('redis://***@10.0.0.5:6379'); + }); +}); + +describe('the offer on the cluster instance — onClusterResync / readClusterDriverHealth', () => { + it('a remote driver offers its liveness: subscribers get the event, a probe reads health', () => { + const cluster = {}; + const { liveness } = makeLiveness(); + offerClusterDriverLiveness(cluster, liveness); + const handler = vi.fn(); + const off = onClusterResync(cluster, handler); + liveness.reportDown('command', new Error('x')); + expect(readClusterDriverHealth(cluster)?.state).toBe('down'); + liveness.reportUp('command'); + expect(handler).toHaveBeenCalledTimes(1); + off(); + liveness.reportDown('command', new Error('y')); + liveness.reportUp('command'); + expect(handler).toHaveBeenCalledTimes(1); + expect(() => offerClusterDriverLiveness(cluster, liveness)).toThrow(/already offers/); + // Not enumerable: never leaks into a spread or a JSON dump of the cluster. + expect(Object.getOwnPropertySymbols({ ...cluster })).toHaveLength(0); + }); + + it('CONTROL — the memory driver offers none: no health, and a subscription is an inert no-op', async () => { + const cluster = defineCluster({ driver: 'memory' }); + expect(readClusterDriverHealth(cluster)).toBeUndefined(); + const handler = vi.fn(); + const off = onClusterResync(cluster, handler); + expect(typeof off).toBe('function'); + off(); + expect(handler).not.toHaveBeenCalled(); + await cluster.close(); + }); +}); diff --git a/packages/services/service-cluster/src/cluster-resync.ts b/packages/services/service-cluster/src/cluster-resync.ts new file mode 100644 index 00000000000..bd74e61721a --- /dev/null +++ b/packages/services/service-cluster/src/cluster-resync.ts @@ -0,0 +1,306 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A remote cluster driver's connection health, and the `cluster.resync` event + * it emits when its connection comes back after an outage. + * + * ## Why this exists + * + * Every cross-node cache-invalidation lane in this repository rides `IPubSub`, + * whose delivery is at-most-once (`cluster.mdx` §4.2): a hint published while + * the store is unreachable is simply gone. Before this module a replica that + * missed hints during an outage kept serving what it had cached until its next + * restart — the outage was over, the staleness was not. A remote driver now + * reports its connection's transitions here, and on the transition back to + * healthy this module emits ONE local `cluster.resync` event; every cache that + * holds cross-node state subscribes and flushes or re-reads on it, so a write + * whose hint was lost during the outage converges without a restart. + * + * The same transitions are where the outage is logged — ONE warning when it + * starts, one info line when it ends, never a line per failed command and + * never a credential — and {@link readClusterDriverHealth} reads them back. + * + * ## Passive reading vs. active probe + * + * {@link readClusterDriverHealth} is PASSIVE: it reports what the driver's + * connections last said (`error` / `close` / `ready`), costs nothing, and + * sends nothing to the store. It cannot see a black-holed store whose socket + * never errors. `probeClusterDriverHealth()` (`driver-health.ts`, #31601) is + * the ACTIVE check `/ready` uses: a bounded `PING` against the store, which + * does see that case. Its `ClusterDriverHealth` (`reachable`, `reason`) is a + * different shape from this module's {@link ClusterDriverLivenessHealth}. + * + * ## The single-node path is untouched + * + * Only a remote driver offers a liveness. The in-process `memory` driver never + * loses a connection and offers none, so on it {@link onClusterResync} hands + * back a disposer that does nothing and the handler never runs, and + * {@link readClusterDriverHealth} answers `undefined`. + * + * ## Why a `Symbol.for` key on the cluster instance + * + * The same reason `driver-connection.ts` gives: a process has been measured + * holding two instances of this module (its ESM and CJS builds), so a module + * registry would let the driver offer into one copy while a consumer read the + * other. The offer lives on the cluster instance, under a key from the global + * symbol registry. + */ + +import type { Unsubscribe } from '@objectstack/spec/contracts'; + +/** The event's name: one local event per recovered outage, never published to peers. */ +export const CLUSTER_RESYNC_EVENT = 'cluster.resync' as const; + +/** What a {@link onClusterResync} handler receives. */ +export interface ClusterResyncEvent { + readonly event: typeof CLUSTER_RESYNC_EVENT; + /** The driver whose connection came back (`'redis'`). */ + readonly driver: string; + /** This node's cluster id. */ + readonly nodeId: string; + /** How long the connection was down, in ms. */ + readonly outageMs: number; + /** When the connection came back (epoch ms). */ + readonly at: number; +} + +/** A {@link onClusterResync} handler. A returned promise is awaited for its rejection only. */ +export type ClusterResyncHandler = (event: ClusterResyncEvent) => void | Promise; + +/** + * The driver's connection health, as {@link readClusterDriverHealth} reports it. + * + * `state` is `unknown` until the driver has connected or failed once (the + * driver connects lazily, on first use), `up` while every connection it + * watches is ready, and `down` from the first connection failure until every + * failed connection is ready again. + */ +export interface ClusterDriverLivenessHealth { + readonly driver: string; + readonly nodeId: string; + readonly state: 'unknown' | 'up' | 'down'; + /** When `state` last changed (epoch ms); construction time while `unknown`. */ + readonly since: number; + /** Outages begun since construction, the current one included. */ + readonly outages: number; + /** The current outage's first failure, credential-free; absent while not `down`. */ + readonly lastError?: string; +} + +/** Where the liveness writes its two lines. Defaults to `console`. */ +export interface ClusterDriverLivenessLogger { + warn(message: string): void; + info?(message: string): void; +} + +export interface ClusterDriverLivenessOptions { + driver: string; + nodeId: string; + /** + * What the driver connects to, credential-free (`host:port`) — named in the + * outage line so an operator knows which store is gone. + */ + target?: string; + logger?: ClusterDriverLivenessLogger; + /** Clock, for tests. */ + now?: () => number; +} + +/** + * The connection state machine a remote driver feeds. The driver reports each + * connection it holds by a stable `source` name (`'command'`, `'subscriber'`): + * {@link reportDown} on an error or an unexpected close, {@link reportUp} when + * that connection is ready. The outage begins at the first `reportDown` and + * ends when every source that went down is up again; that end is when the + * resync handlers run, once. + */ +export class ClusterDriverLiveness { + private readonly driver: string; + private readonly nodeId: string; + private readonly target: string | undefined; + private readonly logger: ClusterDriverLivenessLogger; + private readonly now: () => number; + private readonly handlers = new Set(); + /** Sources currently failed. Non-empty ⇔ `down`. */ + private readonly downSources = new Set(); + private state: ClusterDriverLivenessHealth['state'] = 'unknown'; + private since: number; + private outages = 0; + private outageStartedAt = 0; + private lastError: string | undefined; + private closed = false; + + constructor(options: ClusterDriverLivenessOptions) { + this.driver = options.driver; + this.nodeId = options.nodeId; + this.target = options.target; + this.logger = options.logger ?? console; + this.now = options.now ?? Date.now; + this.since = this.now(); + } + + /** A connection failed or closed unexpectedly. The first one in an outage logs; the rest are silent. */ + reportDown(source: string, error?: unknown): void { + if (this.closed) return; + this.downSources.add(source); + if (this.state === 'down') return; + this.state = 'down'; + this.since = this.now(); + this.outageStartedAt = this.since; + this.outages += 1; + this.lastError = describeConnectionError(error); + this.logger.warn( + `[cluster] ${this.driver} driver lost its connection${this.target ? ` to ${this.target}` : ''} ` + + `(node=${this.nodeId}): ${this.lastError}. Cluster locks, counters and cross-node cache hints fail ` + + 'until it returns; scheduled fires are skipped and retried on their next tick, and every cache ' + + `re-reads on the "${CLUSTER_RESYNC_EVENT}" event when it does. Further failures during this outage are not logged.`, + ); + } + + /** A connection is ready. Ends the outage once every failed source is ready, and runs the resync handlers then. */ + reportUp(source: string): void { + if (this.closed) return; + this.downSources.delete(source); + if (this.state === 'up') return; + if (this.state === 'unknown') { + this.state = 'up'; + this.since = this.now(); + return; + } + if (this.downSources.size > 0) return; + const at = this.now(); + const outageMs = Math.max(0, at - this.outageStartedAt); + this.state = 'up'; + this.since = at; + this.lastError = undefined; + this.logger.info?.( + `[cluster] ${this.driver} driver reconnected${this.target ? ` to ${this.target}` : ''} ` + + `(node=${this.nodeId}) after ${outageMs} ms; emitting "${CLUSTER_RESYNC_EVENT}" so caches re-read what they may have missed.`, + ); + this.emitResync({ event: CLUSTER_RESYNC_EVENT, driver: this.driver, nodeId: this.nodeId, outageMs, at }); + } + + /** Stop reporting: a deliberate close is not an outage. Idempotent. */ + close(): void { + this.closed = true; + this.handlers.clear(); + } + + /** The current reading. */ + health(): ClusterDriverLivenessHealth { + return { + driver: this.driver, + nodeId: this.nodeId, + state: this.state, + since: this.since, + outages: this.outages, + ...(this.state === 'down' && this.lastError !== undefined ? { lastError: this.lastError } : {}), + }; + } + + /** Run `handler` on every `cluster.resync`. */ + onResync(handler: ClusterResyncHandler): Unsubscribe { + if (this.closed) return () => {}; + this.handlers.add(handler); + return () => { + this.handlers.delete(handler); + }; + } + + private emitResync(event: ClusterResyncEvent): void { + for (const handler of [...this.handlers]) { + try { + const result = handler(event); + if (result && typeof (result as Promise).then === 'function') { + (result as Promise).catch((err) => this.reportHandlerFailure(err)); + } + } catch (err) { + this.reportHandlerFailure(err); + } + } + } + + private reportHandlerFailure(err: unknown): void { + this.logger.warn( + `[cluster] a "${CLUSTER_RESYNC_EVENT}" handler failed (node=${this.nodeId}): ${describeConnectionError(err)}. ` + + 'That cache keeps what it held until its own TTL or the next resync.', + ); + } +} + +/** + * One line describing a connection failure, with any credential removed. A + * driver's error text can carry the URL it dialled, and a URL can carry a + * password (`redis://user:secret@host`): the userinfo part is masked whatever + * the scheme. + */ +export function describeConnectionError(error: unknown): string { + if (error === undefined) return 'connection closed'; + const raw = + error instanceof Error + ? `${(error as { code?: unknown }).code ? `${String((error as { code?: unknown }).code)}: ` : ''}${error.message}` + : String(error); + return redactCredentials(raw); +} + +/** Mask the userinfo of every `scheme://user:pass@` in `text`. */ +export function redactCredentials(text: string): string { + return text.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]*@/gi, '$1***@'); +} + +// --------------------------------------------------------------------------- +// The offer on the cluster instance +// --------------------------------------------------------------------------- + +/** The global-registry key the liveness is offered under. */ +const DRIVER_LIVENESS_KEY = Symbol.for('@objectstack/service-cluster:driver-liveness'); + +/** + * Offer `liveness` on `cluster`. Called once by a remote driver's factory, on + * the instance it returns. A second offer on the same instance throws — one + * cluster instance has one driver. + */ +export function offerClusterDriverLiveness(cluster: object, liveness: ClusterDriverLiveness): void { + if (Object.prototype.hasOwnProperty.call(cluster, DRIVER_LIVENESS_KEY)) { + throw new Error('offerClusterDriverLiveness: this cluster instance already offers a driver liveness.'); + } + Object.defineProperty(cluster, DRIVER_LIVENESS_KEY, { + value: liveness, + enumerable: false, + writable: false, + configurable: false, + }); +} + +function readLiveness(cluster: unknown): ClusterDriverLiveness | undefined { + if (!cluster || (typeof cluster !== 'object' && typeof cluster !== 'function')) return undefined; + const value = (cluster as Record)[DRIVER_LIVENESS_KEY]; + if (!value || typeof value !== 'object') return undefined; + const candidate = value as Partial; + if (typeof candidate.onResync !== 'function' || typeof candidate.health !== 'function') return undefined; + return value as ClusterDriverLiveness; +} + +/** + * Run `handler` each time `cluster`'s driver reconnects after an outage — the + * `cluster.resync` event. A cache that holds cross-node state flushes or + * re-reads in it. The event is local: it is never published to peers, and + * each replica emits its own when its own connection returns. + * + * On a cluster whose driver offers no liveness (the in-process `memory` + * driver, which cannot lose a connection) this returns a disposer that does + * nothing, and `handler` never runs. + */ +export function onClusterResync(cluster: unknown, handler: ClusterResyncHandler): Unsubscribe { + const liveness = readLiveness(cluster); + if (!liveness) return () => {}; + return liveness.onResync(handler); +} + +/** + * `cluster`'s driver connection health, or `undefined` when its driver offers + * none (the in-process `memory` driver). Read it per probe: it is a snapshot. + */ +export function readClusterDriverHealth(cluster: unknown): ClusterDriverLivenessHealth | undefined { + return readLiveness(cluster)?.health(); +} diff --git a/packages/services/service-cluster/src/index.ts b/packages/services/service-cluster/src/index.ts index 499cb607dfd..e0f855c7dfc 100644 --- a/packages/services/service-cluster/src/index.ts +++ b/packages/services/service-cluster/src/index.ts @@ -63,6 +63,9 @@ export { type ClusterDriverConnection, } from './driver-connection.js'; +// [#31601] An ACTIVE probe of the shared store (a bounded PING), for /ready. +// `readClusterDriverHealth()` below is the PASSIVE reading of the same +// driver's connection state; the two answer different questions. export { probeClusterDriverHealth, DEFAULT_CLUSTER_PROBE_TIMEOUT_MS, @@ -71,6 +74,24 @@ export { type ProbeClusterDriverHealthOptions, } from './driver-health.js'; +// A remote driver's connection health and the local `cluster.resync` event it +// emits when its connection returns after an outage: caches holding +// cross-node state subscribe with `onClusterResync()` and re-read on it. +export { + CLUSTER_RESYNC_EVENT, + ClusterDriverLiveness, + offerClusterDriverLiveness, + onClusterResync, + readClusterDriverHealth, + describeConnectionError, + redactCredentials, + type ClusterResyncEvent, + type ClusterResyncHandler, + type ClusterDriverLivenessHealth, + type ClusterDriverLivenessLogger, + type ClusterDriverLivenessOptions, +} from './cluster-resync.js'; + export { MetadataClusterBridgePlugin } from './metadata-cluster-bridge-plugin.js'; // [#11968] The `authz.invalidated` bridge + the non-optional boot-time posture diff --git a/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts b/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts index a5f872ea2ca..9b8b13f57d4 100644 --- a/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts +++ b/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts @@ -27,6 +27,7 @@ import { 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'; interface HarnessOptions { /** @@ -518,3 +519,76 @@ describe('[#27428] lane 4 — the automation service’s connector-credential.mu expect(h.detachCredential).toHaveBeenCalledTimes(1); }); }); + +describe('cluster.resync — every attached lane re-reads what an outage made it miss', () => { + /** The harness, with lanes 1, 3 and 4 attached and a driver liveness offered on its cluster. */ + function resyncHarness(opts: { driver?: string; laneThrows?: boolean } = {}) { + const h = makeHarness({ + driver: opts.driver ?? 'redis', metadata: 'manager', protocol: 'real', + datasourceAdmin: 'real', automation: 'real', + }); + const svc = (name: string) => h.ctx.getService>(name); + const resyncMetadata = vi.fn(); + const resyncDatasource = vi.fn(async () => { + if (opts.laneThrows) throw new Error('datasource store unreachable'); + }); + const resyncCredential = vi.fn(async () => {}); + Object.assign(svc('metadata'), { resyncClusterPubSub: resyncMetadata }); + Object.assign(svc('datasource-admin'), { resyncDatasourceMutationPubSub: resyncDatasource }); + Object.assign(svc('automation'), { resyncConnectorCredentialPubSub: resyncCredential }); + const liveness = new ClusterDriverLiveness({ driver: 'redis', nodeId: 'node-a', logger: { warn: vi.fn(), info: vi.fn() } }); + offerClusterDriverLiveness(svc('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, resyncMetadata, resyncDatasource, resyncCredential }; + } + + it('calls each attached lane’s resync seam once per recovered outage', async () => { + const h = resyncHarness(); + await new MetadataClusterBridgePlugin().init(h.ctx); + await h.fire('kernel:ready'); + expect(h.resyncMetadata).not.toHaveBeenCalled(); + + await h.outage(); + expect(h.resyncMetadata).toHaveBeenCalledTimes(1); + expect(h.resyncDatasource).toHaveBeenCalledTimes(1); + expect(h.resyncCredential).toHaveBeenCalledTimes(1); + expect(infoLines(h).some((l) => l.includes('resynced metadata.changed, datasource.mutated, connector-credential.mutated'))).toBe(true); + + await h.outage(); + expect(h.resyncMetadata).toHaveBeenCalledTimes(2); + }); + + it('one lane failing is a warning and does not stop the others', async () => { + const h = resyncHarness({ laneThrows: true }); + await new MetadataClusterBridgePlugin().init(h.ctx); + await h.fire('kernel:ready'); + await h.outage(); + expect(h.resyncMetadata).toHaveBeenCalledTimes(1); + expect(h.resyncCredential).toHaveBeenCalledTimes(1); + expect(warnLines(h).filter((l) => l.includes('datasource.mutated resync after'))).toHaveLength(1); + }); + + it('after kernel:shutdown a later reconnect calls nothing', async () => { + const h = resyncHarness(); + await new MetadataClusterBridgePlugin().init(h.ctx); + await h.fire('kernel:ready'); + await h.fire('kernel:shutdown'); + await h.outage(); + expect(h.resyncMetadata).not.toHaveBeenCalled(); + }); + + it('CONTROL — the in-process memory driver attaches no lane, so no resync is wired', async () => { + const h = resyncHarness({ driver: 'memory' }); + await new MetadataClusterBridgePlugin().init(h.ctx); + await h.fire('kernel:ready'); + await h.outage(); + expect(h.resyncMetadata).not.toHaveBeenCalled(); + expect(h.resyncDatasource).not.toHaveBeenCalled(); + expect(h.resyncCredential).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.ts b/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.ts index c82078dd004..54dab578bd1 100644 --- a/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.ts +++ b/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.ts @@ -3,6 +3,25 @@ import type { Plugin, PluginContext } from '@objectstack/core'; import type { IClusterService } from '@objectstack/spec/contracts'; import { isInProcessClusterDriver } from './split-brain-guard.js'; +import { onClusterResync, type ClusterResyncEvent } from './cluster-resync.js'; + +/** + * One attached lane's resync seam: the state owner's own "flush or re-read + * what a lost hint would have told you" entry, called on `cluster.resync`. + */ +interface LaneResync { + readonly lane: string; + readonly run: () => unknown; +} + +/** + * The owner's resync seam named `method`, bound to it, or `undefined` when the + * owner predates the seam (it then converges on its next reload, as before). + */ +function resyncSeamOf(owner: unknown, method: string): (() => unknown) | undefined { + const fn = (owner as Record | undefined)?.[method]; + return typeof fn === 'function' ? () => (fn as () => unknown).call(owner) : undefined; +} /** * Bridges the cluster pub/sub bus to the metadata state owners so that @@ -67,6 +86,24 @@ import { isInProcessClusterDriver } from './split-brain-guard.js'; * `connector-credential.mutated` — payload shape defined by * `ClusterConnectorCredentialMutationPayload` in `@objectstack/service-automation`. * + * ## Resync after an outage + * + * Every lane above is at-most-once: a hint published while the shared store + * is unreachable is lost. So each lane that attached also registers its + * owner's resync seam, and on the driver's local `cluster.resync` event + * (`onClusterResync`, emitted once when the connection returns after an + * outage) this plugin calls each one, so a write whose hint was lost + * converges without a restart: + * + * 1. metadata service — `resyncClusterPubSub()`; + * 3. datasource admin service — `resyncDatasourceMutationPubSub()`; + * 4. automation service — `resyncConnectorCredentialPubSub()`. + * + * Lane 2 has no resync seam yet: its convergence is a per-item registry + * write-through, and a full re-convergence of the registry is its own change. + * The in-process driver never emits the event, so the single-node path is + * unchanged. + * * See `content/docs/kernel/cluster.mdx` §6.2. */ export class MetadataClusterBridgePlugin implements Plugin { @@ -78,6 +115,8 @@ export class MetadataClusterBridgePlugin implements Plugin { private detachMutation?: () => void; private detachDatasource?: () => void; private detachConnectorCredential?: () => void; + private detachResync?: () => void; + private readonly laneResyncs: LaneResync[] = []; async init(ctx: PluginContext): Promise { ctx.hook('kernel:ready', async () => { @@ -94,6 +133,9 @@ export class MetadataClusterBridgePlugin implements Plugin { this.attachProtocolLane(ctx, cluster); this.attachDatasourceLane(ctx, cluster); this.attachConnectorCredentialLane(ctx, cluster); + if (this.laneResyncs.length > 0) { + this.detachResync = onClusterResync(cluster, (event) => this.resyncLanes(ctx, event)); + } }); ctx.hook('kernel:shutdown', async () => { @@ -133,9 +175,44 @@ export class MetadataClusterBridgePlugin implements Plugin { ); } this.detachConnectorCredential = undefined; + this.detachResync?.(); + this.detachResync = undefined; + this.laneResyncs.length = 0; }); } + /** + * `cluster.resync`: call every attached lane's resync seam. Each lane is + * isolated — one owner failing to re-read never stops the others — and a + * failure is a warning, because that owner keeps serving what it held until + * its next reload, exactly as it did before the seam existed. + */ + private async resyncLanes(ctx: PluginContext, event: ClusterResyncEvent): Promise { + await Promise.all( + this.laneResyncs.map(async ({ lane, run }) => { + try { + await run(); + } catch (err) { + ctx.logger.warn( + `MetadataClusterBridgePlugin: ${lane} resync after a ${event.outageMs} ms cluster outage failed; ` + + 'it converges on its next reload or restart', + err as Error, + ); + } + }), + ); + ctx.logger.info( + `MetadataClusterBridgePlugin: resynced ${this.laneResyncs.map((l) => l.lane).join(', ')} after a ` + + `${event.outageMs} ms cluster outage (node=${event.nodeId})`, + ); + } + + /** Register `owner`'s resync seam `method` for `lane`, when the owner has one. */ + private registerLaneResync(lane: string, owner: unknown, method: string): void { + const run = resyncSeamOf(owner, method); + if (run) this.laneResyncs.push({ lane, run }); + } + /** * Lane 1 — the metadata SERVICE's `metadata.changed` bridge. * @@ -199,6 +276,7 @@ export class MetadataClusterBridgePlugin implements Plugin { pubsub: IClusterService['pubsub'], nodeId: string, ) => () => void).call(md, cluster.pubsub, cluster.nodeId); + this.registerLaneResync('metadata.changed', md, 'resyncClusterPubSub'); ctx.logger.info( `MetadataClusterBridgePlugin: bridged metadata.changed → cluster.pubsub (node=${cluster.nodeId})`, ); @@ -310,6 +388,7 @@ export class MetadataClusterBridgePlugin implements Plugin { pubsub: IClusterService['pubsub'], nodeId: string, ) => () => void).call(admin, cluster.pubsub, cluster.nodeId); + this.registerLaneResync('datasource.mutated', admin, 'resyncDatasourceMutationPubSub'); ctx.logger.info( `MetadataClusterBridgePlugin: bridged datasource.mutated → cluster.pubsub (node=${cluster.nodeId})`, ); @@ -367,6 +446,7 @@ export class MetadataClusterBridgePlugin implements Plugin { pubsub: IClusterService['pubsub'], nodeId: string, ) => () => void).call(automation, cluster.pubsub, cluster.nodeId); + this.registerLaneResync('connector-credential.mutated', automation, 'resyncConnectorCredentialPubSub'); ctx.logger.info( `MetadataClusterBridgePlugin: bridged connector-credential.mutated → cluster.pubsub (node=${cluster.nodeId})`, ); diff --git a/packages/services/service-datasource/src/__tests__/datasource-cluster-convergence.test.ts b/packages/services/service-datasource/src/__tests__/datasource-cluster-convergence.test.ts index 5071a00c3ac..819d59fc458 100644 --- a/packages/services/service-datasource/src/__tests__/datasource-cluster-convergence.test.ts +++ b/packages/services/service-datasource/src/__tests__/datasource-cluster-convergence.test.ts @@ -40,6 +40,13 @@ import { assertEngineUpdateDispatch, } from '@objectstack/metadata-core'; import type { IDataDriver, IPubSub } from '@objectstack/spec/contracts'; +// The plugin under test loads the SQL driver lazily, inside a function body; +// pay that first load here, during collection, not inside a clocked case +// (`pnpm check:test-source-alias`, "The source reach"). The memory driver +// it also loads lazily resolves to source through this package's vitest +// alias instead: a module binding of it would be a new arrival in +// `pnpm check:driver-memory-census`. +import '@objectstack/driver-sql'; import { DatasourceAdminServicePlugin } from '../datasource-admin-plugin.js'; import { DatasourceAdminService, @@ -693,3 +700,58 @@ describe('[#13805] the attach seam — loopback, idempotency, the missing conver expect(published).toHaveLength(0); }); }); + +describe('resyncDatasourceMutationPubSub() — signals lost in a cluster outage converge on the resync', () => { + /** Drop every publish while `down`: the at-most-once loss an outage causes. */ + function lossy(c: Awaited>) { + const state = { down: false }; + const publish = c.raw.publish.bind(c.raw); + c.raw.publish = async (channel: string, payload: unknown) => { + if (state.down) return; + await publish(channel, payload); + }; + return state; + } + + it('a DELETE whose signal was lost: the peer keeps the stuck driver, then evicts it on the resync', async () => { + const c = await makeCluster({ seed: [seeded] }); + const outage = lossy(c); + outage.down = true; + await c.writer.service.removeDatasource('analytics'); + outage.down = false; + await settle(); + expect(c.peer.drivers.has('analytics')).toBe(true); + + await c.peer.service.resyncDatasourceMutationPubSub(); + expect(c.peer.drivers.has('analytics')).toBe(false); + expect(c.peer.evicted).toContain('analytics'); + }); + + it('a CREATE whose signal was lost: the peer is pool-less, then builds it from its own read on the resync', async () => { + const c = await makeCluster(); + const outage = lossy(c); + outage.down = true; + await c.writer.service.createDatasource(draft()); + outage.down = false; + await settle(); + expect(c.peer.drivers.has('analytics')).toBe(false); + + await c.peer.service.resyncDatasourceMutationPubSub(); + expect(c.peer.drivers.get('analytics')?.connected).toBe(true); + }); + + it('nothing lost: a resync leaves the pool it already holds — no churn', async () => { + const c = await makeCluster({ seed: [seeded] }); + const before = c.peer.drivers.get('analytics'); + await c.peer.service.resyncDatasourceMutationPubSub(); + expect(c.peer.drivers.get('analytics')).toBe(before); + expect(before!.closed).toBe(false); + }); + + it('CONTROL — no transport attached (single node): the resync converges nothing', async () => { + const c = await makeCluster({ attach: false, seed: [seeded] }); + await c.writer.service.removeDatasource('analytics'); + await c.peer.service.resyncDatasourceMutationPubSub(); + expect(c.peer.drivers.has('analytics')).toBe(true); + }); +}); diff --git a/packages/services/service-datasource/src/datasource-admin-plugin.ts b/packages/services/service-datasource/src/datasource-admin-plugin.ts index bb95d510bd7..9d5577207f3 100644 --- a/packages/services/service-datasource/src/datasource-admin-plugin.ts +++ b/packages/services/service-datasource/src/datasource-admin-plugin.ts @@ -664,6 +664,17 @@ export class DatasourceAdminServicePlugin implements Plugin { // `convergePool` below for the decision table. The engine is resolved // per call for the same reason every other seam here resolves lazily. convergePool: (name) => this.convergePool(ctx, name, engineOf), + // The resync's address list: the SHARED store's rows (the read + // `convergePool` makes), plus the pools this replica built — a pool + // whose row was deleted during an outage has no row left to name it. + listConvergeNames: async () => { + const names = new Set(this.livePoolRecords.keys()); + for (const row of await findEnvironmentRows(engineOf())) { + const name = (row as { name?: unknown }).name; + if (typeof name === 'string' && name.length > 0) names.add(name); + } + return [...names]; + }, // The admin list's `status` reads the connection service's retained // verdicts (framework#3827). Resolved lazily per call: the service exists diff --git a/packages/services/service-datasource/src/datasource-admin-service.ts b/packages/services/service-datasource/src/datasource-admin-service.ts index 5b5707a1c10..30d7c478ba5 100644 --- a/packages/services/service-datasource/src/datasource-admin-service.ts +++ b/packages/services/service-datasource/src/datasource-admin-service.ts @@ -414,6 +414,15 @@ export interface DatasourceAdminServiceConfig { * `debug` when the transport attaches. */ convergePool?: (name: string) => Promise | void; + /** + * The names a `cluster.resync` must converge — see + * {@link DatasourceAdminService.resyncDatasourceMutationPubSub}: every + * datasource the SHARED store holds (the read `convergePool` performs, never + * the per-replica metadata registry) and every pool this replica built. + * Optional: without it a resync converges only the pools the connection + * service reports. + */ + listConvergeNames?: () => Promise; /** * Last connect verdict per datasource, from `DatasourceConnectionService` * (framework#3827). Absent (a host without the connection service) means the @@ -663,6 +672,40 @@ export class DatasourceAdminService implements IDatasourceAdminService { return () => this.detachDatasourceMutationPubSub(); } + /** + * The `cluster.resync` answer for this lane: the cluster driver's connection + * came back after an outage, during which any `datasource.mutated` 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, or when the host wired no `convergePool`. + * + * Converges every name a lost signal could have carried — each record in + * the SHARED store (created or edited during the outage) and each pool this + * replica holds (deleted during it), from the host's `listConvergeNames` — + * through the same per-name convergence a + * received signal runs, so it re-reads the shared record and builds, + * rebuilds or evicts exactly as a delivered hint would have. Resolves once + * every convergence settled; one name failing is logged and does not stop + * the others. + */ + async resyncDatasourceMutationPubSub(): Promise { + const converge = this.config.convergePool; + if (!this.clusterPubSub || !converge) return; + const names = new Set(); + for (const name of (await this.config.listConvergeNames?.()) ?? []) { + if (typeof name === 'string' && name.length > 0) names.add(name); + } + for (const state of this.config.connectionStates?.() ?? []) { + if (typeof state?.name === 'string' && state.name.length > 0) names.add(state.name); + } + for (const name of names) this.enqueueConvergence(name, converge); + await Promise.all([...names].map((name) => this.convergeChains.get(name))); + this.logger?.info?.( + `datasource admin: re-converged ${names.size} datasource(s) after a cluster outage (node=${this.clusterNodeId})`, + ); + } + /** Tear down the cluster wiring. Safe to call multiple times. [#13805] */ detachDatasourceMutationPubSub(): void { if (this.clusterUnsubscribe) { diff --git a/packages/services/service-datasource/vitest.config.ts b/packages/services/service-datasource/vitest.config.ts index dcd3e3d086d..4df4ced9ac3 100644 --- a/packages/services/service-datasource/vitest.config.ts +++ b/packages/services/service-datasource/vitest.config.ts @@ -65,6 +65,11 @@ export default defineConfig({ // which drives the real driver's introspection; aliased so the draft is // judged against the introspection in the driver's source. alias: [ + // The memory driver the default driver factory loads lazily: from source, + // so a test's verdict is about the checkout, and so a test that reaches + // that lazy load needs no module binding of a frozen driver (#6664's + // census) to satisfy `check:test-source-alias`'s source reach. + { find: /^@objectstack\/driver-memory$/, replacement: path.resolve(__dirname, '../../drivers/driver-memory/src/index.ts') }, { find: /^@objectstack\/driver-odata$/, replacement: path.resolve(__dirname, '../../drivers/driver-odata/src/index.ts') }, { find: /^@objectstack\/core$/, replacement: path.resolve(__dirname, '../../core/src/index.ts') }, { find: /^@objectstack\/metadata-core$/, replacement: path.resolve(__dirname, '../../metadata-core/src/index.ts') }, diff --git a/packages/services/service-job/src/cron-job-adapter.leader.test.ts b/packages/services/service-job/src/cron-job-adapter.leader.test.ts index 9a8a2bfd875..11022531250 100644 --- a/packages/services/service-job/src/cron-job-adapter.leader.test.ts +++ b/packages/services/service-job/src/cron-job-adapter.leader.test.ts @@ -49,3 +49,86 @@ describe('CronJobAdapter — scheduler leader-election', () => { await adapter.destroy(); }); }); + +describe('CronJobAdapter — an unreachable cluster lock skips the fire, never crashes the process', () => { + const lostConnection = () => new Error('Reached the max retries per request limit (which is 3).'); + const logger = () => ({ warn: vi.fn(), info: vi.fn() }); + + it('a rejected acquire resolves the fire (no rejection), skips the handler, and warns ONCE per outage', async () => { + const handler = vi.fn(async () => {}); + const log = logger(); + const acquire = vi.fn(async () => { throw lostConnection(); }); + const adapter = new CronJobAdapter({ cluster: { lock: { acquire } }, logger: log }); + await adapter.schedule('a', { type: 'interval', intervalMs: HOUR }, handler); + await adapter.schedule('b', { type: 'interval', intervalMs: HOUR }, handler); + for (let tick = 0; tick < 5; tick++) { + await expect((adapter as any).runScheduled('a')).resolves.toBeUndefined(); + await expect((adapter as any).runScheduled('b')).resolves.toBeUndefined(); + } + expect(acquire).toHaveBeenCalledTimes(10); + expect(handler).not.toHaveBeenCalled(); + expect(log.warn).toHaveBeenCalledTimes(1); + expect(log.warn.mock.calls[0]![0]).toMatch(/could not acquire "job:a".*retries on its next tick/); + await adapter.destroy(); + }); + + it('the next fire after the lock answers again runs, and a later outage warns again', async () => { + const handler = vi.fn(async () => {}); + const log = logger(); + let down = true; + const acquire = vi.fn(async () => { + if (down) throw lostConnection(); + return { release: vi.fn(async () => {}) }; + }); + const adapter = new CronJobAdapter({ cluster: { lock: { acquire } }, logger: log }); + await adapter.schedule('j', { type: 'interval', intervalMs: HOUR }, handler); + await (adapter as any).runScheduled('j'); + await (adapter as any).runScheduled('j'); + expect(handler).not.toHaveBeenCalled(); + + down = false; + await (adapter as any).runScheduled('j'); + expect(handler).toHaveBeenCalledTimes(1); + expect(log.info).toHaveBeenCalledTimes(1); + expect(log.info.mock.calls[0]![0]).toMatch(/answers again/); + + down = true; + await (adapter as any).runScheduled('j'); + expect(log.warn).toHaveBeenCalledTimes(2); + await adapter.destroy(); + }); + + it('a rejected release after the fire ran is absorbed by the same one-warning latch', async () => { + const handler = vi.fn(async () => {}); + const log = logger(); + const acquire = vi.fn(async () => ({ release: vi.fn(async () => { throw lostConnection(); }) })); + const adapter = new CronJobAdapter({ cluster: { lock: { acquire } }, logger: log }); + await adapter.schedule('j', { type: 'interval', intervalMs: HOUR }, handler); + await expect((adapter as any).runScheduled('j')).resolves.toBeUndefined(); + await expect((adapter as any).runScheduled('j')).resolves.toBeUndefined(); + expect(handler).toHaveBeenCalledTimes(2); + // Release #1 fails → one warning; acquire #2 answers → info; release #2 fails → second warning. + expect(log.warn.mock.calls.map((c) => String(c[0])).every((l) => l.includes('could not release'))).toBe(true); + await adapter.destroy(); + }); + + it('a TIMER-driven fire against a dead lock raises no unhandled rejection', async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => { unhandled.push(reason); }; + process.on('unhandledRejection', onUnhandled); + try { + const log = logger(); + const acquire = vi.fn(async () => { throw lostConnection(); }); + const adapter = new CronJobAdapter({ cluster: { lock: { acquire } }, logger: log }); + await adapter.schedule('t', { type: 'interval', intervalMs: 10 }, vi.fn(async () => {})); + await new Promise((r) => setTimeout(r, 120)); + await adapter.destroy(); + await new Promise((r) => setTimeout(r, 20)); + expect(acquire.mock.calls.length).toBeGreaterThan(2); + expect(unhandled).toEqual([]); + expect(log.warn).toHaveBeenCalledTimes(1); + } finally { + process.off('unhandledRejection', onUnhandled); + } + }); +}); diff --git a/packages/services/service-job/src/cron-job-adapter.ts b/packages/services/service-job/src/cron-job-adapter.ts index 49e9070e33a..7d56f674651 100644 --- a/packages/services/service-job/src/cron-job-adapter.ts +++ b/packages/services/service-job/src/cron-job-adapter.ts @@ -54,8 +54,8 @@ export interface CronJobAdapterOptions { * discriminator and NEVER depends on this value being supplied or distinct. */ namespace?: string; - /** Surface for registry-level anomalies (a reclaimed job name). */ - logger?: { warn(msg: string, meta?: unknown): void }; + /** Surface for registry-level anomalies (a reclaimed job name) and cluster-lock outages. */ + logger?: { warn(msg: string, meta?: unknown): void; info?(msg: string, meta?: unknown): void }; } interface CronJobRecord { @@ -80,7 +80,12 @@ export class CronJobAdapter implements IJobService { private readonly jobs = new Map(); private readonly cluster?: SchedulerCluster; private readonly leaseMs: number; - private readonly logger?: { warn(msg: string, meta?: unknown): void }; + private readonly logger?: { warn(msg: string, meta?: unknown): void; info?(msg: string, meta?: unknown): void }; + /** + * True from the first cluster-lock failure until the lock answers again: + * the outage is warned about once, not once per tick of every job. + */ + private lockOutage = false; /** * This instance's prefix in croner's PROCESS-GLOBAL name registry. @@ -233,15 +238,51 @@ export class CronJobAdapter implements IJobService { if (!record) return; const lock = this.cluster?.lock; if (!lock) { await this.execute(record); return; } - const handle = await lock.acquire(`job:${name}`, { ttlMs: this.leaseMs, waitMs: 0 }); + // The timers above fire this as `void this.runScheduled(...)`, so a + // rejection here is an unhandled one, and an unhandled rejection ends the + // process: before this guard, a remote lock store going away crashed every + // replica at its next tick. An unreachable lock is not "another node is the + // leader" either — it is no answer at all — so the fire is skipped (no + // node can prove it alone runs it) and the next tick asks again. + let handle: { release(): Promise } | null; + try { + handle = await lock.acquire(`job:${name}`, { ttlMs: this.leaseMs, waitMs: 0 }); + } catch (err) { + this.reportLockFailure(name, 'acquire', err); + return; + } + this.reportLockAnswered(); if (!handle) return; // another node is the leader for this fire try { await this.execute(record); } finally { - try { await handle.release(); } catch { /* ignore */ } + try { + await handle.release(); + } catch (err) { + // The lease still expires on its TTL; the fire itself ran. + this.reportLockFailure(name, 'release', err); + } } } + /** One warning per outage of the cluster lock, never one per tick. */ + private reportLockFailure(name: string, step: 'acquire' | 'release', err: unknown): void { + if (this.lockOutage) return; + this.lockOutage = true; + this.logger?.warn( + `CronJobAdapter: the cluster lock could not ${step} "job:${name}" (${err instanceof Error ? err.message : String(err)}); ` + + 'scheduled fires are skipped while the lock is unreachable and each job retries on its next tick. ' + + 'Further lock failures are not logged until it answers again.', + ); + } + + /** The lock answered (granted or held elsewhere): an outage, if one was reported, is over. */ + private reportLockAnswered(): void { + if (!this.lockOutage) return; + this.lockOutage = false; + this.logger?.info?.('CronJobAdapter: the cluster lock answers again; scheduled fires resume.'); + } + private async execute(record: CronJobRecord, data?: unknown): Promise { const execution: JobExecution = { jobId: record.name, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b53fbea4c41..1d1c564c7cd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2931,6 +2931,12 @@ importers: specifier: ^6.0.0 version: 6.0.0 devDependencies: + '@objectstack/core': + specifier: workspace:* + version: link:../../core + '@objectstack/service-job': + specifier: workspace:* + version: link:../service-job '@types/node': specifier: ^26.6.5 version: 26.6.5 diff --git a/scripts/check-test-source-alias.mjs b/scripts/check-test-source-alias.mjs index 7b4aff65358..b1fa662c9e9 100644 --- a/scripts/check-test-source-alias.mjs +++ b/scripts/check-test-source-alias.mjs @@ -620,7 +620,7 @@ const KNOWN_UNALIASED_TEST_IMPORTS = { '@objectstack/service-cluster': ['@objectstack/spec'], '@objectstack/service-cluster-redis': ['@objectstack/service-cluster'], '@objectstack/service-datasource': [ - '@objectstack/driver-memory', '@objectstack/driver-sql', '@objectstack/driver-sqlite-wasm', + '@objectstack/driver-sql', '@objectstack/driver-sqlite-wasm', '@objectstack/plugin-hono-server', '@objectstack/spec', '@objectstack/types', ], '@objectstack/service-i18n': ['@objectstack/core', '@objectstack/spec'],