|
| 1 | +import { createAsyncIterableStreamFromAsyncIterable } from "@trigger.dev/core/v3"; |
| 2 | +import { Readable } from "node:stream"; |
| 3 | +import type { ClientConfig } from "pg"; |
| 4 | +import { LogicalReplicationClient, LogicalReplicationClientOptions } from "./client.js"; |
| 5 | +import type { MessageDelete, MessageInsert, MessageUpdate, PgoutputMessage } from "./pgoutput.js"; |
| 6 | + |
| 7 | +export interface LogicalReplicationStreamOptions extends LogicalReplicationClientOptions { |
| 8 | + onError?: (err: Error) => void; |
| 9 | + filterTags?: Array<"insert" | "update" | "delete">; |
| 10 | + abortSignal?: AbortSignal; |
| 11 | + highWaterMark?: number; |
| 12 | +} |
| 13 | + |
| 14 | +export interface TransactionEvent<T = any> { |
| 15 | + tag: "insert" | "update" | "delete"; |
| 16 | + data: T; |
| 17 | + raw: MessageInsert | MessageUpdate | MessageDelete; |
| 18 | +} |
| 19 | + |
| 20 | +export interface Transaction<T = any> { |
| 21 | + commitLsn: string | null; |
| 22 | + commitEndLsn: string | null; |
| 23 | + xid: number; |
| 24 | + events: TransactionEvent<T>[]; |
| 25 | + replicationLagMs: number; |
| 26 | +} |
| 27 | + |
| 28 | +export function createLogicalReplicationStream<T>( |
| 29 | + client: LogicalReplicationClient, |
| 30 | + highWaterMark?: number, |
| 31 | + signal?: AbortSignal |
| 32 | +) { |
| 33 | + let lastLsn: string | null = null; |
| 34 | + let isSubscribed = false; |
| 35 | + |
| 36 | + const source = new ReadableStream<{ lsn: string; message: PgoutputMessage }>( |
| 37 | + { |
| 38 | + async start(controller) { |
| 39 | + console.log("ReadableStream.start"); |
| 40 | + |
| 41 | + if (signal) { |
| 42 | + signal.addEventListener("abort", () => { |
| 43 | + controller.close(); |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + client.events.on("data", async ({ lsn, log }) => { |
| 48 | + console.log("ReadableStream.data"); |
| 49 | + lastLsn = lsn; |
| 50 | + |
| 51 | + if (signal?.aborted) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + if (isRelevantTag(log.tag)) { |
| 56 | + controller.enqueue({ lsn, message: log }); |
| 57 | + } |
| 58 | + |
| 59 | + if (typeof controller.desiredSize === "number" && controller.desiredSize <= 0) { |
| 60 | + await client.stop(); |
| 61 | + } |
| 62 | + }); |
| 63 | + }, |
| 64 | + async cancel() { |
| 65 | + console.log("ReadableStream.cancel"); |
| 66 | + await client.stop(); |
| 67 | + }, |
| 68 | + async pull() { |
| 69 | + if (!isSubscribed) { |
| 70 | + isSubscribed = true; |
| 71 | + console.log("ReadableStream.pull"); |
| 72 | + await client.subscribe(lastLsn ?? undefined); |
| 73 | + } |
| 74 | + }, |
| 75 | + }, |
| 76 | + new CountQueuingStrategy({ highWaterMark: highWaterMark ?? 1 }) |
| 77 | + ); |
| 78 | + |
| 79 | + return createAsyncIterableStreamFromAsyncIterable<Transaction<T>>(groupByTransaction(source)); |
| 80 | +} |
| 81 | + |
| 82 | +export async function* groupByTransaction<T = any>( |
| 83 | + stream: ReadableStream<{ |
| 84 | + lsn: string; |
| 85 | + message: PgoutputMessage; |
| 86 | + }> |
| 87 | +) { |
| 88 | + let currentTransaction: Omit<Transaction<T>, "commitEndLsn" | "replicationLagMs"> & { |
| 89 | + commitEndLsn?: string | null; |
| 90 | + replicationLagMs?: number; |
| 91 | + } = { |
| 92 | + commitLsn: null, |
| 93 | + xid: 0, |
| 94 | + events: [], |
| 95 | + }; |
| 96 | + for await (const { lsn, message } of stream as AsyncIterable<{ |
| 97 | + lsn: string; |
| 98 | + message: PgoutputMessage; |
| 99 | + }>) { |
| 100 | + console.log("groupByTransaction.for await"); |
| 101 | + console.log(message); |
| 102 | + switch (message.tag) { |
| 103 | + case "begin": { |
| 104 | + currentTransaction = { |
| 105 | + commitLsn: message.commitLsn, |
| 106 | + xid: message.xid, |
| 107 | + events: [], |
| 108 | + }; |
| 109 | + break; |
| 110 | + } |
| 111 | + case "insert": { |
| 112 | + currentTransaction.events.push({ |
| 113 | + tag: message.tag, |
| 114 | + data: message.new as T, |
| 115 | + raw: message, |
| 116 | + }); |
| 117 | + break; |
| 118 | + } |
| 119 | + case "update": { |
| 120 | + currentTransaction.events.push({ |
| 121 | + tag: message.tag, |
| 122 | + data: message.new as T, |
| 123 | + raw: message, |
| 124 | + }); |
| 125 | + break; |
| 126 | + } |
| 127 | + case "delete": { |
| 128 | + currentTransaction.events.push({ |
| 129 | + tag: message.tag, |
| 130 | + data: message.old as T, |
| 131 | + raw: message, |
| 132 | + }); |
| 133 | + break; |
| 134 | + } |
| 135 | + case "commit": { |
| 136 | + const replicationLagMs = Date.now() - Number(message.commitTime / 1000n); |
| 137 | + currentTransaction.commitEndLsn = message.commitEndLsn; |
| 138 | + currentTransaction.replicationLagMs = replicationLagMs; |
| 139 | + yield currentTransaction as Transaction<T>; |
| 140 | + break; |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +export function createSubscription<T = any>(opts: LogicalReplicationStreamOptions) { |
| 147 | + const client = new LogicalReplicationClient({ |
| 148 | + name: opts.name, |
| 149 | + publicationName: opts.publicationName, |
| 150 | + slotName: opts.slotName, |
| 151 | + pgConfig: opts.pgConfig, |
| 152 | + table: opts.table, |
| 153 | + redisOptions: opts.redisOptions, |
| 154 | + publicationActions: opts.filterTags, |
| 155 | + }); |
| 156 | + |
| 157 | + client.events.on("error", (err) => { |
| 158 | + if (opts.onError) opts.onError(err); |
| 159 | + }); |
| 160 | + |
| 161 | + client.events.on("heartbeat", async ({ lsn, shouldRespond }) => { |
| 162 | + if (shouldRespond) { |
| 163 | + await client.acknowledge(lsn); |
| 164 | + } |
| 165 | + }); |
| 166 | + |
| 167 | + const stream = createLogicalReplicationStream<T>(client, opts.highWaterMark, opts.abortSignal); |
| 168 | + |
| 169 | + return { |
| 170 | + stream, |
| 171 | + client, |
| 172 | + }; |
| 173 | +} |
| 174 | + |
| 175 | +function isRelevantTag(tag: string): tag is "insert" | "update" | "delete" | "begin" | "commit" { |
| 176 | + return ( |
| 177 | + tag === "insert" || tag === "update" || tag === "delete" || tag === "begin" || tag === "commit" |
| 178 | + ); |
| 179 | +} |
0 commit comments