Open History to see the last commit
1import { rawSql } from "@neon/realtime/server";
2import { trustedRealtime } from "./live";
3
4// Only a committed terminal state cancels inference. A reconnecting transport
5// is not cancellation; the deadline and guarded writes remain independent.
6export async function watchCancellation(
7 id: string,
8 controller: AbortController,
9) {
10 const rt = trustedRealtime();
11 try {
12 const sub = await rt.subscribe(
13 rawSql<{ id: string; status: string }>(
14 "SELECT id::text,status FROM ai_generations WHERE id=$1::uuid",
15 [id],
16 ),
17 );
18 let stopped = false;
19 const receive = (snapshot: ReturnType<typeof sub.getSnapshot>) => {
20 if (
21 !stopped &&
22 snapshot.status === "live" &&
23 !["designing", "checking", "repairing"].includes(
24 snapshot.data?.[0]?.status || "",
25 )
26 )
27 controller.abort();
28 };
29 const off = sub.onChange(receive);
30 receive(sub.getSnapshot());
31 return () => {
32 if (stopped) return;
33 stopped = true;
34 off();
35 sub.unsubscribe();
36 rt.close();
37 };
38 } catch (error) {
39 rt.close();
40 throw error;
41 }
42}