Skip to content

Commit 424339d

Browse files
committed
perf(webapp): cache deployment logs across deployment switches
Switching between deployments in the dashboard re-read the whole build log stream from the start every time. Logs are now kept in a small in-memory, per-tab cache keyed by deployment, seeded instantly on revisit, and the stream is resumed from the next unread record instead of record zero. A deployment whose stream has emitted its finalized event and reached a terminal status is served from the cache without opening a stream at all. The cache is bounded to 20 deployments and 20k log lines total, evicting least recently viewed deployments first. Incoming records are also batched into one state update per tick instead of one per line.
1 parent 11e1cd8 commit 424339d

4 files changed

Lines changed: 330 additions & 113 deletions

File tree

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { describe, expect, it } from "vitest";
2+
import { DeploymentLogsCache, type DeploymentLogEntry } from "./deploymentLogsCache";
3+
4+
function lines(count: number): DeploymentLogEntry[] {
5+
return Array.from({ length: count }, (_, i) => ({
6+
message: `line ${i}`,
7+
timestamp: new Date(0),
8+
level: "info" as const,
9+
}));
10+
}
11+
12+
describe("DeploymentLogsCache", () => {
13+
it("returns undefined for unknown keys", () => {
14+
const cache = new DeploymentLogsCache(2, 100);
15+
expect(cache.get("missing")).toBeUndefined();
16+
});
17+
18+
it("stores and returns entries", () => {
19+
const cache = new DeploymentLogsCache(2, 100);
20+
const value = { logs: lines(3), nextSeqNum: 3, finalized: true, complete: true };
21+
cache.set("a", value);
22+
expect(cache.get("a")).toBe(value);
23+
expect(cache.size).toBe(1);
24+
expect(cache.lineCount).toBe(3);
25+
});
26+
27+
it("evicts the least recently used deployment past the entry limit", () => {
28+
const cache = new DeploymentLogsCache(2, 100);
29+
cache.set("a", { logs: lines(1), nextSeqNum: 1, finalized: false, complete: false });
30+
cache.set("b", { logs: lines(1), nextSeqNum: 1, finalized: false, complete: false });
31+
cache.get("a");
32+
cache.set("c", { logs: lines(1), nextSeqNum: 1, finalized: false, complete: false });
33+
34+
expect(cache.get("b")).toBeUndefined();
35+
expect(cache.get("a")).toBeDefined();
36+
expect(cache.get("c")).toBeDefined();
37+
expect(cache.size).toBe(2);
38+
});
39+
40+
it("evicts oldest deployments past the total line budget", () => {
41+
const cache = new DeploymentLogsCache(10, 10);
42+
cache.set("a", { logs: lines(4), nextSeqNum: 4, finalized: true, complete: true });
43+
cache.set("b", { logs: lines(4), nextSeqNum: 4, finalized: true, complete: true });
44+
cache.set("c", { logs: lines(4), nextSeqNum: 4, finalized: true, complete: true });
45+
46+
expect(cache.get("a")).toBeUndefined();
47+
expect(cache.get("b")).toBeDefined();
48+
expect(cache.get("c")).toBeDefined();
49+
expect(cache.lineCount).toBe(8);
50+
});
51+
52+
it("always keeps the entry just set, even when it alone exceeds the budget", () => {
53+
const cache = new DeploymentLogsCache(10, 10);
54+
cache.set("a", { logs: lines(4), nextSeqNum: 4, finalized: true, complete: true });
55+
cache.set("big", { logs: lines(50), nextSeqNum: 50, finalized: true, complete: true });
56+
57+
expect(cache.get("a")).toBeUndefined();
58+
expect(cache.get("big")?.logs).toHaveLength(50);
59+
expect(cache.size).toBe(1);
60+
expect(cache.lineCount).toBe(50);
61+
});
62+
63+
it("treats replacing a key as a recent use", () => {
64+
const cache = new DeploymentLogsCache(2, 100);
65+
cache.set("a", { logs: lines(1), nextSeqNum: 1, finalized: false, complete: false });
66+
cache.set("b", { logs: lines(1), nextSeqNum: 1, finalized: false, complete: false });
67+
cache.set("a", { logs: lines(2), nextSeqNum: 2, finalized: true, complete: true });
68+
cache.set("c", { logs: lines(1), nextSeqNum: 1, finalized: false, complete: false });
69+
70+
expect(cache.get("b")).toBeUndefined();
71+
expect(cache.get("a")?.logs).toHaveLength(2);
72+
expect(cache.get("c")).toBeDefined();
73+
});
74+
75+
it("keeps recently read deployments when evicting for the line budget", () => {
76+
const cache = new DeploymentLogsCache(10, 10);
77+
cache.set("a", { logs: lines(4), nextSeqNum: 4, finalized: true, complete: true });
78+
cache.set("b", { logs: lines(4), nextSeqNum: 4, finalized: true, complete: true });
79+
cache.get("a");
80+
cache.set("c", { logs: lines(4), nextSeqNum: 4, finalized: true, complete: true });
81+
82+
expect(cache.get("b")).toBeUndefined();
83+
expect(cache.get("a")).toBeDefined();
84+
expect(cache.get("c")).toBeDefined();
85+
expect(cache.lineCount).toBe(8);
86+
});
87+
88+
it("replaces an existing key without double counting lines", () => {
89+
const cache = new DeploymentLogsCache(10, 100);
90+
cache.set("a", { logs: lines(4), nextSeqNum: 4, finalized: false, complete: false });
91+
cache.set("a", { logs: lines(6), nextSeqNum: 6, finalized: true, complete: true });
92+
93+
expect(cache.size).toBe(1);
94+
expect(cache.lineCount).toBe(6);
95+
expect(cache.get("a")?.complete).toBe(true);
96+
});
97+
});
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
export type DeploymentLogEntry = {
2+
message: string;
3+
timestamp: Date;
4+
level: "info" | "error" | "warn" | "debug";
5+
};
6+
7+
export type CachedDeploymentLogs = {
8+
logs: readonly DeploymentLogEntry[];
9+
nextSeqNum: number;
10+
finalized: boolean;
11+
complete: boolean;
12+
};
13+
14+
export class DeploymentLogsCache {
15+
private entries = new Map<string, CachedDeploymentLogs>();
16+
private totalLines = 0;
17+
18+
constructor(
19+
private readonly maxDeployments: number,
20+
private readonly maxTotalLines: number
21+
) {}
22+
23+
get(key: string): CachedDeploymentLogs | undefined {
24+
const entry = this.entries.get(key);
25+
if (!entry) return undefined;
26+
this.entries.delete(key);
27+
this.entries.set(key, entry);
28+
return entry;
29+
}
30+
31+
set(key: string, value: CachedDeploymentLogs) {
32+
const existing = this.entries.get(key);
33+
if (existing) {
34+
this.totalLines -= existing.logs.length;
35+
this.entries.delete(key);
36+
}
37+
this.entries.set(key, value);
38+
this.totalLines += value.logs.length;
39+
40+
for (const [oldestKey, oldest] of this.entries) {
41+
if (oldestKey === key) break;
42+
if (this.entries.size <= this.maxDeployments && this.totalLines <= this.maxTotalLines) break;
43+
this.entries.delete(oldestKey);
44+
this.totalLines -= oldest.logs.length;
45+
}
46+
}
47+
48+
get size() {
49+
return this.entries.size;
50+
}
51+
52+
get lineCount() {
53+
return this.totalLines;
54+
}
55+
}
56+
57+
export const deploymentLogsCache = new DeploymentLogsCache(20, 20_000);
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
import { S2, S2Error } from "@s2-dev/streamstore";
2+
import { DeploymentEventFromString } from "@trigger.dev/core/v3/schemas";
3+
import type { WorkerDeploymentStatus } from "@trigger.dev/database";
4+
import { useEffect, useState } from "react";
5+
import {
6+
deploymentLogsCache,
7+
type DeploymentLogEntry,
8+
} from "~/components/runs/v3/deploymentLogsCache";
9+
10+
type DeploymentEventStream = {
11+
s2: {
12+
basin: string;
13+
stream: string;
14+
accessToken: string;
15+
};
16+
};
17+
18+
const FINISHED_DEPLOYMENT_STATUSES = new Set<WorkerDeploymentStatus>([
19+
"DEPLOYED",
20+
"FAILED",
21+
"CANCELED",
22+
"TIMED_OUT",
23+
]);
24+
25+
type UseDeploymentLogsOptions = {
26+
eventStream: DeploymentEventStream | undefined;
27+
status: WorkerDeploymentStatus;
28+
};
29+
30+
export function useDeploymentLogs({ eventStream, status }: UseDeploymentLogsOptions) {
31+
const [logs, setLogs] = useState<readonly DeploymentLogEntry[]>([]);
32+
const [isStreaming, setIsStreaming] = useState(true);
33+
const [streamError, setStreamError] = useState<string | null>(null);
34+
35+
const basin = eventStream?.s2.basin;
36+
const stream = eventStream?.s2.stream;
37+
const accessToken = eventStream?.s2.accessToken;
38+
39+
useEffect(() => {
40+
if (!basin || !stream || !accessToken) return;
41+
42+
const isFinished = FINISHED_DEPLOYMENT_STATUSES.has(status);
43+
const cacheKey = `${basin}/${stream}`;
44+
const cached = deploymentLogsCache.get(cacheKey);
45+
46+
let entries = cached?.logs ?? [];
47+
let nextSeqNum = cached?.nextSeqNum ?? 0;
48+
let pending: DeploymentLogEntry[] = [];
49+
let flushTimer: ReturnType<typeof setTimeout> | undefined;
50+
let finalized = cached?.finalized ?? false;
51+
52+
// oxlint-disable-next-line react/set-state-in-effect -- Seed from the cache when the selected deployment changes.
53+
setLogs(entries);
54+
setStreamError(null);
55+
56+
if (cached?.complete) {
57+
setIsStreaming(false);
58+
return;
59+
}
60+
61+
setIsStreaming(true);
62+
63+
const abortController = new AbortController();
64+
65+
const flush = () => {
66+
clearTimeout(flushTimer);
67+
flushTimer = undefined;
68+
if (abortController.signal.aborted || pending.length === 0) return;
69+
entries = entries.concat(pending);
70+
pending = [];
71+
setLogs(entries);
72+
};
73+
74+
const push = (entry: DeploymentLogEntry) => {
75+
pending.push(entry);
76+
flushTimer ??= setTimeout(flush, 0);
77+
};
78+
79+
const store = () => {
80+
clearTimeout(flushTimer);
81+
flushTimer = undefined;
82+
if (pending.length > 0) {
83+
entries = entries.concat(pending);
84+
pending = [];
85+
}
86+
if (entries.length === 0 && nextSeqNum === 0 && !finalized) return;
87+
deploymentLogsCache.set(cacheKey, {
88+
logs: entries,
89+
nextSeqNum,
90+
finalized,
91+
complete: finalized && isFinished,
92+
});
93+
};
94+
95+
const streamLogs = async () => {
96+
try {
97+
const s2 = new S2({ accessToken });
98+
const readSession = await s2
99+
.basin(basin)
100+
.stream(stream)
101+
.readSession(
102+
{
103+
start: { from: { seqNum: nextSeqNum }, clamp: true },
104+
stop: { waitSecs: 60 },
105+
},
106+
{ signal: abortController.signal }
107+
);
108+
109+
for await (const record of readSession) {
110+
nextSeqNum = record.seqNum + 1;
111+
112+
const decoded = record.body;
113+
const result = DeploymentEventFromString.safeParse(decoded);
114+
115+
if (!result.success) {
116+
// fallback to the previous format in s2 logs for compatibility
117+
const headers: Record<string, string> = {};
118+
if (record.headers) {
119+
for (const [name, value] of record.headers) {
120+
headers[name] = value;
121+
}
122+
}
123+
const level =
124+
(headers["level"]?.toLowerCase() as DeploymentLogEntry["level"]) ?? "info";
125+
126+
push({ timestamp: new Date(record.timestamp), message: decoded, level });
127+
continue;
128+
}
129+
130+
const event = result.data;
131+
if (event.type === "finalized") finalized = true;
132+
if (event.type !== "log") continue;
133+
134+
push({
135+
timestamp: new Date(record.timestamp),
136+
message: event.data.message,
137+
level: event.data.level,
138+
});
139+
}
140+
} catch (error) {
141+
if (abortController.signal.aborted) return;
142+
143+
if (error instanceof S2Error && error.code === "stream_not_found") {
144+
finalized = isFinished;
145+
return;
146+
}
147+
if (error instanceof S2Error && error.code === "permission_denied") return;
148+
149+
console.error("Failed to stream logs:", error);
150+
setStreamError("Failed to stream logs");
151+
} finally {
152+
if (!abortController.signal.aborted) {
153+
flush();
154+
setIsStreaming(false);
155+
store();
156+
}
157+
}
158+
};
159+
160+
streamLogs();
161+
162+
return () => {
163+
abortController.abort();
164+
store();
165+
};
166+
}, [basin, stream, accessToken, status]);
167+
168+
return { logs, isStreaming, streamError };
169+
}

0 commit comments

Comments
 (0)