Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/webapp/app/services/runsReplicationService.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,7 @@ export class RunsReplicationService {
const client = new LogicalReplicationClient({
pgConfig: {
connectionString: source.pgConnectionUrl,
connectionTimeoutMillis: 10_000,
},
name: `${options.serviceName}:${source.id}`,
slotName: source.slotName,
Expand All @@ -497,6 +498,7 @@ export class RunsReplicationService {
redisOptions: options.redisOptions,
autoAcknowledge: false,
resubscribeOnFailure: true,
streamHeartbeatTimeoutMs: 90_000,
maxResubscribeAttempts: options.maxResubscribeAttempts,
publicationActions: ["insert", "update", "delete"],
logger:
Expand Down
190 changes: 190 additions & 0 deletions internal-packages/replication/src/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Redis, type RedisOptions } from "@internal/redis";
import { createPostgresContainer, postgresAndRedisTest } from "@internal/testcontainers";
import net from "node:net";
import { Client } from "pg";
import { LogicalReplicationClient } from "./client.js";
import type { MessageRelation, PgoutputMessage } from "./pgoutput.js";
Expand Down Expand Up @@ -1307,4 +1308,193 @@ describe("Replication Client", () => {
}
}
);

postgresAndRedisTest(
"streamHeartbeatTimeoutMs reconnects when a replication stream silently stalls",
async ({ postgresContainer, prisma, redisOptions }) => {
await prisma.$executeRawUnsafe(`ALTER TABLE public."TaskRun" REPLICA IDENTITY FULL;`);

const pgHost = postgresContainer.getHost();
const pgPort = postgresContainer.getPort();
const pgUrl = new URL(postgresContainer.getConnectionUri());

let blackholeActive = false;
const upstreamSockets = new Set<net.Socket>();
const clientSockets = new Set<net.Socket>();
let connectionCount = 0;

const proxy = net.createServer((clientSocket) => {
connectionCount++;
const connIndex = connectionCount;
clientSockets.add(clientSocket);

const upstreamSocket = net.createConnection({ host: pgHost, port: pgPort });
upstreamSockets.add(upstreamSocket);

clientSocket.on("data", (chunk) => {
if (blackholeActive && connIndex === 1) return;
if (!upstreamSocket.destroyed) upstreamSocket.write(chunk);
});
upstreamSocket.on("data", (chunk) => {
if (blackholeActive && connIndex === 1) return;
if (!clientSocket.destroyed) clientSocket.write(chunk);
});

const cleanup = () => {
clientSockets.delete(clientSocket);
upstreamSockets.delete(upstreamSocket);
if (!clientSocket.destroyed) clientSocket.destroy();
if (!upstreamSocket.destroyed) upstreamSocket.destroy();
};
clientSocket.on("error", cleanup);
upstreamSocket.on("error", cleanup);
clientSocket.on("close", cleanup);
upstreamSocket.on("close", cleanup);
});

await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve));
const proxyAddress = proxy.address() as net.AddressInfo;
pgUrl.hostname = "127.0.0.1";
pgUrl.port = String(proxyAddress.port);

const client = new LogicalReplicationClient({
name: "watchdog-stall-test",
slotName: "watchdog_stall_slot",
publicationName: "watchdog_stall_pub",
redisOptions,
table: "TaskRun",
pgConfig: { connectionString: pgUrl.toString() },
resubscribeOnFailure: true,
resubscribeMinDelayMs: 50,
resubscribeMaxDelayMs: 100,
streamHeartbeatTimeoutMs: 150,
});

const errors: Error[] = [];
const starts: number[] = [];
const logs: Array<{ lsn: string; log: PgoutputMessage }> = [];

client.events.on("error", (err) => errors.push(err));
client.events.on("start", () => starts.push(Date.now()));
client.events.on("data", (data) => logs.push(data));

try {
await client.subscribe();
for (let i = 0; i < 40 && starts.length < 1; i++) {
await setTimeout(50);
}
expect(starts).toHaveLength(1);

// Silently blackhole the first TCP connection: no frames, no socket error/close.
blackholeActive = true;

// Wait for watchdog to trip, destroy the stalled socket, and resubscribe on a fresh one.
for (let i = 0; i < 60 && starts.length < 2; i++) {
await setTimeout(50);
}

expect(errors.some((e) => e.message.includes("Replication stream stalled"))).toBe(true);
expect(starts.length).toBeGreaterThanOrEqual(2);

// Verify the reconnected stream actually receives new changes.
const org = await prisma.organization.create({ data: { title: "t", slug: "t-stall" } });
const proj = await prisma.project.create({
data: {
name: "t",
slug: "t-stall",
organizationId: org.id,
externalRef: "t-stall",
},
});
const env = await prisma.runtimeEnvironment.create({
data: {
slug: "t-stall",
type: "DEVELOPMENT",
projectId: proj.id,
organizationId: org.id,
apiKey: "t-stall",
pkApiKey: "t-stall",
shortcode: "t-stall",
},
});
await prisma.taskRun.create({
data: {
friendlyId: "run_after_stall",
taskIdentifier: "my-task",
payload: "{}",
traceId: "t1",
spanId: "s1",
queue: "test",
runtimeEnvironmentId: env.id,
projectId: proj.id,
},
});

const found = await waitForLogs(logs, 0, (f) => f.some((m) => m.tag === "insert"));
expect(found.some((m) => m.tag === "insert")).toBe(true);
} finally {
await client.shutdown();
for (const s of clientSockets) s.destroy();
for (const s of upstreamSockets) s.destroy();
await new Promise<void>((resolve) => proxy.close(() => resolve()));
}
}
);

