import { container, logger, ReplicationAbortedError } from '@powersync/lib-services-framework'; import winston from 'winston'; import { MetricsEngine } from '../metrics/MetricsEngine.js'; import type { CreateJobOptions } from './AbstractReplicator.js'; import { ErrorRateLimiter } from './ErrorRateLimiter.js'; export interface AbstractReplicationJobOptions extends CreateJobOptions { id: string; metrics: MetricsEngine; rateLimiter: ErrorRateLimiter; } export abstract class AbstractReplicationJob { protected logger: winston.Logger; protected abortController = new AbortController(); protected isReplicatingPromise: Promise | null = null; protected constructor(protected options: AbstractReplicationJobOptions) { this.logger = logger.child({ name: `ReplicationJob: ${this.id}` }); } /** * Copy the initial data set from the data source if required and then keep it in sync. */ abstract replicate(): Promise; /** * Ensure the connection to the data source remains active */ abstract keepAlive(): Promise; /** * Start the replication process */ public async start(): Promise { this.isReplicatingPromise = this.replicate() .catch((ex) => { container.reporter.captureException(ex, { metadata: { replicator: this.id } }); this.logger.error(`Replication failed.`, ex); }) .finally(async () => { this.abortController.abort(); await this.options.lock.release(); }); } /** * Safely stop the replication process */ public async stop(): Promise { this.logger.info(`Stopping replication job`); this.abortController.abort(); await this.isReplicatingPromise; } public get id() { return this.options.id; } public get storage() { return this.options.storage; } protected get lock() { return this.options.lock; } protected get rateLimiter() { return this.options.rateLimiter; } /** Log expected restarts without reporting them as replication failures. */ protected shouldReportReplicationError(error: unknown): boolean { if (this.isStopped) { return false; } if (error instanceof ReplicationAbortedError) { if (error.cause != null) { const message = error.cause instanceof Error ? `Replication aborted because ${error.cause.message}` : 'Replication aborted'; this.logger.warn(message, error); } else { this.logger.info('Replication aborted', error); } return false; } return true; } public get isStopped(): boolean { return this.abortController.signal.aborted; } /** * Get replication lag for this job in ms. */ abstract getReplicationLagMillis(): number | undefined; }