diff --git a/backend/README.md b/backend/README.md index 939733ee..8644f2f1 100644 --- a/backend/README.md +++ b/backend/README.md @@ -124,6 +124,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/app.ts b/backend/src/app.ts index 89aa52ce..465f3d65 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -31,12 +31,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/config/swagger.ts b/backend/src/config/swagger.ts index 362afa3f..08b2d245 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 the response X-Request-ID header; omitted when no ID was assigned', + }, }, }, }, diff --git a/backend/src/lib/api-error.ts b/backend/src/lib/api-error.ts index 0665ee12..235b4fc0 100644 --- a/backend/src/lib/api-error.ts +++ b/backend/src/lib/api-error.ts @@ -12,6 +12,7 @@ export interface ApiErrorBody { code: string; message: string; details?: unknown; + requestId?: string; } /** @@ -62,6 +63,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 }); } diff --git a/backend/src/workers/soroban-event-worker.ts b/backend/src/workers/soroban-event-worker.ts index 6215b4f5..bb75dcfb 100644 --- a/backend/src/workers/soroban-event-worker.ts +++ b/backend/src/workers/soroban-event-worker.ts @@ -1239,39 +1239,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/swagger/flowfi.openapi.json b/backend/swagger/flowfi.openapi.json index 5745c803..74eb5007 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 the response X-Request-ID header; omitted when no ID was assigned" } } } diff --git a/backend/tests/cors.test.ts b/backend/tests/cors.test.ts index ce218c4d..9a5ed0c0 100644 --- a/backend/tests/cors.test.ts +++ b/backend/tests/cors.test.ts @@ -78,7 +78,11 @@ describe('CORS policy', () => { expect(response.status).toBe(403); expect(response.headers['content-type']).toMatch(/application\/json/); expect(response.body).toEqual({ - error: { code: 'FORBIDDEN', message: 'CORS origin not allowed' }, + error: { + code: 'FORBIDDEN', + message: 'CORS origin not allowed', + requestId: expect.any(String), + }, }); expect(response.headers['access-control-allow-origin']).toBeUndefined(); expect(warn).toHaveBeenCalledWith( 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(); + }); +}); 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/integration/admin-metrics.test.ts b/backend/tests/integration/admin-metrics.test.ts index 70c8ef6d..a53687b2 100644 --- a/backend/tests/integration/admin-metrics.test.ts +++ b/backend/tests/integration/admin-metrics.test.ts @@ -498,7 +498,7 @@ describe('GET /v1/admin/indexer/status', () => { .set('Authorization', `Bearer ${createToken()}`); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Failed to fetch indexer status' } }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Failed to fetch indexer status', requestId: expect.any(String) } }); }); }); @@ -538,7 +538,7 @@ describe('POST /v1/admin/indexer/reset', () => { .send(body); expect(res.status).toBe(400); - expect(res.body).toEqual({ error: { code: 'BAD_REQUEST', message: 'ledger must be a non-negative integer' } }); + expect(res.body).toEqual({ error: { code: 'BAD_REQUEST', message: 'ledger must be a non-negative integer', requestId: expect.any(String) } }); } expect(resetIndexer).not.toHaveBeenCalled(); @@ -572,7 +572,7 @@ describe('POST /v1/admin/indexer/reset', () => { .send({ ledger: 100 }); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Reset failed' } }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Reset failed', requestId: expect.any(String) } }); }); it('returns a dry-run preview without calling resetIndexer when dryRun=true', async () => { @@ -615,7 +615,7 @@ describe('POST /v1/admin/indexer/reset', () => { .send({ ledger: 500 }); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Reset failed' } }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Reset failed', requestId: expect.any(String) } }); expect(resetIndexer).not.toHaveBeenCalled(); }); }); @@ -652,7 +652,7 @@ describe('POST /v1/admin/indexer/replay', () => { .set('Authorization', `Bearer ${createToken()}`); expect(res.status).toBe(400); - expect(res.body).toEqual({ error: { code: 'BAD_REQUEST', message: 'from_ledger must be a non-negative integer' } }); + expect(res.body).toEqual({ error: { code: 'BAD_REQUEST', message: 'from_ledger must be a non-negative integer', requestId: expect.any(String) } }); } expect(replayFromLedger).not.toHaveBeenCalled(); @@ -683,7 +683,7 @@ describe('POST /v1/admin/indexer/replay', () => { .set('Authorization', `Bearer ${createToken()}`); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Replay failed' } }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Replay failed', requestId: expect.any(String) } }); }); it('returns a dry-run preview without triggering a replay when dryRun=true', async () => { @@ -726,7 +726,7 @@ describe('POST /v1/admin/indexer/replay', () => { .set('Authorization', `Bearer ${createToken()}`); expect(res.status).toBe(500); - expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Replay failed' } }); + expect(res.body).toEqual({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'Replay failed', requestId: expect.any(String) } }); expect(replayFromLedger).not.toHaveBeenCalled(); }); }); 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); + }); + }); +}); 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..44d6de10 --- /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 `lib/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/lib/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"); + }); +}); diff --git a/backend/tests/soroban-event-worker.test.ts b/backend/tests/soroban-event-worker.test.ts index ef759ce0..e1edd15c 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') ); diff --git a/backend/tests/soroban_simulation_errors.test.ts b/backend/tests/soroban_simulation_errors.test.ts index ae704ff8..00a9bab4 100644 --- a/backend/tests/soroban_simulation_errors.test.ts +++ b/backend/tests/soroban_simulation_errors.test.ts @@ -98,6 +98,22 @@ async function simulateFailure(error: unknown): Promise { for (const code of DECLARED_CODES) { const err = service.toSimulationApiError(hostDiagnostic(code), 'create'); - expect(err.status, `code ${code}`).toBe(400); + expect(err.statusCode, `code ${code}`).toBe(400); expect(err.code).toBe('simulation_failed'); - expect(err.details?.contractErrorCode, `code ${code}`).toBe(code); - expect(err.details?.action).toBe('create'); - expect(err.details?.reason).toBe(hostDiagnostic(code)); - expect(String(err.details?.hint)).not.toBe(''); + expect(detailsOf(err).contractErrorCode, `code ${code}`).toBe(code); + expect(detailsOf(err).action).toBe('create'); + expect(detailsOf(err).reason).toBe(hostDiagnostic(code)); + expect(String(detailsOf(err).hint)).not.toBe(''); } }); @@ -158,7 +174,7 @@ describe('toSimulationApiError — the StreamError table', () => { (code) => service.toSimulationApiError(hostDiagnostic(code), 'create').message, ); const hints = DECLARED_CODES.map( - (code) => service.toSimulationApiError(hostDiagnostic(code), 'create').details?.hint, + (code) => detailsOf(service.toSimulationApiError(hostDiagnostic(code), 'create')).hint, ); // Two codes sharing a message means one of them was pasted in, so the @@ -167,14 +183,14 @@ describe('toSimulationApiError — the StreamError table', () => { expect(new Set(hints).size).toBe(DECLARED_CODES.length); for (const code of DECLARED_CODES) { const err = service.toSimulationApiError(hostDiagnostic(code), 'create'); - expect(err.message).not.toBe(err.details?.hint); + expect(err.message).not.toBe(detailsOf(err).hint); } }); it('carries the action through so the client can attribute the failure', () => { for (const action of ['create', 'withdraw', 'cancel', 'top_up', 'batch_withdraw'] as const) { const err = service.toSimulationApiError(hostDiagnostic(2), action); - expect(err.details?.action).toBe(action); + expect(detailsOf(err).action).toBe(action); } }); }); @@ -184,8 +200,8 @@ describe('toSimulationApiError — codes outside the table', () => { for (const code of [15, 42, 999]) { const err = service.toSimulationApiError(hostDiagnostic(code), 'top_up'); - expect(err.details?.contractErrorCode).toBe(code); - expect('hint' in (err.details ?? {})).toBe(false); + expect(detailsOf(err).contractErrorCode).toBe(code); + expect('hint' in (detailsOf(err))).toBe(false); // The raw diagnostic is the only signal the client has for an unknown // variant, so it must survive into the message. expect(err.message).toContain(hostDiagnostic(code)); @@ -196,16 +212,16 @@ describe('toSimulationApiError — codes outside the table', () => { it('treats code 0 as a code rather than as a missing one', () => { const err = service.toSimulationApiError(hostDiagnostic(0), 'cancel'); - expect(err.details?.contractErrorCode).toBe(0); - expect('hint' in (err.details ?? {})).toBe(false); + expect(detailsOf(err).contractErrorCode).toBe(0); + expect('hint' in (detailsOf(err))).toBe(false); }); it('omits contractErrorCode entirely for a diagnostic with no code', () => { const raw = 'transaction failed (result not ok)'; const err = service.toSimulationApiError(raw, 'batch_withdraw'); - expect(Object.keys(err.details ?? {}).sort()).toEqual(['action', 'reason']); - expect(err.details?.reason).toBe(raw); + expect(Object.keys(detailsOf(err)).sort()).toEqual(['action', 'reason']); + expect(detailsOf(err).reason).toBe(raw); expect(err.message).toBe(`Simulation of "batch_withdraw" failed: ${raw}`); }); @@ -217,7 +233,7 @@ describe('toSimulationApiError — codes outside the table', () => { 'tx Bad Sequencce', ]; for (const raw of raws) { - expect(service.toSimulationApiError(raw, 'create').details?.reason).toBe(raw); + expect(detailsOf(service.toSimulationApiError(raw, 'create')).reason).toBe(raw); } }); }); @@ -277,26 +293,26 @@ describe('simulateStreamAction — failed simulation payloads', () => { const err = await simulateFailure(hostDiagnostic(2)); expect(err).toBeInstanceOf(ApiError); - expect(err.status).toBe(400); + expect(err.statusCode).toBe(400); expect(err.message).toBe('Stream not found'); - expect(err.details?.contractErrorCode).toBe(2); + expect(detailsOf(err).contractErrorCode).toBe(2); }); it('serialises a structured simulation error instead of printing [object Object]', async () => { const diagnostic = { error_code: 3, detail: 'caller is not recipient' }; const err = await simulateFailure(diagnostic); - expect(err.details?.reason).toBe(JSON.stringify(diagnostic)); + expect(detailsOf(err).reason).toBe(JSON.stringify(diagnostic)); expect(err.message).toContain(JSON.stringify(diagnostic)); expect(err.message).not.toContain('[object Object]'); }); it('keeps a non-object, non-string error renderable', async () => { const err = await simulateFailure('Error(Contract, #13)'); - expect(err.details?.contractErrorCode).toBe(13); + expect(detailsOf(err).contractErrorCode).toBe(13); const arrayErr = await simulateFailure([hostDiagnostic(1)]); - expect(arrayErr.details?.reason).toBe(JSON.stringify([hostDiagnostic(1)])); + expect(detailsOf(arrayErr).reason).toBe(JSON.stringify([hostDiagnostic(1)])); }); }); 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 02d2c791..5e49a5c1 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 the response X-Request-ID header; omitted when no ID was assigned */ + requestId?: string; }; }; };