|
1 | 1 | import { Redis, type RedisOptions } from "@internal/redis"; |
2 | 2 | import { createPostgresContainer, postgresAndRedisTest } from "@internal/testcontainers"; |
| 3 | +import net from "node:net"; |
3 | 4 | import { Client } from "pg"; |
4 | 5 | import { LogicalReplicationClient } from "./client.js"; |
5 | 6 | import type { MessageRelation, PgoutputMessage } from "./pgoutput.js"; |
@@ -1307,4 +1308,193 @@ describe("Replication Client", () => { |
1307 | 1308 | } |
1308 | 1309 | } |
1309 | 1310 | ); |
| 1311 | + |
| 1312 | + postgresAndRedisTest( |
| 1313 | + "streamHeartbeatTimeoutMs reconnects when a replication stream silently stalls", |
| 1314 | + async ({ postgresContainer, prisma, redisOptions }) => { |
| 1315 | + await prisma.$executeRawUnsafe(`ALTER TABLE public."TaskRun" REPLICA IDENTITY FULL;`); |
| 1316 | + |
| 1317 | + const pgHost = postgresContainer.getHost(); |
| 1318 | + const pgPort = postgresContainer.getPort(); |
| 1319 | + const pgUrl = new URL(postgresContainer.getConnectionUri()); |
| 1320 | + |
| 1321 | + let blackholeActive = false; |
| 1322 | + const upstreamSockets = new Set<net.Socket>(); |
| 1323 | + const clientSockets = new Set<net.Socket>(); |
| 1324 | + let connectionCount = 0; |
| 1325 | + |
| 1326 | + const proxy = net.createServer((clientSocket) => { |
| 1327 | + connectionCount++; |
| 1328 | + const connIndex = connectionCount; |
| 1329 | + clientSockets.add(clientSocket); |
| 1330 | + |
| 1331 | + const upstreamSocket = net.createConnection({ host: pgHost, port: pgPort }); |
| 1332 | + upstreamSockets.add(upstreamSocket); |
| 1333 | + |
| 1334 | + clientSocket.on("data", (chunk) => { |
| 1335 | + if (blackholeActive && connIndex === 1) return; |
| 1336 | + if (!upstreamSocket.destroyed) upstreamSocket.write(chunk); |
| 1337 | + }); |
| 1338 | + upstreamSocket.on("data", (chunk) => { |
| 1339 | + if (blackholeActive && connIndex === 1) return; |
| 1340 | + if (!clientSocket.destroyed) clientSocket.write(chunk); |
| 1341 | + }); |
| 1342 | + |
| 1343 | + const cleanup = () => { |
| 1344 | + clientSockets.delete(clientSocket); |
| 1345 | + upstreamSockets.delete(upstreamSocket); |
| 1346 | + if (!clientSocket.destroyed) clientSocket.destroy(); |
| 1347 | + if (!upstreamSocket.destroyed) upstreamSocket.destroy(); |
| 1348 | + }; |
| 1349 | + clientSocket.on("error", cleanup); |
| 1350 | + upstreamSocket.on("error", cleanup); |
| 1351 | + clientSocket.on("close", cleanup); |
| 1352 | + upstreamSocket.on("close", cleanup); |
| 1353 | + }); |
| 1354 | + |
| 1355 | + await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve)); |
| 1356 | + const proxyAddress = proxy.address() as net.AddressInfo; |
| 1357 | + pgUrl.hostname = "127.0.0.1"; |
| 1358 | + pgUrl.port = String(proxyAddress.port); |
| 1359 | + |
| 1360 | + const client = new LogicalReplicationClient({ |
| 1361 | + name: "watchdog-stall-test", |
| 1362 | + slotName: "watchdog_stall_slot", |
| 1363 | + publicationName: "watchdog_stall_pub", |
| 1364 | + redisOptions, |
| 1365 | + table: "TaskRun", |
| 1366 | + pgConfig: { connectionString: pgUrl.toString() }, |
| 1367 | + resubscribeOnFailure: true, |
| 1368 | + resubscribeMinDelayMs: 50, |
| 1369 | + resubscribeMaxDelayMs: 100, |
| 1370 | + streamHeartbeatTimeoutMs: 150, |
| 1371 | + }); |
| 1372 | + |
| 1373 | + const errors: Error[] = []; |
| 1374 | + const starts: number[] = []; |
| 1375 | + const logs: Array<{ lsn: string; log: PgoutputMessage }> = []; |
| 1376 | + |
| 1377 | + client.events.on("error", (err) => errors.push(err)); |
| 1378 | + client.events.on("start", () => starts.push(Date.now())); |
| 1379 | + client.events.on("data", (data) => logs.push(data)); |
| 1380 | + |
| 1381 | + try { |
| 1382 | + await client.subscribe(); |
| 1383 | + for (let i = 0; i < 40 && starts.length < 1; i++) { |
| 1384 | + await setTimeout(50); |
| 1385 | + } |
| 1386 | + expect(starts).toHaveLength(1); |
| 1387 | + |
| 1388 | + // Silently blackhole the first TCP connection: no frames, no socket error/close. |
| 1389 | + blackholeActive = true; |
| 1390 | + |
| 1391 | + // Wait for watchdog to trip, destroy the stalled socket, and resubscribe on a fresh one. |
| 1392 | + for (let i = 0; i < 60 && starts.length < 2; i++) { |
| 1393 | + await setTimeout(50); |
| 1394 | + } |
| 1395 | + |
| 1396 | + expect(errors.some((e) => e.message.includes("Replication stream stalled"))).toBe(true); |
| 1397 | + expect(starts.length).toBeGreaterThanOrEqual(2); |
| 1398 | + |
| 1399 | + // Verify the reconnected stream actually receives new changes. |
| 1400 | + const org = await prisma.organization.create({ data: { title: "t", slug: "t-stall" } }); |
| 1401 | + const proj = await prisma.project.create({ |
| 1402 | + data: { |
| 1403 | + name: "t", |
| 1404 | + slug: "t-stall", |
| 1405 | + organizationId: org.id, |
| 1406 | + externalRef: "t-stall", |
| 1407 | + }, |
| 1408 | + }); |
| 1409 | + const env = await prisma.runtimeEnvironment.create({ |
| 1410 | + data: { |
| 1411 | + slug: "t-stall", |
| 1412 | + type: "DEVELOPMENT", |
| 1413 | + projectId: proj.id, |
| 1414 | + organizationId: org.id, |
| 1415 | + apiKey: "t-stall", |
| 1416 | + pkApiKey: "t-stall", |
| 1417 | + shortcode: "t-stall", |
| 1418 | + }, |
| 1419 | + }); |
| 1420 | + await prisma.taskRun.create({ |
| 1421 | + data: { |
| 1422 | + friendlyId: "run_after_stall", |
| 1423 | + taskIdentifier: "my-task", |
| 1424 | + payload: "{}", |
| 1425 | + traceId: "t1", |
| 1426 | + spanId: "s1", |
| 1427 | + queue: "test", |
| 1428 | + runtimeEnvironmentId: env.id, |
| 1429 | + projectId: proj.id, |
| 1430 | + }, |
| 1431 | + }); |
| 1432 | + |
| 1433 | + const found = await waitForLogs(logs, 0, (f) => f.some((m) => m.tag === "insert")); |
| 1434 | + expect(found.some((m) => m.tag === "insert")).toBe(true); |
| 1435 | + } finally { |
| 1436 | + await client.shutdown(); |
| 1437 | + for (const s of clientSockets) s.destroy(); |
| 1438 | + for (const s of upstreamSockets) s.destroy(); |
| 1439 | + await new Promise<void>((resolve) => proxy.close(() => resolve())); |
| 1440 | + } |
| 1441 | + } |
| 1442 | + ); |
| 1443 | + |
| 1444 | + postgresAndRedisTest( |
| 1445 | + "periodic keepalive (0x6b) frames reset the stream watchdog and prevent disconnects", |
| 1446 | + async ({ postgresContainer, prisma, redisOptions }) => { |
| 1447 | + await prisma.$executeRawUnsafe(`ALTER TABLE public."TaskRun" REPLICA IDENTITY FULL;`); |
| 1448 | + |
| 1449 | + const client = new LogicalReplicationClient({ |
| 1450 | + name: "watchdog-keepalive-test", |
| 1451 | + slotName: "watchdog_keepalive_slot", |
| 1452 | + publicationName: "watchdog_keepalive_pub", |
| 1453 | + redisOptions, |
| 1454 | + table: "TaskRun", |
| 1455 | + pgConfig: { connectionString: postgresContainer.getConnectionUri() }, |
| 1456 | + resubscribeOnFailure: true, |
| 1457 | + resubscribeMinDelayMs: 50, |
| 1458 | + resubscribeMaxDelayMs: 100, |
| 1459 | + streamHeartbeatTimeoutMs: 200, |
| 1460 | + }); |
| 1461 | + |
| 1462 | + const errors: Error[] = []; |
| 1463 | + const starts: number[] = []; |
| 1464 | + const heartbeats: number[] = []; |
| 1465 | + |
| 1466 | + client.events.on("error", (err) => errors.push(err)); |
| 1467 | + client.events.on("start", () => starts.push(Date.now())); |
| 1468 | + client.events.on("heartbeat", () => heartbeats.push(Date.now())); |
| 1469 | + |
| 1470 | + try { |
| 1471 | + await client.subscribe(); |
| 1472 | + for (let i = 0; i < 40 && starts.length < 1; i++) { |
| 1473 | + await setTimeout(50); |
| 1474 | + } |
| 1475 | + expect(starts).toHaveLength(1); |
| 1476 | + |
| 1477 | + // Send valid 0x6b Primary keepalive frames every 75ms for 450ms (> 200ms timeout). |
| 1478 | + const keepalive = Buffer.alloc(18); |
| 1479 | + keepalive[0] = 0x6b; |
| 1480 | + keepalive.writeUInt32BE(1, 5); // LSN 0/1 |
| 1481 | + |
| 1482 | + for (let i = 0; i < 6; i++) { |
| 1483 | + await setTimeout(75); |
| 1484 | + // @ts-expect-error accessing private connection to simulate inbound keepalive frames |
| 1485 | + client.connection?.emit("copyData", { |
| 1486 | + length: keepalive.length, |
| 1487 | + chunk: keepalive, |
| 1488 | + name: "copyData", |
| 1489 | + }); |
| 1490 | + } |
| 1491 | + |
| 1492 | + expect(heartbeats.length).toBeGreaterThanOrEqual(6); |
| 1493 | + expect(errors).toHaveLength(0); |
| 1494 | + expect(starts).toHaveLength(1); |
| 1495 | + } finally { |
| 1496 | + await client.shutdown(); |
| 1497 | + } |
| 1498 | + } |
| 1499 | + ); |
1310 | 1500 | }); |
0 commit comments