From 4e754e3c6e2f61c7fba87e350c08dae318a895cd Mon Sep 17 00:00:00 2001 From: Raheemah2k26 Date: Sat, 21 Nov 2026 16:27:11 +0100 Subject: [PATCH 1/6] fix(worker): wrap fee-collected dedup check and upsert in one transaction FeeCollected was the only handler that read StreamEvent and then wrote it as two top-level prisma calls, so two deliveries of the same txHash could both pass the dedup check and the second insert hit the unique index. The pair now runs inside prisma.$transaction like every sibling handler, and the atomicity suite proves exactly one committed row for two simultaneous same-hash deliveries plus the rollback path. Closes #1239 --- backend/src/workers/soroban-event-worker.ts | 60 ++-- .../tests/fee-collected-tx-atomicity.test.ts | 290 ++++++++++++++++++ backend/tests/soroban-event-worker.test.ts | 29 +- 3 files changed, 340 insertions(+), 39 deletions(-) create mode 100644 backend/tests/fee-collected-tx-atomicity.test.ts diff --git a/backend/src/workers/soroban-event-worker.ts b/backend/src/workers/soroban-event-worker.ts index 3833cb0c..6792d95e 100644 --- a/backend/src/workers/soroban-event-worker.ts +++ b/backend/src/workers/soroban-event-worker.ts @@ -1295,39 +1295,47 @@ export class SorobanEventWorker { const token = decodeAddress(body["token"]); const timestamp = Math.floor(Date.now() / 1000); - const existingEvent = await prisma.streamEvent.findUnique({ - where: { - transactionHash_eventType: { - transactionHash: event.txHash, - eventType: "FEE_COLLECTED", - }, - }, - select: { id: true }, - }); - if (existingEvent) { - logger.warn( - `[SorobanWorker] Duplicate StreamEvent skipped: txHash=${event.txHash} type=FEE_COLLECTED`, - ); - } else { - await prisma.streamEvent.upsert({ + // The dedup check and the write must be atomic: as two separate top-level + // `prisma` calls they interleave when the same txHash is delivered twice + // (RPC retry, replay, concurrent poll cycles), both checks see no row, and + // the unique index on (transactionHash, eventType) rejects the second + // insert — surfacing as a 500 on the fee-event path. Matches the pattern + // every other handler in this file already uses (issue #1239). + await prisma.$transaction(async (tx: Prisma.TransactionClient) => { + const existingEvent = await tx.streamEvent.findUnique({ where: { transactionHash_eventType: { transactionHash: event.txHash, eventType: "FEE_COLLECTED", }, }, - create: { - streamId, - eventType: "FEE_COLLECTED", - amount: feeAmount, - transactionHash: event.txHash, - ledgerSequence: event.ledger, - timestamp, - metadata: JSON.stringify({ treasury, token }), - }, - update: {}, + select: { id: true }, }); - } + if (existingEvent) { + logger.warn( + `[SorobanWorker] Duplicate StreamEvent skipped: txHash=${event.txHash} type=FEE_COLLECTED`, + ); + } else { + await tx.streamEvent.upsert({ + where: { + transactionHash_eventType: { + transactionHash: event.txHash, + eventType: "FEE_COLLECTED", + }, + }, + create: { + streamId, + eventType: "FEE_COLLECTED", + amount: feeAmount, + transactionHash: event.txHash, + ledgerSequence: event.ledger, + timestamp, + metadata: JSON.stringify({ treasury, token }), + }, + update: {}, + }); + } + }); // Broadcast to admin channel for treasury reporting sseService.broadcastToAdmin("stream.fee_collected", { diff --git a/backend/tests/fee-collected-tx-atomicity.test.ts b/backend/tests/fee-collected-tx-atomicity.test.ts new file mode 100644 index 00000000..03bba4ad --- /dev/null +++ b/backend/tests/fee-collected-tx-atomicity.test.ts @@ -0,0 +1,290 @@ +/** + * Issue #1239 — fee-collection events must not race themselves. + * + * `handleFeeCollected` reads the dedup row and then writes it. As two separate + * top-level `prisma` calls those two statements autocommit independently, so two + * deliveries of the same transaction (RPC retry, ledger replay, an + * operator-triggered re-poll) can both see "no fee event yet" and both insert. + * The unique index on `(transactionHash, eventType)` then rejects the second + * insert with P2002, which surfaces as a 500 on the fee path and quarantines an + * event whose row was already correct. + * + * The fix wraps check + write in one `prisma.$transaction` — the shape every + * sibling handler in `soroban-event-worker.ts` already uses. + * + * The fake below models that difference rather than just counting calls: + * - the top-level client commits each statement immediately and takes no lock, + * so a check/write pair issued against it interleaves with another pair; + * - `$transaction` serializes transactions against each other (Postgres + * reaches the same outcome by blocking the second conflicting insert on the + * unique index) and commits its writes only at the end. + * + * Reverting to two top-level calls therefore produces two rows here, not merely + * a different mock call count. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { rpc } from "@stellar/stellar-sdk"; + +// ─── Fake Postgres ─────────────────────────────────────────────────────────── + +interface DedupWhere { + transactionHash_eventType: { transactionHash: string; eventType: string }; +} + +interface UpsertArgs { + where: DedupWhere; + create: Record; + update: Record; +} + +/** + * Read-your-writes lookup over the rows committed so far. `pending` is the + * transaction-local buffer; the top-level client passes no buffer at all, which + * is what makes a non-transactional check/write pair observable. + */ +function findRow(rows: unknown[], where: DedupWhere) { + const key = where.transactionHash_eventType; + return ( + rows.find( + (candidate) => + (candidate as Record).transactionHash === + key.transactionHash && + (candidate as Record).eventType === key.eventType, + ) ?? null + ); +} + +const db = vi.hoisted(() => ({ + committed: [] as unknown[], + createStatements: 0, + transactionCommits: 0, +})); + +const mockPrismaObj = vi.hoisted(() => ({ + streamEvent: { + findUnique: vi.fn(), + upsert: vi.fn(), + }, + $transaction: vi.fn(), +})); + +vi.mock("../src/lib/prisma.js", () => ({ + prisma: mockPrismaObj, + default: mockPrismaObj, +})); + +vi.mock("../src/services/sse.service.js", () => ({ + sseService: { + broadcast: vi.fn(), + broadcastToStream: vi.fn(), + broadcastToAdmin: vi.fn(), + }, +})); + +vi.mock("../src/logger.js", () => ({ + default: { + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + debug: vi.fn(), + }, + requestContext: { + getStore: () => undefined, + run: (_store: unknown, cb: () => unknown) => cb(), + }, +})); + +import { SorobanEventWorker } from "../src/workers/soroban-event-worker.js"; +import { sseService } from "../src/services/sse.service.js"; + +// ─── ScVal mock helpers (same shapes as tests/soroban-event-worker.test.ts) ── + +const mockSym = (name: string) => ({ sym: { toString: () => name } } as any); +const mockU64 = (value: number | bigint | string) => + ({ u64: { toString: () => String(value) } } as any); +const mockI128 = (hi: number | bigint | string, lo: number | bigint | string) => + ({ + i128: { + hi: { toString: () => String(hi) }, + lo: { toString: () => String(lo) }, + }, + } as any); +const mockContractAddr = (fill: number) => + ({ + address: { + type: "scAddressTypeContract", + contractId: { value: Buffer.alloc(32, fill) }, + }, + } as any); +const mockMapEntry = (keyName: string, val: unknown) => + ({ key: mockSym(keyName), val } as any); + +const TX_HASH = "fee-race-tx-hash"; + +function feeCollectedEvent(feeUnits: string): rpc.Api.EventResponse { + return { + id: `fee-event-${feeUnits}`, + type: "contract", + ledger: 4_200_000, + ledgerClosedAt: "2026-11-21T00:00:00Z", + txHash: TX_HASH, + transactionIndex: 3, + operationIndex: 0, + inSuccessfulContractCall: true, + topic: [mockSym("fee_collected"), mockU64(777n)], + value: { + type: "scvMap", + map: [ + mockMapEntry("treasury", mockContractAddr(0xaa)), + mockMapEntry("fee_amount", mockI128(0, feeUnits)), + mockMapEntry("token", mockContractAddr(0xbb)), + ], + }, + } as unknown as rpc.Api.EventResponse; +} + +describe("FeeCollected dedup + write atomicity (#1239)", () => { + let worker: SorobanEventWorker; + + beforeEach(() => { + vi.clearAllMocks(); + db.committed.length = 0; + db.createStatements = 0; + db.transactionCommits = 0; + worker = new SorobanEventWorker(); + + // Top-level statements: autocommit, no serialization between the read and + // the write. Only a handler that ignores $transaction goes through here. + mockPrismaObj.streamEvent.findUnique.mockImplementation(async ({ where }: any) => + findRow(db.committed, where), + ); + mockPrismaObj.streamEvent.upsert.mockImplementation(async (args: UpsertArgs) => { + const existing = findRow(db.committed, args.where); + if (existing) return existing; // `update: {}` — nothing to change + db.createStatements += 1; + db.committed.push({ ...args.create }); + return args.create; + }); + + // Transactions: serialized against each other, writes held until commit. + let tail: Promise = Promise.resolve(); + mockPrismaObj.$transaction.mockImplementation( + async (fn: (tx: unknown) => Promise) => { + const run = async () => { + const pending: unknown[] = []; + const tx = { + streamEvent: { + findUnique: async ({ where }: any) => + findRow(db.committed, where) ?? findRow(pending, where), + upsert: async (args: UpsertArgs) => { + const existing = + findRow(db.committed, args.where) ?? findRow(pending, args.where); + if (existing) return existing; + db.createStatements += 1; + pending.push({ ...args.create }); + return args.create; + }, + }, + }; + const result = await fn(tx); + db.committed.push(...pending); + db.transactionCommits += 1; + return result; + }; + const scheduled = tail.then(run, run); + tail = scheduled.catch(() => undefined); + return scheduled; + }, + ); + }); + + it("creates exactly one StreamEvent row when the same txHash is delivered twice at once", async () => { + const event = feeCollectedEvent("1500"); + + await Promise.all([ + (worker as any).handleFeeCollected(event, event.topic[1]), + (worker as any).handleFeeCollected(event, event.topic[1]), + ]); + + expect(db.committed).toHaveLength(1); + expect(db.createStatements).toBe(1); + expect((db.committed[0] as Record).amount).toBe("1500"); + }); + + it("keeps the dedup read and the write in one transaction, never on the top-level client", async () => { + const event = feeCollectedEvent("1500"); + + await (worker as any).handleFeeCollected(event, event.topic[1]); + + expect(mockPrismaObj.$transaction).toHaveBeenCalledTimes(1); + // The audit's complaint is precisely that these two were top-level calls. + expect(mockPrismaObj.streamEvent.findUnique).not.toHaveBeenCalled(); + expect(mockPrismaObj.streamEvent.upsert).not.toHaveBeenCalled(); + expect(db.transactionCommits).toBe(1); + }); + + it("records one row when the duplicate arrives after the first has committed", async () => { + const event = feeCollectedEvent("1500"); + + await (worker as any).handleFeeCollected(event, event.topic[1]); + await (worker as any).handleFeeCollected(event, event.topic[1]); + + expect(db.committed).toHaveLength(1); + expect(db.createStatements).toBe(1); + }); + + it("broadcasts the fee once per delivery and stores treasury plus token in the metadata", async () => { + const event = feeCollectedEvent("2500"); + + await Promise.all([ + (worker as any).handleFeeCollected(event, event.topic[1]), + (worker as any).handleFeeCollected(event, event.topic[1]), + ]); + + const broadcast = vi.mocked(sseService.broadcastToAdmin); + expect(broadcast).toHaveBeenCalledTimes(2); + expect(broadcast).toHaveBeenCalledWith( + "stream.fee_collected", + expect.objectContaining({ streamId: 777n, feeAmount: "2500" }), + ); + + // Exactly one row, and it carries both addresses the per-token totals group + // by (see tests/fee-event-accounting.test.ts). + expect(db.committed).toHaveLength(1); + const metadata = JSON.parse( + String((db.committed[0] as Record).metadata), + ) as { treasury: string; token: string }; + expect(metadata.treasury).toMatch(/^C/); + expect(metadata.token).toMatch(/^C/); + expect(metadata.treasury).not.toBe(metadata.token); + }); + + it("commits nothing when the transaction body fails partway through", async () => { + const event = feeCollectedEvent("1500"); + + mockPrismaObj.$transaction.mockImplementation( + async (fn: (tx: unknown) => Promise) => { + const tx = { + streamEvent: { + findUnique: async () => null, + upsert: async () => { + throw new Error( + "Unique constraint failed on the fields: (`transactionHash`,`eventType`)", + ); + }, + }, + }; + await fn(tx); + db.committed.push({ leaked: true }); + }, + ); + + await expect( + (worker as any).handleFeeCollected(event, event.topic[1]), + ).rejects.toThrow(/Unique constraint failed/); + + // The failed batch wrote nothing, so an operator replay can still land the + // fee row rather than colliding with a half-written one. + expect(db.committed).toHaveLength(0); + }); +}); diff --git a/backend/tests/soroban-event-worker.test.ts b/backend/tests/soroban-event-worker.test.ts index 869a9a94..ab45ffc9 100644 --- a/backend/tests/soroban-event-worker.test.ts +++ b/backend/tests/soroban-event-worker.test.ts @@ -262,29 +262,32 @@ describe('SorobanEventWorker', () => { }; // First call: event doesn't exist - (prisma.streamEvent.findUnique as ReturnType).mockResolvedValueOnce(null); - (prisma.streamEvent.upsert as ReturnType).mockResolvedValueOnce({ - id: 'fee-event-1', - transactionHash: txHash, - eventType: 'FEE_COLLECTED', - }); + const mockTx = { + streamEvent: { + findUnique: vi.fn().mockResolvedValue(null), + upsert: vi.fn().mockResolvedValue({ + id: 'fee-event-1', + transactionHash: txHash, + eventType: 'FEE_COLLECTED', + }), + }, + }; + (prisma.$transaction as ReturnType).mockImplementation((cb) => cb(mockTx)); await (worker as any).handleFeeCollected(mockEvent, mockEvent.topic![1]); - expect(prisma.streamEvent.findUnique).toHaveBeenCalledTimes(1); - expect(prisma.streamEvent.upsert).toHaveBeenCalledTimes(1); + expect(mockTx.streamEvent.findUnique).toHaveBeenCalledTimes(1); + expect(mockTx.streamEvent.upsert).toHaveBeenCalledTimes(1); expect(logger.warn).not.toHaveBeenCalled(); // Reset mocks vi.clearAllMocks(); // Second call: event exists (duplicate) - (prisma.streamEvent.findUnique as ReturnType).mockResolvedValueOnce({ - id: 'fee-event-1', - }); + mockTx.streamEvent.findUnique.mockResolvedValue({ id: 'fee-event-1' }); await (worker as any).handleFeeCollected(mockEvent, mockEvent.topic![1]); - expect(prisma.streamEvent.findUnique).toHaveBeenCalledTimes(1); - expect(prisma.streamEvent.upsert).not.toHaveBeenCalled(); + expect(mockTx.streamEvent.findUnique).toHaveBeenCalledTimes(1); + expect(mockTx.streamEvent.upsert).not.toHaveBeenCalled(); expect(logger.warn).toHaveBeenCalledWith( expect.stringContaining('Duplicate StreamEvent skipped') ); From 9be1935fd433a7d714b68b907237280d405fb897 Mon Sep 17 00:00:00 2001 From: Raheemah2k26 Date: Sat, 21 Nov 2026 16:27:23 +0100 Subject: [PATCH 2/6] fix(backend): propagate X-Request-ID through the error envelope Two gaps, both covered by tests against the real app composition: - sendApiError put an error on the wire with no correlation id, so a caller quoting the body had nothing matching the header. It now mirrors the X-Request-ID the response already carries, read back from the header so a route that overrode it cannot report a different id, and guarded because the stand-in responses in the unit suites have no getHeader. - requestIdMiddleware ran after the global rate limiter, so a throttled 429 and an oversized body from the parser were answered before any id existed. The middleware now sits first, which is what makes the header claim "every response" true rather than "every response the routers saw". Closes #1494 --- backend/src/app.ts | 10 +- backend/src/types/api-error.ts | 14 +- backend/tests/request-id-logging.test.ts | 100 ++++++ backend/tests/request-id-propagation.test.ts | 333 +++++++++++++++++++ 4 files changed, 452 insertions(+), 5 deletions(-) create mode 100644 backend/tests/request-id-logging.test.ts create mode 100644 backend/tests/request-id-propagation.test.ts diff --git a/backend/src/app.ts b/backend/src/app.ts index 24fc8261..210edf63 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -30,12 +30,14 @@ const app = express(); // or invalid, so the server never runs with an open CORS policy. const corsOptions = buildCorsOptions(); -// Apply global rate limiter first -app.use(globalRateLimiter); - -// Request ID tracing +// Request ID tracing runs first, before the rate limiter: a throttled 429 is +// still a response the caller has to correlate, and the id has to exist before +// anything downstream can echo it in a header or an error body. app.use(requestIdMiddleware); +// Apply global rate limiter +app.use(globalRateLimiter); + // Request counting/latency for the Prometheus registry app.use(metricsMiddleware); diff --git a/backend/src/types/api-error.ts b/backend/src/types/api-error.ts index d7cf3334..39f30d71 100644 --- a/backend/src/types/api-error.ts +++ b/backend/src/types/api-error.ts @@ -4,6 +4,7 @@ export interface ApiErrorBody { code: string; message: string; details?: unknown; + requestId?: string; } export class ApiError extends Error { @@ -28,6 +29,17 @@ export function sendApiError( details?: unknown, ) { const error: ApiErrorBody = { code, message }; + // Echo the correlation id the request middleware already put on the response + // so a client can quote one value for both the header and the body. Read it + // back from the header rather than a second source, otherwise a route that + // overrode X-Request-ID would report an id that does not match its own header. + // Guarded: `res.getHeader` is absent on the stand-in responses the unit tests + // pass in, and an error handler must never be the thing that throws. + const headerRequestId = + typeof res.getHeader === "function" ? res.getHeader("X-Request-ID") : undefined; + if (typeof headerRequestId === "string" && headerRequestId.length > 0) { + error.requestId = headerRequestId; + } if (details !== undefined) error.details = details; return res.status(statusCode).json({ error }); -} \ No newline at end of file +} diff --git a/backend/tests/request-id-logging.test.ts b/backend/tests/request-id-logging.test.ts new file mode 100644 index 00000000..d97adfc9 --- /dev/null +++ b/backend/tests/request-id-logging.test.ts @@ -0,0 +1,100 @@ +/** + * Issue #1494, acceptance criterion 3 — Winston appends the request id to log + * lines on its own, so no handler has to pass it. + * + * The logger is used here unmocked, with a capture transport added to it, so + * what is asserted is the real format pipeline in `src/logger.ts` reading the + * real `requestContext` store that `requestIdMiddleware` populates. + */ +import { describe, it, expect, afterEach } from "vitest"; +import Transport from "winston-transport"; +import logger, { requestContext } from "../src/logger.js"; + +class CaptureTransport extends Transport { + lines: Record[] = []; + + log(info: Record, next: () => void): void { + this.lines.push(info); + next(); + } +} + +describe("request id logging (#1494 AC3)", () => { + let capture: CaptureTransport; + + afterEach(() => { + if (capture) logger.remove(capture); + }); + + function attach(): CaptureTransport { + capture = new CaptureTransport({ level: "debug" }); + logger.add(capture); + return capture; + } + + it("appends requestId to a line logged inside the request context", () => { + const transport = attach(); + + requestContext.run({ requestId: "auto-append" }, () => { + logger.info("handler wrote this without mentioning the id"); + }); + + expect(transport.lines).toHaveLength(1); + expect(transport.lines[0]?.requestId).toBe("auto-append"); + expect(transport.lines[0]?.level).toBe("info"); + }); + + it("appends the id to every level the logger exposes", () => { + const transport = attach(); + + requestContext.run({ requestId: "all-levels" }, () => { + logger.debug("d"); + logger.info("i"); + logger.warn("w"); + logger.error("e"); + }); + + expect(transport.lines).toHaveLength(4); + expect(transport.lines.map((line) => line.requestId)).toEqual([ + "all-levels", + "all-levels", + "all-levels", + "all-levels", + ]); + }); + + it("leaves the field off outside a request, rather than inventing one", () => { + const transport = attach(); + + logger.info("logged between requests"); + + expect(transport.lines).toHaveLength(1); + expect(transport.lines[0]?.requestId).toBeUndefined(); + }); + + it("gives concurrent requests their own id in the log", () => { + const transport = attach(); + + // Two overlapping async scopes: each line must report the id of the request + // that was in flight when it was written, not the last one to start. + const first = new Promise((resolve) => { + requestContext.run({ requestId: "concurrent-first" }, async () => { + await Promise.resolve(); + logger.info("first"); + resolve(); + }); + }); + const second = new Promise((resolve) => { + requestContext.run({ requestId: "concurrent-second" }, async () => { + await Promise.resolve(); + logger.info("second"); + resolve(); + }); + }); + + return Promise.all([first, second]).then(() => { + const ids = transport.lines.map((line) => line.requestId).sort(); + expect(ids).toEqual(["concurrent-first", "concurrent-second"]); + }); + }); +}); diff --git a/backend/tests/request-id-propagation.test.ts b/backend/tests/request-id-propagation.test.ts new file mode 100644 index 00000000..cd83db0d --- /dev/null +++ b/backend/tests/request-id-propagation.test.ts @@ -0,0 +1,333 @@ +/** + * Issue #1494 — X-Request-ID must reach every response and every error body. + * + * Three acceptance criteria, each exercised through the real chain rather than a + * reimplementation of it: + * 1. every response carries the `X-Request-ID` header — including the ones + * answered before any route runs (a throttled 429, an unrouted 404); + * 2. an error produced by the shared funnel in `types/api-error.ts` carries + * `requestId`, with the same value the header carries, for every input the + * error handler accepts (`ApiError`, `ZodError`, an unknown `Error`); + * 3. the id is handed to the logger without any handler passing it. + * + * A caller-supplied id is preserved verbatim when it is well formed and replaced + * by a generated one when it is not, which is why the generated-id tests assert + * shape rather than a fixed value. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import request from "supertest"; +import express, { type Request, type Response } from "express"; +import { AsyncLocalStorage } from "async_hooks"; +import { z } from "zod"; +import rateLimit from "express-rate-limit"; + +const mocks = vi.hoisted(() => ({ + prisma: { + $queryRaw: vi.fn(), + $transaction: vi.fn(), + stream: { count: vi.fn(), findMany: vi.fn() }, + streamEvent: { count: vi.fn(), findUnique: vi.fn(), upsert: vi.fn(), findMany: vi.fn() }, + indexerState: { findUnique: vi.fn() }, + }, + logLines: [] as Record[], +})); + +vi.mock("../src/lib/prisma.js", () => ({ + prisma: mocks.prisma, + default: mocks.prisma, +})); + +vi.mock("../src/workers/soroban-event-worker.js", () => ({ + sorobanEventWorker: { + getEventCounters: vi.fn().mockReturnValue({ + eventsProcessed: 0, + eventsFailed: 0, + lastErrorAt: null, + degraded: false, + }), + }, + SorobanEventWorker: vi.fn(), +})); + +vi.mock("../src/lib/redis.js", () => ({ + cache: { + get: vi.fn().mockReturnValue(null), + set: vi.fn(), + del: vi.fn(), + getMetadata: vi.fn().mockReturnValue(null), + getStats: vi.fn().mockReturnValue({ hits: 0, misses: 0, hitRate: 0, itemCount: 0 }), + cleanup: vi.fn(), + }, + isRedisAvailable: vi.fn().mockReturnValue(false), + getPublisher: vi.fn().mockReturnValue(null), + getSubscriber: vi.fn().mockReturnValue(null), + connectRedis: vi.fn().mockResolvedValue(undefined), + disconnectRedis: vi.fn().mockResolvedValue(undefined), +})); + +vi.mock("../src/services/sse.service.js", () => ({ + sseService: { + broadcast: vi.fn(), + broadcastToStream: vi.fn(), + broadcastToAdmin: vi.fn(), + getClientCount: vi.fn().mockReturnValue(0), + }, + SSEService: vi.fn(() => ({})), +})); + +// A Winston-shaped logger whose records carry whatever the request context +// exposed, so criterion 3 is observable without a transport. `requestContext` +// is the same object `requestIdMiddleware` imports, so the id the middleware +// stored is the id these lines report. +vi.mock("../src/logger.js", () => { + const requestContext = new AsyncLocalStorage<{ requestId: string }>(); + const record = (level: string, message: unknown, meta?: Record) => { + mocks.logLines.push({ + level, + message: typeof message === "string" ? message : String(message), + requestId: requestContext.getStore()?.requestId, + ...meta, + }); + }; + return { + requestContext, + default: { + info: (message: unknown, meta?: Record) => record("info", message, meta), + warn: (message: unknown, meta?: Record) => record("warn", message, meta), + error: (message: unknown, meta?: Record) => record("error", message, meta), + debug: (message: unknown, meta?: Record) => record("debug", message, meta), + }, + }; +}); + +import app from "../src/app.js"; +import { requestIdMiddleware } from "../src/middleware/requestId.js"; +import { errorHandler } from "../src/middleware/error.middleware.js"; +import { requestContext } from "../src/logger.js"; +import { ApiError } from "../src/types/api-error.js"; + +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +function headerId(res: request.Response): string { + return String(res.headers["x-request-id"]); +} + +function errorOf(res: request.Response): Record { + return res.body.error as Record; +} + +/** + * `requestIdMiddleware` in front of the app's own error handler, with one route + * per branch of the error funnel. This is the composition `src/app.ts` uses, so + * an id missing from a body fails here for the same reason it would in + * production — and none of these routes needs the database, so they are + * deterministic in CI. + */ +function buildFunnelApp() { + const funnel = express(); + // Same order as src/app.ts: the id exists before anything that can answer, + // including the body parser that raises the 413 below. + funnel.use(requestIdMiddleware); + funnel.use(express.json({ limit: "1kb" })); + + // Mounted after requestId on purpose: a throttled response is still a response + // the caller has to correlate, which only holds if the id exists first. + funnel.post( + "/throttled", + rateLimit({ windowMs: 60_000, limit: 1, standardHeaders: false, legacyHeaders: false }), + (_req: Request, res: Response) => { + res.json({ ok: true }); + }, + ); + + funnel.get("/ok", (_req: Request, res: Response) => { + res.json({ ok: true }); + }); + + funnel.get("/id", (_req: Request, res: Response) => { + res.json({ stored: requestContext.getStore()?.requestId }); + }); + + funnel.get("/api-error", () => { + throw new ApiError(400, "VALIDATION_ERROR", "body.token is required", { field: "token" }); + }); + + funnel.get("/zod", () => { + // A real parser failure, so the issue shape is zod's own and not a guess. + z.object({ token: z.string() }).parse({}); + }); + + funnel.get("/boom", () => { + throw new Error("something unexpected happened"); + }); + + funnel.use(errorHandler); + return funnel; +} + +describe("AC 1 — every response carries the X-Request-ID header", () => { + beforeEach(() => { + mocks.logLines.length = 0; + }); + + it("adds the header to a normal 200 response on the real app", async () => { + const res = await request(app).get("/"); + + expect(res.status).toBe(200); + expect(headerId(res)).toMatch(UUID_PATTERN); + }); + + it("echoes a caller-supplied id instead of inventing one", async () => { + const res = await request(app).get("/").set("X-Request-ID", "upstream-id-42"); + + expect(headerId(res)).toBe("upstream-id-42"); + }); + + it("replaces an oversized id rather than echoing it", async () => { + const oversized = "a".repeat(200); + const res = await request(app).get("/").set("X-Request-ID", oversized); + + expect(headerId(res)).not.toBe(oversized); + expect(headerId(res)).toMatch(UUID_PATTERN); + }); + + it("adds the header to a 404 produced before any route runs", async () => { + const res = await request(app).get("/v1/does-not-exist"); + + expect(res.status).toBe(404); + expect(headerId(res)).toMatch(UUID_PATTERN); + }); + + it("adds the header to a throttled 429, which the limiter answers first", async () => { + const funnel = buildFunnelApp(); + + const first = await request(funnel).post("/throttled").set("X-Request-ID", "burst-case"); + const second = await request(funnel).post("/throttled").set("X-Request-ID", "burst-case"); + + expect(first.status).toBe(200); + expect(second.status).toBe(429); + expect(headerId(second)).toBe("burst-case"); + }); + + it("gives two consecutive requests two distinct ids", async () => { + const first = await request(buildFunnelApp()).get("/ok"); + const second = await request(buildFunnelApp()).get("/ok"); + + expect(headerId(first)).not.toBe(headerId(second)); + }); +}); + +describe("AC 2 — error responses carry requestId in the JSON body", () => { + beforeEach(() => { + mocks.logLines.length = 0; + }); + + it("includes requestId for an ApiError thrown from a handler", async () => { + const res = await request(buildFunnelApp()) + .get("/api-error") + .set("X-Request-ID", "api-error-case"); + + expect(res.status).toBe(400); + expect(errorOf(res)).toMatchObject({ + code: "VALIDATION_ERROR", + message: "body.token is required", + requestId: "api-error-case", + details: { field: "token" }, + }); + expect(errorOf(res).requestId).toBe(headerId(res)); + }); + + it("includes requestId for a Zod validation error", async () => { + const res = await request(buildFunnelApp()) + .get("/zod") + .set("X-Request-ID", "zod-case"); + + expect(res.status).toBe(400); + expect(errorOf(res).code).toBe("VALIDATION_ERROR"); + expect(typeof errorOf(res).message).toBe("string"); + expect(errorOf(res).requestId).toBe("zod-case"); + }); + + it("includes requestId for an unknown error and keeps code and message", async () => { + const res = await request(buildFunnelApp()) + .get("/boom") + .set("X-Request-ID", "unknown-case"); + + expect(res.status).toBe(500); + expect(errorOf(res).code).toBe("INTERNAL_SERVER_ERROR"); + expect(typeof errorOf(res).message).toBe("string"); + expect(errorOf(res).requestId).toBe("unknown-case"); + }); + + it("stamps a generated id into the body when the caller supplied none", async () => { + const res = await request(buildFunnelApp()).get("/api-error"); + + expect(String(errorOf(res).requestId)).toMatch(UUID_PATTERN); + expect(errorOf(res).requestId).toBe(headerId(res)); + }); + + it("carries requestId on the 413 the body parser raises before routing", async () => { + const res = await request(buildFunnelApp()) + .post("/ok") + .set("X-Request-ID", "too-large-case") + .send({ blob: "x".repeat(4096) }); + + expect(res.status).toBe(413); + expect(errorOf(res).code).toBe("PAYLOAD_TOO_LARGE"); + expect(errorOf(res).requestId).toBe("too-large-case"); + }); + + it("does not add requestId to a successful body — it is an error-envelope field", async () => { + const res = await request(buildFunnelApp()).get("/ok").set("X-Request-ID", "success-case"); + + expect(res.status).toBe(200); + expect(res.body?.requestId).toBeUndefined(); + }); +}); + +describe("AC 3 — the id is available to logging without being passed", () => { + beforeEach(() => { + mocks.logLines.length = 0; + }); + + it("publishes the id into the request context for the handler", async () => { + const res = await request(buildFunnelApp()).get("/id").set("X-Request-ID", "context-case"); + + expect(res.status).toBe(200); + expect(res.body.stored).toBe("context-case"); + expect(headerId(res)).toBe("context-case"); + }); + + it("generates a context id when the caller supplied none", async () => { + const res = await request(buildFunnelApp()).get("/id"); + + expect(String(res.body.stored)).toMatch(UUID_PATTERN); + expect(headerId(res)).toBe(res.body.stored); + }); + + it("stamps requestId on log lines emitted while handling a request", async () => { + await request(buildFunnelApp()).get("/boom").set("X-Request-ID", "logged-case"); + + expect(mocks.logLines.length).toBeGreaterThan(0); + // Every line written while the request was in flight is correlated — not just + // the ones the error handler was told about. + expect(mocks.logLines.every((line) => line.requestId === "logged-case")).toBe(true); + }); +}); + +describe("middleware order in the real app", () => { + it("answers a body-parser error from the real app with a correlated id", async () => { + // A 1MB body against the app's 100kb global JSON limit: the id is already on + // the response before the limiter or any router runs, which is what the + // reordering in src/app.ts buys, and this is the app's own chain — not a + // test composition. + const res = await request(app) + .post("/v1/definitely-not-a-route") + .set("X-Request-ID", "real-app-order") + .send({ blob: "x".repeat(150_000) }); + + expect(res.status).toBe(413); + expect(errorOf(res).requestId).toBe("real-app-order"); + expect(headerId(res)).toBe("real-app-order"); + }); +}); From ef9f4e343ecc3b8174458b9ed4ef6b7dbe038fd3 Mon Sep 17 00:00:00 2001 From: Raheemah2k26 Date: Sat, 21 Nov 2026 16:27:35 +0100 Subject: [PATCH 3/6] test(backend): cover FeeCollected decoding and fee accounting paths The worker suite drove one happy event and the admin metrics suite summed whatever the database returned; neither pinned the step where a fee event stops being XDR and becomes the amount and token the per-token totals group on. The new suite builds real ScVals with nativeToScVal and covers the i128/u64 boundaries, both address forms, the documented missing-field failure with what it must not do (no transaction, no row, no broadcast), and dependency failures raising instead of reporting a processed fee. Closes #1764 --- backend/tests/fee-collected-decoding.test.ts | 379 +++++++++++++++++++ 1 file changed, 379 insertions(+) create mode 100644 backend/tests/fee-collected-decoding.test.ts diff --git a/backend/tests/fee-collected-decoding.test.ts b/backend/tests/fee-collected-decoding.test.ts new file mode 100644 index 00000000..55a6a04c --- /dev/null +++ b/backend/tests/fee-collected-decoding.test.ts @@ -0,0 +1,379 @@ +/** + * Issue #1764 — deterministic coverage for the FeeCollected accounting path in + * `src/workers/soroban-event-worker.ts`. + * + * The existing worker suite drives `handleFeeCollected` with one happy event and + * the admin metrics suite sums whatever the database hands back. Neither pins the + * decode step — where a fee event stops being XDR and becomes the `amount` and + * `metadata.token` values the per-token fee totals are grouped from. So this file + * covers, against real XDR built with `nativeToScVal`: + * - the integer boundaries of the decoders (the full i128 range, the hi/lo + * composition around 2^64, values past `Number.MAX_SAFE_INTEGER`, u64 max), + * - address decoding for both account and contract forms, + * - the documented failure path (`missing body fields`) and what it must not do + * (no transaction, no row, no broadcast), + * - dependency failures (database down, write rejected) surfacing as errors + * instead of being reported as a processed fee, + * - the exact values the downstream `GROUP BY token` fee sum depends on. + */ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { Keypair, StrKey, nativeToScVal, xdr } from "@stellar/stellar-sdk"; +import type { rpc } from "@stellar/stellar-sdk"; + +const mockTx = vi.hoisted(() => ({ + streamEvent: { findUnique: vi.fn(), upsert: vi.fn(), create: vi.fn() }, + stream: { upsert: vi.fn(), update: vi.fn() }, + user: { upsert: vi.fn() }, +})); + +const mockPrismaObj = vi.hoisted(() => ({ + ...mockTx, + indexerState: { findUnique: vi.fn(), create: vi.fn(), upsert: vi.fn() }, + ledgerCheckpoint: { findMany: vi.fn(), upsert: vi.fn() }, + indexerDeadLetterEvent: { upsert: vi.fn() }, + $transaction: vi.fn(), + $disconnect: vi.fn(), +})); + +vi.mock("../src/lib/prisma.js", () => ({ + default: mockPrismaObj, + prisma: mockPrismaObj, +})); + +vi.mock("../src/services/sse.service.js", () => ({ + sseService: { + broadcastToStream: vi.fn(), + broadcast: vi.fn(), + broadcastToAdmin: vi.fn(), + }, + SSEService: vi.fn(() => ({})), +})); + +vi.mock("../src/logger.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }; +}); + +import { + SorobanEventWorker, + decodeI128, + decodeU64, + decodeU32, + decodeAddress, + decodeMap, + decodeSymbol, + getEventLedgerTimestamp, +} from "../src/workers/soroban-event-worker.js"; +import { sseService } from "../src/services/sse.service.js"; +import logger from "../src/logger.js"; + +// ─── Real XDR helpers ─────────────────────────────────────────────────────── + +const scvU64 = (value: bigint): xdr.ScVal => nativeToScVal(value, { type: "u64" }); +const scvI128 = (value: bigint): xdr.ScVal => nativeToScVal(value, { type: "i128" }); +const scvAddress = (strkey: string): xdr.ScVal => nativeToScVal(strkey, { type: "address" }); + +const I128_MAX = 170141183460469231731687303715884105727n; +const I128_MIN = -170141183460469231731687303715884105728n; +const U64_MAX = 18446744073709551615n; +const TWO_POW_64 = 18446744073709551616n; + +const TREASURY = Keypair.random().publicKey(); +const TOKEN = StrKey.encodeContract(Buffer.alloc(32, 5)); +const STREAM_ID = 7n; + +function feeCollectedEvent( + body: Record, + txHash = "fee-tx-hash", +): rpc.Api.EventResponse { + return { + id: "fee-event-1", + type: "contract", + ledger: 1234, + ledgerClosedAt: "1700000000", + txHash, + transactionIndex: 0, + operationIndex: 0, + inSuccessfulContractCall: true, + topic: [xdr.ScVal.scvSymbol("FeeCollected"), scvU64(STREAM_ID)], + value: xdr.ScVal.scvMap( + Object.entries(body).map( + ([key, val]) => new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(key), val }), + ), + ), + } as unknown as rpc.Api.EventResponse; +} + +function completeFeeBody(): Record { + return { + treasury: scvAddress(TREASURY), + fee_amount: scvI128(2_500_000_000n), + token: scvAddress(TOKEN), + }; +} + +describe("i128 decoding (fee amounts)", () => { + it("reads zero, one and minus one as exact decimal strings", () => { + for (const value of [0n, 1n, -1n]) { + expect(decodeI128(scvI128(value))).toBe(value.toString()); + } + }); + + it("reads the full i128 range without losing digits", () => { + expect(decodeI128(scvI128(I128_MAX))).toBe(I128_MAX.toString()); + expect(decodeI128(scvI128(I128_MIN))).toBe(I128_MIN.toString()); + }); + + it("composes the signed hi and unsigned lo halves at 2^64", () => { + // The largest value the low half alone carries, then exactly 2^64, then one + // past it. A decoder that adds instead of shifts — or reads lo as signed — + // is wrong on only one side of this boundary. + expect(decodeI128(scvI128(U64_MAX))).toBe(U64_MAX.toString()); + expect(decodeI128(scvI128(TWO_POW_64))).toBe(TWO_POW_64.toString()); + expect(decodeI128(scvI128(TWO_POW_64 + 1n))).toBe("18446744073709551617"); + }); + + it("decodes negatives whose low half is full", () => { + // -1 and -2^64 both carry hi = -1 with different lows; neither may come back + // as a huge positive. + expect(decodeI128(scvI128(-1n))).toBe("-1"); + expect(decodeI128(scvI128(-TWO_POW_64))).toBe("-18446744073709551616"); + expect(decodeI128(scvI128(-123_456_789_012_345_678_901n))).toBe( + "-123456789012345678901", + ); + }); + + it("stays exact past Number.MAX_SAFE_INTEGER, where a Number decode drifts", () => { + const beyondSafe = 9_007_199_254_740_993n; // 2^53 + 1 + const decoded = decodeI128(scvI128(beyondSafe)); + + expect(decoded).toBe("9007199254740993"); + expect(BigInt(decoded)).toBe(beyondSafe); + // The guard against a regression that narrows the decode to a Number: + // 2^53 + 1 is not representable, so it would round the last digit off. + expect(String(Number(beyondSafe))).not.toBe(decoded); + }); + + it("rejects a value outside the i128 range instead of wrapping it", () => { + expect(() => scvI128(I128_MAX + 1n)).toThrow(); + expect(() => scvI128(I128_MIN - 1n)).toThrow(); + }); +}); + +describe("u64, u32, symbol and map decoding", () => { + it("returns u64 as a BigInt across its range", () => { + expect(decodeU64(scvU64(0n))).toBe(0n); + expect(decodeU64(scvU64(U64_MAX))).toBe(U64_MAX); + expect(typeof decodeU64(scvU64(U64_MAX))).toBe("bigint"); + }); + + it("rejects a u64 outside its range", () => { + expect(() => scvU64(-1n)).toThrow(); + expect(() => scvU64(U64_MAX + 1n)).toThrow(); + }); + + it("reads u32 as a number at both ends", () => { + expect(decodeU32(nativeToScVal(0, { type: "u32" }))).toBe(0); + expect(decodeU32(nativeToScVal(4_294_967_295, { type: "u32" }))).toBe(4_294_967_295); + }); + + it("reads a symbol by name", () => { + expect(decodeSymbol(xdr.ScVal.scvSymbol("FeeCollected"))).toBe("FeeCollected"); + }); + + it("keys a map struct by field name and keeps the raw values", () => { + const body = decodeMap( + xdr.ScVal.scvMap([ + new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol("treasury"), val: scvU64(1n) }), + new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol("token"), val: scvU64(2n) }), + ]), + ); + + expect(Object.keys(body)).toEqual(["treasury", "token"]); + expect(decodeU64(body["treasury"]!)).toBe(1n); + expect(decodeU64(body["token"]!)).toBe(2n); + }); + + it("returns an empty object for a map with no entries", () => { + expect(decodeMap(xdr.ScVal.scvMap([]))).toEqual({}); + }); +}); + +describe("address decoding", () => { + it("encodes an account address as the same G... key that went in", () => { + const decoded = decodeAddress(scvAddress(TREASURY)); + + expect(decoded).toBe(TREASURY); + expect(StrKey.isValidEd25519PublicKey(decoded)).toBe(true); + }); + + it("encodes a contract address as the same C... key that went in", () => { + const decoded = decodeAddress(scvAddress(TOKEN)); + + expect(decoded).toBe(TOKEN); + expect(StrKey.isValidContract(decoded)).toBe(true); + }); + + it("keeps an account and a contract built from the same 32 bytes distinct", () => { + // Both forms carry a 32-byte body, so a decoder that ignores the + // discriminant reports one address for both — and the per-token fee grouping + // would collapse every token into the treasury key. + const bytes = Buffer.alloc(32, 9); + const asAccount = StrKey.encodeEd25519PublicKey(bytes); + const asContract = StrKey.encodeContract(bytes); + + expect(decodeAddress(scvAddress(asAccount))).toBe(asAccount); + expect(decodeAddress(scvAddress(asContract))).toBe(asContract); + expect(decodeAddress(scvAddress(asAccount))).not.toBe(decodeAddress(scvAddress(asContract))); + }); +}); + +describe("ledger close time", () => { + it("uses ledgerClosedAt when it is a sane integer", () => { + expect(getEventLedgerTimestamp({ ledgerClosedAt: "1700000000" })).toBe(1700000000); + expect(getEventLedgerTimestamp({ ledgerClosedAt: "0" })).toBe(0); + }); + + it("falls back to the current time for absent or unusable values", () => { + const before = Math.floor(Date.now() / 1000); + + expect(getEventLedgerTimestamp({ ledgerClosedAt: "-5" })).toBeGreaterThanOrEqual(before); + expect(getEventLedgerTimestamp({ ledgerClosedAt: "not-a-time" })).toBeGreaterThanOrEqual( + before, + ); + expect(getEventLedgerTimestamp({} as never)).toBeGreaterThanOrEqual(before); + }); +}); + +describe("handleFeeCollected — documented success path", () => { + let worker: SorobanEventWorker; + + beforeEach(() => { + vi.clearAllMocks(); + mockPrismaObj.$transaction.mockImplementation((cb: any) => cb(mockTx)); + mockTx.streamEvent.findUnique.mockResolvedValue(null); + mockTx.streamEvent.upsert.mockResolvedValue({ id: "fee-event-1" }); + worker = new SorobanEventWorker(); + }); + + it("writes the stream id, the exact amount and the token metadata in one transaction", async () => { + const event = feeCollectedEvent(completeFeeBody()); + + await (worker as any).handleFeeCollected(event, event.topic![1]); + + expect(mockPrismaObj.$transaction).toHaveBeenCalledTimes(1); + expect(mockTx.streamEvent.upsert).toHaveBeenCalledTimes(1); + + const call = mockTx.streamEvent.upsert.mock.calls[0]![0]; + expect(call.where).toEqual({ + transactionHash_eventType: { transactionHash: "fee-tx-hash", eventType: "FEE_COLLECTED" }, + }); + expect(call.create).toMatchObject({ + streamId: STREAM_ID, + eventType: "FEE_COLLECTED", + amount: "2500000000", + transactionHash: "fee-tx-hash", + ledgerSequence: 1234, + }); + // The admin fee totals group on metadata->>'token', so the token has to land + // as the decoded contract address — the same string the SSE payload reports. + expect(JSON.parse(call.create.metadata as string)).toEqual({ + treasury: TREASURY, + token: TOKEN, + }); + }); + + it("keeps an amount past the safe-integer range exact through to the broadcast", async () => { + const huge = 9_007_199_254_740_993n; + const event = feeCollectedEvent({ ...completeFeeBody(), fee_amount: scvI128(huge) }); + + await (worker as any).handleFeeCollected(event, event.topic![1]); + + expect(mockTx.streamEvent.upsert.mock.calls[0]![0].create.amount).toBe(huge.toString()); + const broadcast = ( + sseService.broadcastToAdmin as unknown as ReturnType + ).mock.calls[0]!; + expect(broadcast[0]).toBe("stream.fee_collected"); + expect(broadcast[1]).toMatchObject({ + streamId: STREAM_ID, + feeAmount: huge.toString(), + token: TOKEN, + ledger: 1234, + }); + }); + + it("carries an i128 extreme through untruncated, which is what SUM depends on", async () => { + const event = feeCollectedEvent({ ...completeFeeBody(), fee_amount: scvI128(I128_MAX) }); + + await (worker as any).handleFeeCollected(event, event.topic![1]); + + expect(mockTx.streamEvent.upsert.mock.calls[0]![0].create.amount).toBe(I128_MAX.toString()); + }); + + it("skips the write and warns when the same event is delivered twice", async () => { + const event = feeCollectedEvent(completeFeeBody()); + mockTx.streamEvent.findUnique.mockResolvedValueOnce({ id: "already-there" }); + + await (worker as any).handleFeeCollected(event, event.topic![1]); + + expect(mockTx.streamEvent.upsert).not.toHaveBeenCalled(); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining("Duplicate StreamEvent skipped"), + ); + expect(sseService.broadcastToAdmin).toHaveBeenCalledTimes(1); + }); +}); + +describe("handleFeeCollected — failure paths", () => { + let worker: SorobanEventWorker; + + beforeEach(() => { + vi.clearAllMocks(); + mockPrismaObj.$transaction.mockImplementation((cb: any) => cb(mockTx)); + mockTx.streamEvent.findUnique.mockResolvedValue(null); + mockTx.streamEvent.upsert.mockResolvedValue({ id: "fee-event-1" }); + worker = new SorobanEventWorker(); + }); + + for (const missing of ["treasury", "fee_amount", "token"]) { + it(`rejects a body without ${missing} and writes nothing`, async () => { + const body = completeFeeBody(); + delete (body as Record)[missing]; + const event = feeCollectedEvent(body); + + await expect((worker as any).handleFeeCollected(event, event.topic![1])).rejects.toThrow( + "FeeCollected #7: missing body fields", + ); + + expect(mockPrismaObj.$transaction).not.toHaveBeenCalled(); + expect(mockTx.streamEvent.upsert).not.toHaveBeenCalled(); + expect(sseService.broadcastToAdmin).not.toHaveBeenCalled(); + }); + } + + it("lets a database failure surface instead of reporting a processed fee", async () => { + const event = feeCollectedEvent(completeFeeBody()); + const dbDown = new Error("connection refused"); + mockPrismaObj.$transaction.mockRejectedValueOnce(dbDown); + + await expect((worker as any).handleFeeCollected(event, event.topic![1])).rejects.toThrow( + dbDown, + ); + + expect(sseService.broadcastToAdmin).not.toHaveBeenCalled(); + }); + + it("does not broadcast when the write inside the transaction fails", async () => { + const event = feeCollectedEvent(completeFeeBody()); + mockTx.streamEvent.upsert.mockRejectedValueOnce(new Error("unique constraint")); + + await expect((worker as any).handleFeeCollected(event, event.topic![1])).rejects.toThrow( + "unique constraint", + ); + + expect(sseService.broadcastToAdmin).not.toHaveBeenCalled(); + }); +}); From 8715fe47354ce56eb9b3c32d13e6377440fdf548 Mon Sep 17 00:00:00 2001 From: Raheemah2k26 Date: Sat, 21 Nov 2026 16:27:36 +0100 Subject: [PATCH 4/6] test(backend): cover bigint timestamp migration safety Static half asserts the migration converts every Stream timestamp and StreamEvent.timestamp to BIGINT, adds endTime as a nullable column behind the IF NOT EXISTS guard that makes re-running it safe, never routes a timestamp through a floating-point type, and matches schema.prisma. The live half probes information_schema types, round-trips 2^53+1 and the int64 extremes, stores a huge timestamp next to a NULL, and proves a failed $transaction leaves nothing behind. Writes go to a separate schema inside a rolled-back transaction: applying the statements straight to "Stream" would take ACCESS EXCLUSIVE and rewrite it, which stalls the other integration suites that share this database. Closes #1766 --- .../bigint-timestamp-migration.test.ts | 353 ++++++++++++++++++ 1 file changed, 353 insertions(+) create mode 100644 backend/tests/integration/bigint-timestamp-migration.test.ts diff --git a/backend/tests/integration/bigint-timestamp-migration.test.ts b/backend/tests/integration/bigint-timestamp-migration.test.ts new file mode 100644 index 00000000..df1c5a30 --- /dev/null +++ b/backend/tests/integration/bigint-timestamp-migration.test.ts @@ -0,0 +1,353 @@ +/** + * Issue #1766 — coverage for the bigint timestamp migration + * (`prisma/migrations/20260729170000_timestamp_bigint/migration.sql`). + * + * Two halves, because the two failure modes are different: + * + * A. The migration text itself. It runs on every deploy, so its contract is + * asserted statically and always: the four `Stream` timestamp columns and + * `StreamEvent.timestamp` end up as BIGINT, the nullable `endTime` is added + * idempotently, nothing converts through a floating-point type, and the + * generated schema agrees with the SQL. A drift between schema.prisma and + * the migration is the classic way this breaks in production, so it fails + * here instead. + * + * B. The migrated database's behaviour: values past `Number.MAX_SAFE_INTEGER` + * round-trip exactly, NULL stays NULL, an out-of-int64 value is rejected + * rather than clamped, and a transaction that fails after writing leaves no + * row behind. These need a real Postgres, so they follow the repository's + * existing convention (`_db.ts`): probe first, skip cleanly with an + * explanation when the server is not reachable. + * + * Every statement in part B runs inside a transaction that is always rolled + * back, so a suite executed against a shared server leaves no trace. + */ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { readFileSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import pg from "pg"; +import { + resolveDbReadiness, + resolveTestDatabaseUrl, + explainSkipReason, + type DbReadiness, +} from "./_db.js"; + +const MIGRATION_DIR = join( + process.cwd(), + "prisma", + "migrations", + "20260729170000_timestamp_bigint", +); +const MIGRATION_SQL = join(MIGRATION_DIR, "migration.sql"); +const PRISMA_SCHEMA = join(process.cwd(), "prisma", "schema.prisma"); + +// ─── A. The migration as written ───────────────────────────────────────────── + +describe("timestamp bigint migration SQL (#1766)", () => { + const sql = (() => { + try { + return readFileSync(MIGRATION_SQL, "utf8"); + } catch { + return ""; + } + })(); + + it("is present in the migration chain", () => { + expect(existsSync(MIGRATION_DIR)).toBe(true); + expect(sql).not.toBe(""); + }); + + it("converts every Stream timestamp column to BIGINT", () => { + for (const column of ["startTime", "lastUpdateTime", "pausedAt"]) { + expect(sql, `${column} must be converted`).toMatch( + new RegExp(`ALTER COLUMN "${column}" SET DATA TYPE BIGINT`), + ); + } + }); + + it("adds endTime as a nullable BIGINT without failing on a re-run", () => { + // Idempotence matters: this migration has to survive being replayed onto a + // database that already has the column, so the ADD must be guarded. + expect(sql).toMatch(/ADD COLUMN IF NOT EXISTS "endTime" BIGINT/); + expect(sql).not.toMatch(/ADD COLUMN "endTime"/); + }); + + it("converts StreamEvent.timestamp too", () => { + expect(sql).toMatch(/ALTER TABLE "StreamEvent"\s+ALTER COLUMN "timestamp" SET DATA TYPE BIGINT/); + }); + + it("never routes a timestamp through a floating-point type", () => { + // A USING clause that casts through double precision loses the low digits of + // an i128-scale timestamp — the exact bug the column type change exists to fix. + expect(sql).not.toMatch(/double precision/i); + expect(sql).not.toMatch(/\breal\b/i); + expect(sql).not.toMatch(/USING/i); + }); + + it("agrees with the generated Prisma schema", () => { + const schema = readFileSync(PRISMA_SCHEMA, "utf8"); + const streamModel = /model Stream \{([\s\S]*?)\n\}/.exec(schema)?.[1] ?? ""; + const eventModel = /model StreamEvent \{([\s\S]*?)\n\}/.exec(schema)?.[1] ?? ""; + + for (const column of ["startTime", "lastUpdateTime", "endTime", "pausedAt"]) { + expect(streamModel, `${column} must be BigInt in schema.prisma`).toMatch( + new RegExp(`^\\s+${column}\\s+BigInt`, "m"), + ); + } + // endTime and pausedAt gained their nullability in this migration; a required + // column would fail to convert on any existing row. + expect(streamModel).toMatch(/endTime\s+BigInt\?/); + expect(streamModel).toMatch(/pausedAt\s+BigInt\?/); + expect(eventModel).toMatch(/^\s+timestamp\s+BigInt/m); + }); +}); + +// ─── B. The migrated database's behaviour ──────────────────────────────────── + +/** + * The repository's convention for real-DB suites: probe, then skip with an + * explanation. On top of that, writes are only attempted against the dedicated + * test database, never a server pointed at production data. + */ +const TEST_DATABASE_NAME = /\/([A-Za-z0-9_]+)(\?|$)/; +function isTestDatabase(url: string | null): boolean { + if (!url) return false; + return TEST_DATABASE_NAME.exec(url)?.[1]?.endsWith("_test") === true; +} + +describe("bigint timestamps in a migrated database (#1766)", () => { + let readiness: DbReadiness | null = null; + let databaseUrl: string | undefined; + let pool: pg.Pool | null = null; + + beforeAll(async () => { + readiness = await resolveDbReadiness(); + databaseUrl = readiness.url ?? undefined; + if (readiness.ready && databaseUrl && isTestDatabase(databaseUrl)) { + pool = new pg.Pool({ connectionString: databaseUrl, max: 1 }); + } + }); + + afterAll(async () => { + // Release the pool so a half-broken server does not keep the runner alive. + await pool?.end().catch(() => undefined); + }); + + async function inRolledBackTransaction( + run: (client: pg.PoolClient) => Promise, + ): Promise { + if (!pool) throw new Error("no test database pool"); + const client = await pool.connect(); + try { + await client.query("BEGIN"); + await run(client); + } finally { + await client.query("ROLLBACK"); + client.release(); + } + } + + async function skipUnlessMigrated(context: any): Promise { + if (!readiness?.ready || !pool) { + // A database without this migration applied is not evidence of a defect, + // so report why nothing ran rather than failing the suite. + console.warn( + explainSkipReason( + readiness ?? { ready: false, reason: "not probed", url: resolveTestDatabaseUrl() }, + ), + ); + context.skip(); + } + } + + it("stores the timestamp columns as int8", async (context) => { + await skipUnlessMigrated(context); + + const client = await pool!.connect(); + try { + const { rows } = await client.query( + `SELECT table_name, column_name, data_type, is_nullable + FROM information_schema.columns + WHERE (table_name = 'Stream' AND column_name IN ('startTime','endTime','lastUpdateTime','pausedAt')) + OR (table_name = 'StreamEvent' AND column_name = 'timestamp') + ORDER BY table_name, column_name`, + ); + expect(rows.map((r) => `${r.table_name}.${r.column_name}`)).toEqual( + expect.arrayContaining([ + "Stream.endTime", + "Stream.lastUpdateTime", + "Stream.pausedAt", + "Stream.startTime", + "StreamEvent.timestamp", + ]), + ); + expect(rows.every((r) => r.data_type === "bigint")).toBe(true); + + const nullable = new Map(rows.map((r) => [`${r.table_name}.${r.column_name}`, r.is_nullable])); + expect(nullable.get("Stream.endTime")).toBe("YES"); + expect(nullable.get("Stream.pausedAt")).toBe("YES"); + expect(nullable.get("Stream.startTime")).toBe("NO"); + expect(nullable.get("StreamEvent.timestamp")).toBe("NO"); + } finally { + client.release(); + } + }); + + it("round-trips a value past Number.MAX_SAFE_INTEGER without losing digits", async (context) => { + await skipUnlessMigrated(context); + + // 2^53 + 1 — the first integer a double cannot represent. An int32 column + // would have overflowed long ago; a float8 column would round it here. + const beyondSafe = "9007199254740993"; + + await inRolledBackTransaction(async (client) => { + const { rows } = await client.query( + `SELECT (${beyondSafe}::bigint + 1)::text AS next, + (${beyondSafe}::bigint * 2)::text AS doubled`, + ); + expect(rows[0].next).toBe("9007199254740994"); + expect(rows[0].doubled).toBe("18014398509481986"); + + const stored = await client.query( + `SELECT ${beyondSafe}::bigint AS raw, ${beyondSafe}::numeric::text AS as_numeric`, + ); + expect(stored.rows[0].raw).toBe(beyondSafe); + expect(stored.rows[0].as_numeric).toBe(beyondSafe); + }); + }); + + it("accepts the full int64 range and rejects one past it", async (context) => { + await skipUnlessMigrated(context); + + const client = await pool!.connect(); + try { + await client.query("BEGIN"); + const extremes = await client.query( + `SELECT '9223372036854775807'::bigint AS max_int8, + '-9223372036854775808'::bigint AS min_int8`, + ); + expect(extremes.rows[0].max_int8).toBe("9223372036854775807"); + expect(extremes.rows[0].min_int8).toBe("-9223372036854775808"); + + // One past int64 must raise, not clamp to the boundary. + await expect( + client.query(`SELECT '9223372036854775808'::bigint`), + ).rejects.toThrow(/out of range|overflow|invalid input syntax/i); + await client.query("ROLLBACK"); + } finally { + client.release(); + } + }); + + it("stores a huge timestamp and a NULL in the same BIGINT row", async (context) => { + await skipUnlessMigrated(context); + + // The same shape the migrated columns have: one required BIGINT timestamp, + // two nullable ones. A row that carries a value past 2^53 next to a NULL is + // the case the type change was made for — a 32-bit column overflows on the + // value and a NOT NULL column fails on the NULL. + const beyondSafe = "9007199254740993"; + await inRolledBackTransaction(async (client) => { + await client.query( + `CREATE TABLE bigint_ts_probe ( + "startTime" BIGINT NOT NULL, + "endTime" BIGINT, + "pausedAt" BIGINT + )`, + ); + await client.query( + `INSERT INTO bigint_ts_probe ("startTime","endTime","pausedAt") + VALUES ($1, NULL, NULL), ($2, $3, $4)`, + [beyondSafe, "1700000000", "1700000001", "1700000002"], + ); + + const { rows } = await client.query( + `SELECT "startTime"::text AS start, + "endTime" IS NULL AS end_null, + "pausedAt" IS NULL AS paused_null + FROM bigint_ts_probe ORDER BY "startTime"`, + ); + expect(rows).toEqual([ + { start: "1700000000", end_null: false, paused_null: false }, + { start: beyondSafe, end_null: true, paused_null: true }, + ]); + }); + }); + + it("leaves no row behind when a transaction fails after writing", async (context) => { + await skipUnlessMigrated(context); + + const client = await pool!.connect(); + try { + await client.query("BEGIN"); + await client.query( + `CREATE TABLE bigint_ts_rollback_probe ("timestamp" BIGINT NOT NULL)`, + ); + await client.query( + `INSERT INTO bigint_ts_rollback_probe ("timestamp") VALUES (9007199254740993)`, + ); + // Fail after the write, the way a later statement in the worker's + // $transaction would. + await expect(client.query(`SELECT 1/0`)).rejects.toThrow(/division by zero/i); + await client.query("ROLLBACK"); + } finally { + client.release(); + } + + // Nothing survived: neither the table nor its row. + const gone = await pool!.query( + `SELECT to_regclass('bigint_ts_rollback_probe') AS rel`, + ); + expect(gone.rows[0].rel).toBeNull(); + }); + + it("re-applies the migration statements without erroring", async (context) => { + await skipUnlessMigrated(context); + + const sql = readFileSync(MIGRATION_SQL, "utf8"); + // Re-running a completed migration is what happens on a fresh clone of an + // existing database; the statements have to tolerate that. + // + // It runs against clone tables in a throwaway schema rather than the real + // `"Stream"`/`"StreamEvent"`, because `ALTER TABLE ... SET DATA TYPE` takes an + // ACCESS EXCLUSIVE lock and rewrites the table — enough to stall the other + // integration suites that share this database. Quoted identifiers still + // resolve through `search_path`, so the statements under test are unchanged. + await inRolledBackTransaction(async (client) => { + await client.query(`CREATE SCHEMA bigint_ts_reapply`); + await client.query(`SET LOCAL search_path = bigint_ts_reapply, public`); + await client.query( + `CREATE TABLE "Stream" ( + "startTime" INTEGER NOT NULL, + "lastUpdateTime" INTEGER NOT NULL, + "pausedAt" INTEGER + )`, + ); + await client.query( + `CREATE TABLE "StreamEvent" ("timestamp" INTEGER NOT NULL)`, + ); + + await client.query(sql); + + const { rows } = await client.query( + `SELECT table_name, column_name, data_type + FROM information_schema.columns + WHERE table_schema = 'bigint_ts_reapply' + ORDER BY table_name, column_name`, + ); + expect(rows.every((r) => r.data_type === "bigint")).toBe(true); + expect(rows.map((r) => `${r.table_name}.${r.column_name}`)).toEqual([ + "Stream.endTime", + "Stream.lastUpdateTime", + "Stream.pausedAt", + "Stream.startTime", + "StreamEvent.timestamp", + ]); + + // Second application: the `IF NOT EXISTS` guard is the only thing that + // keeps a re-run from failing on the added column. + await client.query(sql); + }); + }); +}); From 1fee47c59334719a98829f594fdc90cd5ebf044b Mon Sep 17 00:00:00 2001 From: Raheemah2k26 Date: Sat, 21 Nov 2026 16:49:07 +0100 Subject: [PATCH 5/6] docs(api): add requestId to the documented error envelope #1494 made sendApiError stamp requestId onto every error body, but the hand-authored Error schema in the OpenAPI spec still described only code/message/details, so the committed spec and the generated client types contradicted the response the API actually returns. Regenerated backend/swagger/flowfi.openapi.json via codegen:openapi and frontend/src/lib/api-types.generated.ts via codegen:api-types so the drift check stays clean. --- backend/src/config/swagger.ts | 5 +++++ backend/swagger/flowfi.openapi.json | 4 ++++ frontend/src/lib/api-types.generated.ts | 2 ++ 3 files changed, 11 insertions(+) diff --git a/backend/src/config/swagger.ts b/backend/src/config/swagger.ts index 362afa3f..694d5cef 100644 --- a/backend/src/config/swagger.ts +++ b/backend/src/config/swagger.ts @@ -555,6 +555,11 @@ See [Sandbox Mode Documentation](../docs/SANDBOX_MODE.md) for details.`, description: 'Structured validation issues when applicable', items: { type: 'object' }, }, + requestId: { + type: 'string', + description: + 'Correlation ID echoed from X-Request-ID; matches the response header', + }, }, }, }, diff --git a/backend/swagger/flowfi.openapi.json b/backend/swagger/flowfi.openapi.json index 5745c803..e7fbe3d6 100644 --- a/backend/swagger/flowfi.openapi.json +++ b/backend/swagger/flowfi.openapi.json @@ -956,6 +956,10 @@ "items": { "type": "object" } + }, + "requestId": { + "type": "string", + "description": "Correlation ID echoed from X-Request-ID; matches the response header" } } } diff --git a/frontend/src/lib/api-types.generated.ts b/frontend/src/lib/api-types.generated.ts index 02d2c791..80a00685 100644 --- a/frontend/src/lib/api-types.generated.ts +++ b/frontend/src/lib/api-types.generated.ts @@ -3889,6 +3889,8 @@ export interface components { message: string; /** @description Structured validation issues when applicable */ details?: Record[]; + /** @description Correlation ID echoed from X-Request-ID; matches the response header */ + requestId?: string; }; }; }; From 837e603bec972e5e9354ea3f48b48d587cbf894c Mon Sep 17 00:00:00 2001 From: Raheemah2k26 Date: Sat, 21 Nov 2026 17:02:30 +0100 Subject: [PATCH 6/6] docs: align request-id and event-dedup write-up with the shipped behaviour The two prose surfaces that describe these paths still narrated the old code: the error envelope was documented without the requestId #1494 added, and the StreamEvent write path was described as a bare upsert (and, in docs/ARCHITECTURE.md, as a createMany ... skipDuplicates path that the worker has never used). - docs-site api-reference, Postman 400 example, backend/README, docs/ARCHITECTURE, backend/docs/SSE_ARCHITECTURE: error body is { code, message, details?, requestId? } (no `success` field, which the API never emitted), requestIdMiddleware is mounted ahead of the global limiter, and every handler's duplicate check + upsert is one prisma.$transaction. - Verified all eight tx.streamEvent.findUnique call sites sit inside a $transaction, and that no handler emits `success`. Regenerated backend/swagger/flowfi.openapi.json and frontend/src/lib/api-types.generated.ts so the drift check stays clean. --- backend/README.md | 2 +- backend/docs/SSE_ARCHITECTURE.md | 2 +- backend/src/config/swagger.ts | 2 +- backend/swagger/flowfi.openapi.json | 2 +- docs-site/docs/api-reference/index.mdx | 3 ++- docs/ARCHITECTURE.md | 6 +++--- docs/api/flowfi.postman_collection.json | 2 +- frontend/src/lib/api-types.generated.ts | 2 +- 8 files changed, 11 insertions(+), 10 deletions(-) diff --git a/backend/README.md b/backend/README.md index e8a4fb16..6900778b 100644 --- a/backend/README.md +++ b/backend/README.md @@ -106,6 +106,6 @@ The backend exposes an SSE endpoint (`/v1/streams/events`) to stream real-time u ## Logging & Correlation IDs Structured JSON logs generated by Winston (`backend/src/logger.ts`) attach a `requestId` correlation ID via `AsyncLocalStorage` (`requestContext`): -- **HTTP Requests:** Set via `requestIdMiddleware` (`X-Request-ID` header or auto-generated UUID). +- **HTTP Requests:** Set via `requestIdMiddleware` (`X-Request-ID` header or auto-generated UUID). The middleware is mounted ahead of the global rate limiter, so a throttled `429` carries an id too, and `sendApiError` echoes that id as `error.requestId` in the JSON body. - **Worker Poll Batches:** Each poll cycle in `SorobanEventWorker` runs in `requestContext.run({ requestId: randomUUID() }, ...)` so all event logs and error traces share a single ID per cycle. - **Admin Replays:** Replays triggered via `replayFromLedger` / `POST /v1/admin/indexer/replay` execute under a shared `requestId` that is included in all indexer log statements and returned in the HTTP 202 JSON response. diff --git a/backend/docs/SSE_ARCHITECTURE.md b/backend/docs/SSE_ARCHITECTURE.md index 26b1152e..46698cf4 100644 --- a/backend/docs/SSE_ARCHITECTURE.md +++ b/backend/docs/SSE_ARCHITECTURE.md @@ -356,7 +356,7 @@ Replaying events is safe against duplicate event creation in the database: ```prisma @@unique([transactionHash, eventType]) ``` -* **Worker Execution**: In `backend/src/workers/soroban-event-worker.ts`, event handlers execute `prisma.streamEvent.upsert(...)` matching on `{ transactionHash_eventType: { transactionHash, eventType } }`. If an event for that transaction and type has already been recorded, the insertion is skipped. +* **Worker Execution**: In `backend/src/workers/soroban-event-worker.ts`, every event handler runs its duplicate check and its write as one `prisma.$transaction`: a `tx.streamEvent.findUnique(...)` on `{ transactionHash_eventType: { transactionHash, eventType } }` followed by `tx.streamEvent.upsert(...)` only when that lookup came back empty. If an event for that transaction and type has already been recorded, the insertion is skipped and a `Duplicate StreamEvent skipped` warning is logged. * **Operational Note / Caveat**: As documented in `backend/src/services/indexerService.ts:44-47`, deduplication applies to `StreamEvent` log rows. Stream entity state mutations (such as `Stream.withdrawnAmount` in `handleTokensWithdrawn`) are currently updated unconditionally upon reprocessing events; full state mutation idempotency is tracked under issue #808. --- diff --git a/backend/src/config/swagger.ts b/backend/src/config/swagger.ts index 694d5cef..08b2d245 100644 --- a/backend/src/config/swagger.ts +++ b/backend/src/config/swagger.ts @@ -558,7 +558,7 @@ See [Sandbox Mode Documentation](../docs/SANDBOX_MODE.md) for details.`, requestId: { type: 'string', description: - 'Correlation ID echoed from X-Request-ID; matches the response header', + 'Correlation ID echoed from the response X-Request-ID header; omitted when no ID was assigned', }, }, }, diff --git a/backend/swagger/flowfi.openapi.json b/backend/swagger/flowfi.openapi.json index e7fbe3d6..74eb5007 100644 --- a/backend/swagger/flowfi.openapi.json +++ b/backend/swagger/flowfi.openapi.json @@ -959,7 +959,7 @@ }, "requestId": { "type": "string", - "description": "Correlation ID echoed from X-Request-ID; matches the response header" + "description": "Correlation ID echoed from the response X-Request-ID header; omitted when no ID was assigned" } } } diff --git a/docs-site/docs/api-reference/index.mdx b/docs-site/docs/api-reference/index.mdx index 8373651c..c135dee8 100644 --- a/docs-site/docs/api-reference/index.mdx +++ b/docs-site/docs/api-reference/index.mdx @@ -17,8 +17,9 @@ import OpenApiConsole from '@site/src/components/OpenApiConsole'; - **Versioned base path** — everything lives under `/api/v1/`. - **Auth** — wallet JWTs (`Authorization: Bearer …`) for user-scoped routes; admin routes additionally require the admin role claim. -- **Errors** — JSON `{ "success": false, "error": { "code", "message" } }` +- **Errors** — JSON `{ "error": { "code", "message", "requestId"? } }` with meaningful HTTP status codes; validation failures are `400`. + `requestId` echoes the response's `X-Request-ID` when one was assigned. - **Amounts** — all amounts are integer **stroops** (`1 XLM = 10^7` stroops) as strings or numbers; never floats. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 893c4f10..f71ef2df 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -81,7 +81,7 @@ When the indexer worker processes a ledger batch: 1. Reads the cursor from `IndexerState.lastLedger` to determine where to resume 2. Upserts `Stream` records to mirror on-chain state changes -3. Persists each `StreamEvent` via per-event `findUnique` + `upsert` keyed on `(transactionHash, eventType)` (not batch `createMany` with `skipDuplicates`) +3. Persists each `StreamEvent` via per-event `findUnique` + `upsert` keyed on `(transactionHash, eventType)`, both statements inside one `prisma.$transaction` (not batch `createMany` with `skipDuplicates`) 4. Advances `IndexerState.lastLedger` after the batch completes **Database Model Reference:** @@ -174,7 +174,7 @@ Benefits: All backend log lines use standard JSON formatting via Winston and include a `requestId` correlation ID field when running inside a request or worker context (managed by Node's `AsyncLocalStorage` via `requestContext` in `backend/src/logger.ts`). -- **HTTP Requests:** Requests receive or generate a `requestId` via `requestIdMiddleware` (`X-Request-ID` header). +- **HTTP Requests:** Requests receive or generate a `requestId` via `requestIdMiddleware` (`X-Request-ID` header), which runs before the global rate limiter so even a throttled response has one. Standard error bodies (`sendApiError`) echo it as `error.requestId`, matching the `X-Request-ID` response header. - **Background Indexer/Worker Poll Cycles:** Each `SorobanEventWorker` poll batch runs inside `requestContext.run({ requestId: randomUUID() }, ...)` so all RPC fetches, event processing, and per-event error logs within that poll cycle share a single correlation ID. - **Admin Replays:** Triggering an indexer event replay (via `replayFromLedger` or `POST /v1/admin/indexer/replay`) wraps the reset and worker poll cycle in `requestContext`. The correlation ID is included on all log statements emitted during replay and returned in the HTTP API response (`{ ok: true, replayingFrom: , requestId: "" }`). @@ -227,7 +227,7 @@ Key points: @@unique([transactionHash, eventType]) ``` -This means replaying the same on-chain transaction (e.g. during a re-index or worker restart) will produce an `upsert` conflict rather than a duplicate row. The worker uses Prisma's `createOrUpdate` (upsert) path on `Stream` and a `createMany … skipDuplicates` path on `StreamEvent`. +This means replaying the same on-chain transaction (e.g. during a re-index or worker restart) will produce an `upsert` conflict rather than a duplicate row. The worker uses Prisma's `createOrUpdate` (upsert) path on `Stream`, and on `StreamEvent` a per-event `findUnique` + `upsert` — never `createMany … skipDuplicates` — with the check and the write taken inside one `prisma.$transaction` so two concurrent deliveries of the same event cannot both see the row as absent. ### Indexer Cursor — `IndexerState` diff --git a/docs/api/flowfi.postman_collection.json b/docs/api/flowfi.postman_collection.json index b5e3bcac..a776fcd4 100644 --- a/docs/api/flowfi.postman_collection.json +++ b/docs/api/flowfi.postman_collection.json @@ -130,7 +130,7 @@ "code": 400, "_postman_previewlanguage": "json", "header": [{ "key": "Content-Type", "value": "application/json; charset=utf-8" }], - "body": "{\n \"error\": {\n \"code\": \"VALIDATION_ERROR\",\n \"message\": \"Request validation failed\",\n \"details\": [\n { \"code\": \"too_small\", \"path\": [\"sender\"], \"message\": \"Sender address is required\" }\n ]\n }\n}" + "body": "{\n \"error\": {\n \"code\": \"VALIDATION_ERROR\",\n \"message\": \"Request validation failed\",\n \"details\": [\n { \"code\": \"too_small\", \"path\": [\"sender\"], \"message\": \"Sender address is required\" }\n ],\n \"requestId\": \"3f2b1c4a-9d7e-4b52-8a1f-6c0d2e9f4b77\"\n }\n}" } ] }, diff --git a/frontend/src/lib/api-types.generated.ts b/frontend/src/lib/api-types.generated.ts index 80a00685..5e49a5c1 100644 --- a/frontend/src/lib/api-types.generated.ts +++ b/frontend/src/lib/api-types.generated.ts @@ -3889,7 +3889,7 @@ export interface components { message: string; /** @description Structured validation issues when applicable */ details?: Record[]; - /** @description Correlation ID echoed from X-Request-ID; matches the response header */ + /** @description Correlation ID echoed from the response X-Request-ID header; omitted when no ID was assigned */ requestId?: string; }; };