Skip to content
Open
8 changes: 5 additions & 3 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,12 @@ app.use((err: unknown, req: Request, res: Response, next: NextFunction) => {
// The larger parser MUST be registered first: Express runs middleware in
// registration order, so a request that reaches the 100kb parser first can
// never be rescued by the larger one further down the chain.
//
// Only routes that exist: `/v1/streams/batch`, `/v1/streams/import` and
// `/v1/payroll/import` were listed here while no such route existed anywhere in
// `src/`, so the allowlist granted a 1mb body to requests that could only 404
// (#1900).
const BULK_JSON_PATHS = [
"/v1/streams/batch",
"/v1/streams/import",
"/v1/payroll/import",
// `/v1/streams/simulate` accepts `batch_withdraw`, whose `streamIds` array can
// be large for payroll recipients.
"/v1/streams/simulate",
Expand Down
7 changes: 6 additions & 1 deletion backend/src/graphql/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import express from "express";
import { graphql as executeGraphQL } from "graphql/index.js";
import { prisma } from "../lib/prisma.js";
import { createContext } from "./context.js";
import logger from "../logger.js";
import { schema } from "./schema.js";

export const graphqlRoutes = express.Router();
Expand Down Expand Up @@ -54,8 +55,12 @@ async function execute(request: express.Request, response: express.Response): Pr
});
response.status(200).json(result);
} catch (error) {
// The stack stays in the log; the client gets a stable message. GraphQL
// errors arrive here untyped, and echoing them leaked whatever the
// resolver threw - including Prisma text (#1901).
logger.error("[GraphQL] execution failed:", error);
response.status(200).json({
errors: [{ message: error instanceof Error ? error.message : "GraphQL execution failed" }],
errors: [{ message: "GraphQL execution failed" }],
});
}
}
Expand Down
35 changes: 34 additions & 1 deletion backend/src/middleware/error.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,28 @@ const asStatusedError = (err: unknown): StatusedError | null =>
const statusOf = (err: StatusedError): number =>
err.statusCode ?? err.status ?? 500;

/**
* The status this error will be answered with, before anything is sent.
*
* Needed because the log line and the response must agree on severity: logging
* every rejected request at `error` level buries the failures worth waking up
* for (#1901).
*/
function resolveErrorStatus(err: unknown): number {
if (err instanceof ZodError) return 400;

const prismaError = fromPrismaError(err);
if (prismaError) return prismaError.statusCode;

if (err instanceof ApiError) return err.statusCode;

const candidate = err as { status?: unknown; statusCode?: unknown };
if (typeof candidate?.status === 'number') return candidate.status;
if (typeof candidate?.statusCode === 'number') return candidate.statusCode;

return 500;
}

