Skip to content
2 changes: 1 addition & 1 deletion backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 1 addition & 1 deletion backend/docs/SSE_ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---
Expand Down
10 changes: 6 additions & 4 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
5 changes: 5 additions & 0 deletions backend/src/config/swagger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
},
},
},
},
Expand Down
12 changes: 12 additions & 0 deletions backend/src/lib/api-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface ApiErrorBody {
code: string;
message: string;
details?: unknown;
requestId?: string;
}

/**
Expand Down Expand Up @@ -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 });
}
Expand Down
60 changes: 34 additions & 26 deletions backend/src/workers/soroban-event-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", {
Expand Down
4 changes: 4 additions & 0 deletions backend/swagger/flowfi.openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion backend/tests/cors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading