Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 14 additions & 39 deletions backend/src/controllers/stream.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
} from "../repositories/streamEvent.repository.js";
import { findStreams } from "../repositories/stream.repository.js";
import { ApiError, fromPrismaError, sendApiError } from "../lib/api-error.js";
import {
getUserStreamSummaryCache,
invalidateUserStreamSummaryCache,
pruneUserStreamSummaryCache,
setUserStreamSummaryCache,
type UserStreamSummary,
} from "../services/user-summary-cache.js";

const DEFAULT_STREAM_PAGE_SIZE = 20;
const MAX_STREAM_PAGE_SIZE = 100;
Expand All @@ -43,37 +50,6 @@
*/
export const MAX_USER_STREAMS = 500;

interface UserStreamSummary {
address: string;
totalStreamsCreated: number;
totalStreamedOut: string;
totalStreamedIn: string;
currentClaimable: string;
activeOutgoingCount: number;
activeIncomingCount: number;
}

interface UserSummaryCacheEntry {
value: UserStreamSummary;
expiresAtMs: number;
}

const USER_SUMMARY_CACHE_TTL_MS = 30_000;
const userSummaryCache = new Map<string, UserSummaryCacheEntry>();

function pruneUserSummaryCache(nowMs: number): void {
for (const [key, entry] of userSummaryCache.entries()) {
if (entry.expiresAtMs <= nowMs) {
userSummaryCache.delete(key);
}
}
}

// Issue #682: Periodic prune to prevent memory drift when no requests come in
setInterval(() => {
pruneUserSummaryCache(Date.now());
}, 60_000); // Run every 60 seconds

function sumStringI128(values: string[]): string {
let total = 0n;
for (const value of values) {
Expand Down Expand Up @@ -193,6 +169,7 @@
},
});

