import type {LogContext} from '@rocicorp/logger'; import type {ReadonlyJSONObject} from '../../../../shared/src/json.ts'; import type {Source} from '../../types/streams.ts'; import type {ReservationFollowup} from '../change-streamer/change-streamer-http.ts'; import type {ChangeStreamer} from '../change-streamer/change-streamer.ts'; import type {Service} from '../service.ts'; import type {SwitchoverOptions} from './drain-handler.ts'; import {IncrementalSyncer} from './incremental-sync.ts'; import { publishReplicationError, type ReplicationStatusPublisher, } from './replication-status.ts'; import type {ReplicationLagReadinessOptions} from './reporter/recorder.ts'; import type {WriteWorkerClient} from './write-worker-client.ts'; /** See {@link ReplicaStateNotifier.subscribe()}. */ export type ReplicaState = { readonly state: 'version-ready'; /** * The replica watermark that became ready. Omitted for the initial * "current state is ready" notification, which should not count as newly * unserved work for a freshly-started ViewSyncer. */ readonly watermark?: string | undefined; /** * Millisecond epoch when `watermark` became ready to read from the replica. */ readonly replicaReadyTimeMs?: number | undefined; /** * Millisecond epoch at which the transaction behind `watermark` committed * *upstream*, as reported by the ChangeSource. Unlike `replicaReadyTimeMs`, * which is stamped locally when the change lands in the replica, this is the * origin of the whole pipeline, so `now - upstreamCommitTimeMs` at the point * the change is poked to clients is the end-to-end serving lag. * * Note that this crosses a clock domain: it comes from the upstream * database, whereas it is subtracted from the local clock in the ViewSyncer. * The existing `zero.replication.total_lag` metric spans the same boundary. * * Undefined when the ChangeSource does not report a commit time, and for the * initial "current state is ready" notification. */ readonly upstreamCommitTimeMs?: number | undefined; // Used in tests to verify behavior when additional information // is ferried in the future. Not set in production. readonly testSeqNum?: number | undefined; }; export interface ReplicaStateNotifier { /** * Creates a cancelable subscription of changes in the replica state. * * A `version-ready` message indicates that the replica is ready to be * read, and henceforth that a _new_ version is ready, i.e. whenever a * change is committed to the replica. The `version-ready` message itself * otherwise contains no other information; the subscriber queries the * replica for the current data. * * A `maintenance` state indicates that the replica should not be read from. * If a subscriber is holding any transaction locks, it should release them * until the next `version-ready` signal. * * Upon subscription, the current state of the replica is sent immediately * if known. If multiple notifications occur before the subscriber * can consume them, all but the last notification are discarded by the * Subscription object (i.e. not buffered). Thus, a subscriber only * ever consumes the current (i.e. known) state of the replica. This avoids * a buildup of "work" if a subscriber is too busy to consume all * notifications. */ subscribe(): Source; } export interface Replicator extends ReplicaStateNotifier { /** * Returns an opaque message for human-readable consumption. This is * purely for ensuring that the Replicator has started at least once to * bootstrap a new replica. */ status(): Promise; } export type ReplicatorMode = 'backup' | 'serving'; export class ReplicatorService implements Replicator, Service { readonly id: string; readonly #lc: LogContext; readonly #incrementalSyncer: IncrementalSyncer; readonly #shouldPublishErrors: boolean; readonly #worker: WriteWorkerClient; #runPromise: Promise | undefined; constructor( lc: LogContext, taskID: string, id: string, mode: ReplicatorMode, changeStreamer: ChangeStreamer, worker: WriteWorkerClient, statusPublisher: ReplicationStatusPublisher | null, replicationLagReadinessOptions: ReplicationLagReadinessOptions = {}, // The still-open connection from the snapshot reservation that produced // the replica this process just restored (serving mode only). Used for // IncrementalSyncer's first subscribe() so the replication-manager that // reserved the change log is the one that serves the subscription. initialConnection?: ReservationFollowup, switchover?: SwitchoverOptions, ) { this.id = id; this.#lc = lc .withContext('component', 'replicator') .withContext('serviceID', this.id); this.#worker = worker; this.#shouldPublishErrors = statusPublisher !== null; this.#incrementalSyncer = new IncrementalSyncer( this.#lc, taskID, `${taskID}/${id}`, changeStreamer, worker, mode, statusPublisher, replicationLagReadinessOptions, initialConnection, switchover, ); } status() { return Promise.resolve({status: 'ok'}); } ready(): Promise { return this.#incrementalSyncer.ready(); } run() { this.#runPromise = this.#incrementalSyncer.run().catch(async error => { if (this.#shouldPublishErrors) { await publishReplicationError( this.#lc, 'Replicating', 'Replication stopped because the replica writer failed', ); } throw error; }); return this.#runPromise; } subscribe(): Source { return this.#incrementalSyncer.subscribe(); } async stop() { this.#incrementalSyncer.stop(this.#lc); // Wait for the syncer's run loop to finish so that any in-flight // worker.processMessages() call completes and clears #pending // before we send the 'stop' message to the worker. await this.#runPromise; await this.#worker.stop(); } }