postgresAndRedisTest(
"periodic keepalive (0x6b) frames reset the stream watchdog and prevent disconnects",
async ({ postgresContainer, prisma, redisOptions }) => {
await prisma.$executeRawUnsafe(`ALTER TABLE public."TaskRun" REPLICA IDENTITY FULL;`);

const client = new LogicalReplicationClient({
name: "watchdog-keepalive-test",
slotName: "watchdog_keepalive_slot",
publicationName: "watchdog_keepalive_pub",
redisOptions,
table: "TaskRun",
pgConfig: { connectionString: postgresContainer.getConnectionUri() },
resubscribeOnFailure: true,
resubscribeMinDelayMs: 50,
resubscribeMaxDelayMs: 100,
streamHeartbeatTimeoutMs: 200,
});

const errors: Error[] = [];
const starts: number[] = [];
const heartbeats: number[] = [];

client.events.on("error", (err) => errors.push(err));
client.events.on("start", () => starts.push(Date.now()));
client.events.on("heartbeat", () => heartbeats.push(Date.now()));

try {
await client.subscribe();
for (let i = 0; i < 40 && starts.length < 1; i++) {
await setTimeout(50);
}
expect(starts).toHaveLength(1);

// Send valid 0x6b Primary keepalive frames every 75ms for 450ms (> 200ms timeout).
const keepalive = Buffer.alloc(18);
keepalive[0] = 0x6b;
keepalive.writeUInt32BE(1, 5); // LSN 0/1

for (let i = 0; i < 6; i++) {
await setTimeout(75);
// @ts-expect-error accessing private connection to simulate inbound keepalive frames
client.connection?.emit("copyData", {
length: keepalive.length,
chunk: keepalive,
name: "copyData",
});
}

expect(heartbeats.length).toBeGreaterThanOrEqual(6);
expect(errors).toHaveLength(0);
expect(starts).toHaveLength(1);
} finally {
await client.shutdown();
}
}
);
});
67 changes: 65 additions & 2 deletions internal-packages/replication/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@ export interface LogicalReplicationClientOptions {
*/
ackIntervalSeconds?: number;

/**
* Watchdog timeout in ms for inbound replication stream traffic (`0x77` XLogData or `0x6b`
* Primary keepalive). When exceeded, the stalled socket is destroyed with an error so the
* client reconnects. Off by default when omitted or `<= 0`.
*/
streamHeartbeatTimeoutMs?: number;

/**
* The actions to publish to the publication.
*/
Expand Down Expand Up @@ -166,6 +173,8 @@ export class LogicalReplicationClient {
private ackIntervalSeconds: number;
private lastAckTimestamp: number = 0;
private ackIntervalTimer: NodeJS.Timeout | null = null;
private streamHeartbeatTimeoutMs: number;
private streamWatchdogTimer: NodeJS.Timeout | null = null;
private _isStopped: boolean = false;
private _tracer: Tracer;
private resubscribeOnFailure: boolean;
Expand Down Expand Up @@ -207,6 +216,7 @@ export class LogicalReplicationClient {
this.leaderLockAcquireAdditionalTimeMs = options.leaderLockAcquireAdditionalTimeMs ?? 1000;
this.leaderLockRetryIntervalMs = options.leaderLockRetryIntervalMs ?? 500;
this.ackIntervalSeconds = options.ackIntervalSeconds ?? 10;
this.streamHeartbeatTimeoutMs = options.streamHeartbeatTimeoutMs ?? 0;
this.resubscribeOnFailure = options.resubscribeOnFailure ?? false;
this.resubscribeMinDelayMs = options.resubscribeMinDelayMs ?? 1000;
this.resubscribeMaxDelayMs = options.resubscribeMaxDelayMs ?? 30000;
Expand Down Expand Up @@ -258,6 +268,7 @@ export class LogicalReplicationClient {
clearInterval(this.ackIntervalTimer);
this.ackIntervalTimer = null;
}
this.#clearStreamWatchdog();
// Release leader lock if held
await this.#releaseLeaderLock();

Expand Down Expand Up @@ -292,6 +303,7 @@ export class LogicalReplicationClient {
clearInterval(this.ackIntervalTimer);
this.ackIntervalTimer = null;
}
this.#clearStreamWatchdog();

return this;
});
Expand Down Expand Up @@ -349,6 +361,8 @@ export class LogicalReplicationClient {
this.ackIntervalTimer = null;
}

this.#clearStreamWatchdog();

this.connection?.removeAllListeners();
this.connection = null;

Expand Down Expand Up @@ -602,7 +616,8 @@ export class LogicalReplicationClient {
return this;
}

this.connection.once("replicationStart", () => {
const connection = this.connection;
connection.once("replicationStart", () => {
if (this._intentionalStop) {
// shutdown() raced the stream start — tear this attempt down.
void this.#cleanupAttempt();
Expand All @@ -612,17 +627,19 @@ export class LogicalReplicationClient {
this.resubscribeAttempts = 0;
this.recoveryFailures = 0;
this.resubscribeGaveUp = false;
this.#armStreamWatchdog(attemptEpoch, connection);
this.events.emit("start");
});

this.connection.on(
connection.on(
"copyData",
async ({ chunk: buffer }: { length: number; chunk: Buffer; name: string }) => {
// pgoutput protocol: 0x77 = XLogData, 0x6b = Primary keepalive
if (buffer[0] !== 0x77 && buffer[0] !== 0x6b) {
this.logger.warn("Unknown replication message type", { byte: buffer[0] });
return;
}
this.#armStreamWatchdog(attemptEpoch, connection);
const lsn =
buffer.readUInt32BE(1).toString(16).toUpperCase() +
"/" +
Expand Down Expand Up @@ -1372,4 +1389,50 @@ export class LogicalReplicationClient {
}
}, 1000);
}

#clearStreamWatchdog(): void {
if (this.streamWatchdogTimer) {
clearTimeout(this.streamWatchdogTimer);
this.streamWatchdogTimer = null;
}
}

#armStreamWatchdog(attemptEpoch: number, connection: Connection): void {
this.#clearStreamWatchdog();
if (this.streamHeartbeatTimeoutMs <= 0) return;
if (
this._intentionalStop ||
attemptEpoch !== this.subscribeEpoch ||
this.connection !== connection
) {
return;
}

this.streamWatchdogTimer = setTimeout(() => {
this.streamWatchdogTimer = null;
if (
this._intentionalStop ||
attemptEpoch !== this.subscribeEpoch ||
this.connection !== connection
) {
return;
}

this.logger.error("Replication stream stalled", {
name: this.options.name,
slotName: this.options.slotName,
publicationName: this.options.publicationName,
streamHeartbeatTimeoutMs: this.streamHeartbeatTimeoutMs,
});

// @ts-ignore pg does not type the client's connection stream
const stream: { destroy(error?: Error): void } | undefined = connection.stream;
const stalledError = new Error("Replication stream stalled");
if (stream) {
stream.destroy(stalledError);
} else {
connection.emit("error", stalledError);
}
}, this.streamHeartbeatTimeoutMs);
}
}