invalidateUserStreamSummaryCache(sender, recipient);
return res.status(201).json(JSON.parse(JSON.stringify(stream, (_key, value) => typeof value === "bigint" ? value.toString() : value)));
} catch (error) {
if (
Expand Down Expand Up @@ -563,12 +540,12 @@

const nowMs = Date.now();
const cacheKey = address;
const cached = userSummaryCache.get(cacheKey);
if (cached && cached.expiresAtMs > nowMs) {
return res.status(200).json(cached.value);
const cached = getUserStreamSummaryCache(cacheKey, nowMs);
if (cached) {
return res.status(200).json(cached);
}

pruneUserSummaryCache(nowMs);
pruneUserStreamSummaryCache(nowMs);

// Issue #1246: cap the number of streams fetched per direction to prevent
// unbounded DB queries. Power users with more than MAX_USER_STREAMS
Expand Down Expand Up @@ -628,17 +605,17 @@

const totalStreamsCreated = outgoingStreams.length;
const totalStreamedOut = sumStringI128(
outgoingStreams.map((stream: any) => stream.withdrawnAmount),

Check warning on line 608 in backend/src/controllers/stream.controller.ts

View workflow job for this annotation

GitHub Actions / Backend CI

Unexpected any. Specify a different type
);
const totalStreamedIn = sumStringI128(
incomingStreams.map((stream: any) => stream.withdrawnAmount),

Check warning on line 611 in backend/src/controllers/stream.controller.ts

View workflow job for this annotation

GitHub Actions / Backend CI

Unexpected any. Specify a different type
);

const activeOutgoingCount = outgoingStreams.filter(
(stream: any) => stream.isActive,

Check warning on line 615 in backend/src/controllers/stream.controller.ts

View workflow job for this annotation

GitHub Actions / Backend CI

Unexpected any. Specify a different type
).length;
const activeIncomingCount = incomingStreams.filter(
(stream: any) => stream.isActive,

Check warning on line 618 in backend/src/controllers/stream.controller.ts

View workflow job for this annotation

GitHub Actions / Backend CI

Unexpected any. Specify a different type
).length;

const truncated =
Expand All @@ -656,10 +633,7 @@
...(truncated ? { truncated: true } : {}),
} satisfies UserStreamSummary & { truncated?: boolean };

userSummaryCache.set(cacheKey, {
value: summary,
expiresAtMs: nowMs + USER_SUMMARY_CACHE_TTL_MS,
});
setUserStreamSummaryCache(cacheKey, summary, nowMs);

return res.status(200).json(summary);
} catch (error) {
Expand Down Expand Up @@ -744,6 +718,7 @@
applyTopUpOnce(tx, { streamId, txHash, amount }),
);

invalidateUserStreamSummaryCache(stream.sender, stream.recipient);
logger.info(`[topUp] stream=${streamId} amount=${amount} txHash=${txHash}`);
return res
.status(200)
Expand Down
2 changes: 2 additions & 0 deletions backend/src/controllers/stream/cancel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { AuthenticatedRequest } from '../../types/auth.types.js';
import * as streamRepository from '../../repositories/stream.repository.js';
import { parseStreamId } from '../../lib/stream-id.js';
import { ApiError, sendApiError } from '../../lib/api-error.js';
import { invalidateUserStreamSummaryCache } from '../../services/user-summary-cache.js';

/**
* @openapi
Expand Down Expand Up @@ -129,6 +130,7 @@ export const cancelStreamHandler = async (req: AuthenticatedRequest, res: Respon
// atomically (issue #1219) so the stream shows up under the "cancelled"
// filter before the indexer has processed the on-chain event.
await streamRepository.markCancelledProvisionally(parsedStreamId, txHash);
invalidateUserStreamSummaryCache(stream.sender, stream.recipient);

logger.info(`[CancelStream] Stream ${parsedStreamId} cancelled by ${callerAddress}. Tx: ${txHash}`);

Expand Down
60 changes: 60 additions & 0 deletions backend/src/services/user-summary-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
export interface UserStreamSummary {
address: string;
totalStreamsCreated: number;
totalStreamedOut: string;
totalStreamedIn: string;
currentClaimable: string;
activeOutgoingCount: number;
activeIncomingCount: number;
}

interface UserSummaryCacheEntry {
value: UserStreamSummary;
expiresAtMs: number;
}

export const USER_SUMMARY_CACHE_TTL_MS = 30_000;

const userSummaryCache = new Map<string, UserSummaryCacheEntry>();

export function getUserStreamSummaryCache(
address: string,
nowMs: number,
): UserStreamSummary | undefined {
const cached = userSummaryCache.get(address);
if (!cached) return undefined;
if (cached.expiresAtMs <= nowMs) {
userSummaryCache.delete(address);
return undefined;
}
return cached.value;
}

export function setUserStreamSummaryCache(
address: string,
value: UserStreamSummary,
nowMs: number,
): void {
userSummaryCache.set(address, {
value,
expiresAtMs: nowMs + USER_SUMMARY_CACHE_TTL_MS,
});
}

export function invalidateUserStreamSummaryCache(...addresses: string[]): void {
if (addresses.length === 0) {
userSummaryCache.clear();
return;
}
for (const address of addresses) userSummaryCache.delete(address);
}

export function pruneUserStreamSummaryCache(nowMs: number): void {
for (const [address, entry] of userSummaryCache.entries()) {
if (entry.expiresAtMs <= nowMs) userSummaryCache.delete(address);
}
}

setInterval(() => {
pruneUserStreamSummaryCache(Date.now());
}, 60_000);
9 changes: 8 additions & 1 deletion backend/src/validators/stream.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,14 @@ export const createStreamSchema = z.object({
.string()
.regex(/^\d+$/, 'Amount must be a positive integer as string')
.refine(isAtMostI128, { message: 'Amount exceeds maximum allowed value' }),
startTime: z.union([z.number().int().nonnegative(), z.string().regex(/^\d+$/).transform(v => parseInt(v))]),
startTime: z.union([
z.number().int().nonnegative().refine(Number.isSafeInteger, 'Start time must be a safe integer'),
z
.string()
.regex(/^\d+$/)
.transform(Number)
.refine(Number.isSafeInteger, 'Start time must be a safe integer'),
]),
});

export type CreateStreamInput = z.infer<typeof createStreamSchema>;
Expand Down
8 changes: 8 additions & 0 deletions backend/src/workers/soroban-event-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { sseService } from "../services/sse.service.js";
import { sentinelService } from "../services/sentinel.service.js";
import { publishIndexerLag, quarantineEvent } from "../services/indexerService.js";
import { applyToppedUpEvent } from "../services/top-up-writer.js";
import { invalidateUserStreamSummaryCache } from "../services/user-summary-cache.js";
import {
indexerEventsProcessedTotal,
indexerPollsTotal,
Expand Down Expand Up @@ -633,24 +634,31 @@ export class SorobanEventWorker {
switch (eventName) {
case "stream_created":
await this.handleStreamCreated(event, topic1);
invalidateUserStreamSummaryCache();
break;
case "stream_topped_up":
await this.handleStreamToppedUp(event, topic1);
invalidateUserStreamSummaryCache();
break;
case "tokens_withdrawn":
await this.handleTokensWithdrawn(event, topic1);
invalidateUserStreamSummaryCache();
break;
case "stream_paused":
await this.handleStreamPaused(event, topic1);
invalidateUserStreamSummaryCache();
break;
case "stream_resumed":
await this.handleStreamResumed(event, topic1);
invalidateUserStreamSummaryCache();
break;
case "stream_cancelled":
await this.handleStreamCancelled(event, topic1);
invalidateUserStreamSummaryCache();
break;
case "stream_completed":
await this.handleStreamCompleted(event, topic1);
invalidateUserStreamSummaryCache();
break;
case "fee_collected":
await this.handleFeeCollected(event, topic1);
Expand Down
90 changes: 90 additions & 0 deletions backend/tests/integration/streams/withdraw.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,96 @@ describe('POST /api/v1/streams/:streamId/withdraw', () => {
expect(response.body.error.message).toBe('No claimable balance is currently available');
});

it.each([
{
label: 'exact depletion',
withdrawnAmount: '1000',
isActive: true,
},
{
label: 'over-withdrawn accounting state',
withdrawnAmount: '1001',
isActive: true,
},
{
label: 'persisted completed state',
withdrawnAmount: '1000',
isActive: false,
},
])('returns a conflict for $label without mutating persisted completion state', async ({
withdrawnAmount,
isActive,
}) => {
const recipient = makeKeypair();
const token = setAuthAs(recipient);
const streamId = 321;
const nowSec = Math.floor(Date.now() / 1000);
const stream = {
streamId,
sender: makeKeypair().publicKey(),
recipient: recipient.publicKey(),
ratePerSecond: '10',
depositedAmount: '1000',
withdrawnAmount,
startTime: nowSec - 200,
lastUpdateTime: nowSec - 100,
isActive,
isPaused: false,
pausedAt: null,
totalPausedDuration: 0,
updatedAt: new Date(),
};
mockPrisma.stream.findUnique.mockResolvedValue(stream);

const response = await request(app)
.post(`/v1/streams/${streamId}/withdraw`)
.set('Authorization', `Bearer ${token}`);

expect(response.status).toBe(409);
expect(response.body.error).toMatchObject({
code: 'CONFLICT',
message: 'No claimable balance is currently available',
});
expect(mockWithdraw).not.toHaveBeenCalled();
expect(mockPrisma.stream.update).not.toHaveBeenCalled();
expect(mockPrisma.streamEvent.upsert).not.toHaveBeenCalled();
expect(mockPrisma.streamEvent.create).not.toHaveBeenCalled();
expect(stream).toMatchObject({ withdrawnAmount, isActive });
});

it('returns the documented 400 error when the withdrawal simulation dependency fails', async () => {
const recipient = makeKeypair();
const token = setAuthAs(recipient);
const nowSec = Math.floor(Date.now() / 1000);

mockPrisma.stream.findUnique.mockResolvedValue({
streamId: 654,
sender: makeKeypair().publicKey(),
recipient: recipient.publicKey(),
ratePerSecond: '10',
depositedAmount: '1000',
withdrawnAmount: '0',
startTime: nowSec - 100,
lastUpdateTime: nowSec - 50,
isActive: true,
isPaused: false,
pausedAt: null,
totalPausedDuration: 0,
updatedAt: new Date(),
});
mockWithdraw.mockRejectedValue(new Error('Soroban unavailable'));

const response = await request(app)
.post('/v1/streams/654/withdraw')
.set('Authorization', `Bearer ${token}`);

expect(response.status).toBe(400);
expect(response.body.error).toMatchObject({
code: 'WITHDRAWAL_FAILED',
message: 'Failed to withdraw from stream on chain',
});
});

it('never touches withdrawnAmount, isActive or events, however often it is called', async () => {
const recipient = makeKeypair();
const token = setAuthAs(recipient);
Expand Down
Loading
Loading