/**
* Global error handler middleware
*/
Expand All @@ -38,7 +60,18 @@ export const errorHandler = (
res: Response,
next: NextFunction
) => {
logger.error('Unhandled error:', err);
const resolvedStatus = resolveErrorStatus(err);

if (resolvedStatus >= 500) {
// Only server-side failures are incidents. A rejected request is the
// API working: it is logged at warn, with the route, so it stays visible
// without drowning the error stream.
logger.error('Unhandled error:', err);
} else {
logger.warn(
`Request rejected with ${resolvedStatus}: ${req.method} ${req.originalUrl}`,
);
}

if (res.headersSent) {
return next(err);
Expand Down
9 changes: 5 additions & 4 deletions backend/src/services/indexerService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,11 @@ export async function previewReplay(fromLedger: number): Promise<ReplayPreview>
* The @@unique([transactionHash, eventType]) constraint on StreamEvent
* guarantees no duplicate StreamEvent rows are created on replay.
*
* CAVEAT: This dedup does NOT apply to stream state mutations.
* Stream.withdrawnAmount (handleTokensWithdrawn, soroban-event-worker.ts:635)
* is incremented unconditionally on every replay, so replay is NOT fully
* idempotent. See issue #808 for the withdrawnAmount idempotency fix.
* The same holds for stream state: `handleTokensWithdrawn` (and the other
* handlers) check for the existing `StreamEvent` row *before* mutating any
* Stream field, inside the same transaction, so a replay cannot
* double-increment `withdrawnAmount` (#802). Replay is idempotent for both the
* event log and the stream state it derives.
*/
export async function replayFromLedger(
fromLedger: number,
Expand Down
153 changes: 95 additions & 58 deletions backend/src/workers/stream-runway-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,20 @@
* Stream Runway & Low-Balance Alert Engine (Issue #1190)
* Monitors active streams and generates proactive notifications before funds run out
*/
import type { Stream } from "../generated/prisma/index.js";
import { prisma } from "../lib/prisma.js";
import logger from "../logger.js";
import { claimableAmountService } from "../services/claimable.service.js";
import { sseService } from "../services/sse.service.js";

/**
* Streams read per round trip. Large enough that the query count is negligible
* for a normal hour, small enough that a page of records cannot dominate the
* worker's memory: the previous unbounded `findMany` loaded every active
* stream and then made one or two dedup queries per stream, serially (#1899).
*/
const STREAM_PAGE_SIZE = 500;

const WARNING_THRESHOLD_HOURS = 48;
const CRITICAL_THRESHOLD_HOURS = 24;
const DEDUPLICATION_WINDOW_HOURS = 24;
Expand All @@ -23,7 +32,7 @@ interface RunwayCalculation {
/**
* Calculate remaining runway for a stream in seconds
*/
function calculateStreamRunway(stream: any, now: number): RunwayCalculation {
function calculateStreamRunway(stream: Stream, now: number): RunwayCalculation {
const result = claimableAmountService.getClaimableAmount(
{
streamId: stream.streamId,
Expand Down Expand Up @@ -65,25 +74,31 @@ function calculateStreamRunway(stream: any, now: number): RunwayCalculation {
/**
* Check if alert was recently sent to prevent spam
*/
async function wasAlertRecentlySent(
streamId: bigint,
/**
* Which of `streamIds` already received `alertType` inside the deduplication
* window.
*
* One query per page instead of one per stream: the alert history is keyed by
* `(streamId, alertType)` with a `sentAt` index, so a single range scan answers
* the whole page.
*/
async function recentlyAlertedStreams(
streamIds: bigint[],
alertType: string,
): Promise<boolean> {
const cutoff = new Date(
Date.now() - DEDUPLICATION_WINDOW_HOURS * 60 * 60 * 1000,
);
cutoff: Date,
): Promise<Set<string>> {
if (streamIds.length === 0) return new Set();

const recent = await prisma.alertHistory.findFirst({
const rows = await prisma.alertHistory.findMany({
where: {
streamId,
streamId: { in: streamIds },
alertType,
sentAt: {
gte: cutoff,
},
sentAt: { gte: cutoff },
},
select: { streamId: true },
});

return !!recent;
return new Set(rows.map((row) => row.streamId.toString()));
}

/**
Expand Down Expand Up @@ -144,63 +159,85 @@ export async function runStreamRunwayCheck(): Promise<void> {
logger.info("[RunwayWorker] Starting runway check...");

try {
// Fetch all active, unpaused streams
const activeStreams = await prisma.stream.findMany({
where: {
isActive: true,
isPaused: false,
},
});

logger.info(
`[RunwayWorker] Checking ${activeStreams.length} active streams`,
);

const now = Math.floor(Date.now() / 1000);
const cutoff = new Date(
Date.now() - DEDUPLICATION_WINDOW_HOURS * 60 * 60 * 1000,
);
let warningsSent = 0;
let criticalsSent = 0;
let checked = 0;

for (const stream of activeStreams) {
try {
const runway = calculateStreamRunway(stream, now);
// Keyset pagination: the stream table is ordered by its unique id, so a
// cursor is exact and does not drift as streams are created during the run.
// Every page costs one stream query and, at most, two alert-history queries
// — constant in the number of streams being checked.
let cursor: bigint | undefined;

// Check critical threshold (24 hours)
if (runway.remainingRunwaySeconds <= CRITICAL_THRESHOLD_HOURS * 3600) {
const alreadySent = await wasAlertRecentlySent(
stream.streamId,
"CRITICAL_24H",
);
for (;;) {
const page = await prisma.stream.findMany({
where: {
isActive: true,
isPaused: false,
},
orderBy: { streamId: "asc" },
take: STREAM_PAGE_SIZE,
...(cursor === undefined
? {}
: { cursor: { streamId: cursor }, skip: 1 }),
});

if (!alreadySent) {
await sendLowBalanceAlert(runway, "CRITICAL_24H");
await recordAlert(stream.streamId, "CRITICAL_24H");
criticalsSent++;
}
}
// Check warning threshold (48 hours)
else if (
runway.remainingRunwaySeconds <=
WARNING_THRESHOLD_HOURS * 3600
) {
const alreadySent = await wasAlertRecentlySent(
stream.streamId,
"WARNING_48H",
);
if (page.length === 0) break;
checked += page.length;

const critical = await recentlyAlertedStreams(
page.map((stream) => stream.streamId),
"CRITICAL_24H",
cutoff,
);
const warning = await recentlyAlertedStreams(
page.map((stream) => stream.streamId),
"WARNING_48H",
cutoff,
);

if (!alreadySent) {
await sendLowBalanceAlert(runway, "WARNING_48H");
await recordAlert(stream.streamId, "WARNING_48H");
warningsSent++;
for (const stream of page) {
try {
const runway = calculateStreamRunway(stream, now);
const key = stream.streamId.toString();

// Check critical threshold (24 hours)
if (runway.remainingRunwaySeconds <= CRITICAL_THRESHOLD_HOURS * 3600) {
if (!critical.has(key)) {
await sendLowBalanceAlert(runway, "CRITICAL_24H");
await recordAlert(stream.streamId, "CRITICAL_24H");
criticalsSent++;
}
}
// Check warning threshold (48 hours)
else if (
runway.remainingRunwaySeconds <=
WARNING_THRESHOLD_HOURS * 3600
) {
if (!warning.has(key)) {
await sendLowBalanceAlert(runway, "WARNING_48H");
await recordAlert(stream.streamId, "WARNING_48H");
warningsSent++;
}
}
} catch (error) {
logger.error(
`[RunwayWorker] Error processing stream ${stream.streamId}:`,
error,
);
}
} catch (error) {
logger.error(
`[RunwayWorker] Error processing stream ${stream.streamId}:`,
error,
);
}

if (page.length < STREAM_PAGE_SIZE) break;
cursor = page[page.length - 1]!.streamId;
}

logger.info(`[RunwayWorker] Checked ${checked} active streams`);

const duration = Date.now() - startTime;
logger.info(
`[RunwayWorker] Check complete in ${duration}ms. Warnings: ${warningsSent}, Critical: ${criticalsSent}`,
Expand Down
9 changes: 7 additions & 2 deletions backend/tests/body-size-limit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,17 @@ describe('JSON body size limits', () => {
expect(res.body.error.code).toBe('PAYLOAD_TOO_LARGE');
});

it('does not tighten the limit for batch-creation paths', async () => {
it('does not grant a bulk allowance to a route that does not exist', async () => {
// `/v1/streams/batch` was in the 1mb allowlist while no such route existed
// (#1900). Without a route to reach, the request must still be parsed by the
// standard 100kb limit: an allowlist that grants memory to a 404 is the same
// as no limit at all.
const res = await request(app)
.post('/v1/streams/batch')
.set('Content-Type', 'application/json')
.send(jsonBody(300 * 1024));

expect(res.status).not.toBe(413);
expect(res.status).toBe(413);
expect(res.body.error.code).toBe('PAYLOAD_TOO_LARGE');
});
});
9 changes: 6 additions & 3 deletions backend/tests/error.middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ describe('Error Middleware', () => {
});

it('should handle Prisma P2002 error with sanitized DUPLICATE_ENTRY code and without schema leak', () => {
const loggerSpy = vi.spyOn(logger, 'error');
const loggerSpy = vi.spyOn(logger, 'warn');
const errorSpy = vi.spyOn(logger, 'error');
const error = new Prisma.PrismaClientKnownRequestError(
'Unique constraint failed on the fields: (`email`)',
{ code: 'P2002', clientVersion: '1.0', meta: { target: ['email', 'User_email_key'] } },
Expand All @@ -53,8 +54,10 @@ describe('Error Middleware', () => {
expect(jsonStr).not.toContain('email');
expect(jsonStr).not.toContain('User_email_key');

// Verify full error context is preserved in logger
expect(loggerSpy).toHaveBeenCalledWith('Unhandled error:', error);
// A 409 is the API rejecting a duplicate, not an incident: it is logged at
// warn and must not reach the error stream (#1901).
expect(loggerSpy).toHaveBeenCalled();
expect(errorSpy).not.toHaveBeenCalled();
});

it('should handle Prisma P2025 error with sanitized RESOURCE_NOT_FOUND code', () => {
Expand Down
Loading
Loading