forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseBaseline.ts
More file actions
274 lines (248 loc) · 8.03 KB
/
Copy pathuseBaseline.ts
File metadata and controls
274 lines (248 loc) · 8.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"use client";
import { useEffect, useState, useCallback, useRef } from "react";
import { getPb, pbIsMisconfigured, PB_MISCONFIG_MESSAGE } from "../lib/pb";
import type {
BaselineCell,
BaselineStatus,
BaselineTag,
} from "../lib/baseline-types";
/* ------------------------------------------------------------------ */
/* Public types */
/* ------------------------------------------------------------------ */
export type BaselineConnection = "connecting" | "live" | "error";
export interface UseBaselineResult {
cells: Map<string, BaselineCell>;
status: BaselineConnection;
error: string | null;
updateCell: (
key: string,
status: BaselineStatus,
tags: BaselineTag[],
) => Promise<void>;
}
/* ------------------------------------------------------------------ */
/* Constants */
/* ------------------------------------------------------------------ */
// Baseline has ~825 records — fetch in a single request to avoid
// sequential round-trip latency (5 × 200 = 5 round trips to Railway PB).
const PAGE_SIZE = 1000;
const MAX_PAGES = 2;
const MAX_RECONNECT_ATTEMPTS = 3;
const RECONNECT_BACKOFF_BASE_MS = 1000;
const RECONNECT_BACKOFF_MAX_MS = 8000;
/* ------------------------------------------------------------------ */
/* Hook */
/* ------------------------------------------------------------------ */
/**
* Subscribes to the `baseline` collection. Returns a Map of
* BaselineCell keyed by `cell.key`, connection status, and an
* optimistic `updateCell` function for inline edits.
*
* Follows the same paginated-fetch + SSE subscribe + exponential
* backoff pattern as `useLiveStatus`.
*/
export function useBaseline(): UseBaselineResult {
const [cells, setCells] = useState<Map<string, BaselineCell>>(new Map());
const [status, setStatus] = useState<BaselineConnection>("connecting");
const [error, setError] = useState<string | null>(null);
// Ref to the current cells map so updateCell always sees latest state
// without needing cells in its dependency array.
const cellsRef = useRef<Map<string, BaselineCell>>(cells);
useEffect(() => {
cellsRef.current = cells;
}, [cells]);
useEffect(() => {
if (pbIsMisconfigured()) {
setCells(new Map());
setStatus("error");
setError(PB_MISCONFIG_MESSAGE);
return;
}
const pb = getPb();
let alive = true;
let attempts = 0;
let cancel: (() => void) | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let reconnecting = false;
function teardownSubscription(): void {
if (cancel) {
try {
cancel();
} catch (err) {
// eslint-disable-next-line no-console
console.debug("[useBaseline] unsubscribe failed (best-effort)", {
err,
});
}
cancel = null;
}
}
function clearReconnectTimer(): void {
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
}
function startReconnect(reason: string, err?: unknown): void {
if (reconnecting) return;
reconnecting = true;
setStatus("connecting");
if (err !== undefined) {
setError(err instanceof Error ? err.message : String(err));
} else {
setError(reason);
}
clearReconnectTimer();
teardownSubscription();
void connect();
}
async function fetchInitial(): Promise<Map<string, BaselineCell>> {
// getFullList auto-paginates internally — single call, no manual loop.
const items = await pb
.collection("baseline")
.getFullList<BaselineCell>({ batch: 1000 });
const result = new Map<string, BaselineCell>();
for (const item of items) {
result.set(item.key, item);
}
return result;
}
async function connect(): Promise<void> {
try {
const initial = await fetchInitial();
if (!alive) return;
setCells(initial);
setStatus("live");
setError(null);
attempts = 0;
// Batch SSE updates to avoid per-event re-renders (825 records
// seeding = 825 individual SSE events = 825 Map clones + grid
// re-renders without batching). Buffer events and flush every 100ms.
const sseBuf: Array<{ action: string; record: BaselineCell }> = [];
let flushTimer: ReturnType<typeof setTimeout> | null = null;
function flushSseBuf() {
flushTimer = null;
if (sseBuf.length === 0 || !alive) return;
const batch = sseBuf.splice(0);
setCells((prev) => {
const next = new Map(prev);
for (const evt of batch) {
if (evt.action === "delete") {
next.delete(evt.record.key);
} else {
next.set(evt.record.key, evt.record);
}
}
return next;
});
}
const unsub = await pb
.collection("baseline")
.subscribe<BaselineCell>("*", (e) => {
try {
if (!alive) return;
sseBuf.push({ action: e.action, record: e.record });
if (!flushTimer) {
flushTimer = setTimeout(flushSseBuf, 100);
}
} catch (cbErr) {
// eslint-disable-next-line no-console
console.error("[useBaseline] subscribe callback threw", cbErr);
}
});
if (!alive) {
try {
await unsub();
} catch (unsubErr) {
// eslint-disable-next-line no-console
console.debug(
"[useBaseline] orphan unsubscribe failed (best-effort)",
{ err: unsubErr },
);
}
reconnecting = false;
return;
}
cancel = (): void => {
void unsub();
};
reconnecting = false;
} catch (err) {
if (!alive) {
reconnecting = false;
return;
}
attempts += 1;
if (attempts >= MAX_RECONNECT_ATTEMPTS) {
setCells(new Map());
setStatus("error");
setError(err instanceof Error ? err.message : String(err));
reconnecting = false;
return;
}
const delay = Math.min(
RECONNECT_BACKOFF_BASE_MS * 2 ** (attempts - 1),
RECONNECT_BACKOFF_MAX_MS,
);
clearReconnectTimer();
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
if (alive) void connect();
else reconnecting = false;
}, delay);
}
}
void connect();
return () => {
alive = false;
clearReconnectTimer();
teardownSubscription();
};
}, []);
const updateCell = useCallback(
async (
key: string,
newStatus: BaselineStatus,
newTags: BaselineTag[],
): Promise<void> => {
const current = cellsRef.current.get(key);
if (!current) {
throw new Error(`No baseline cell found for key "${key}"`);
}
const previousCell = { ...current };
const now = new Date().toISOString();
// Optimistic update
const optimistic: BaselineCell = {
...current,
status: newStatus,
tags: newTags,
updated_at: now,
updated_by: "dashboard",
};
setCells((prev) => {
const next = new Map(prev);
next.set(key, optimistic);
return next;
});
try {
const pb = getPb();
await pb.collection("baseline").update(current.id, {
status: newStatus,
tags: newTags,
updated_at: now,
updated_by: "dashboard",
});
} catch (err) {
// Revert optimistic update
setCells((prev) => {
const next = new Map(prev);
next.set(key, previousCell);
return next;
});
throw err;
}
},
[],
);
return { cells, status, error, updateCell };
}