Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

live.ts

126 lines3.9 KB

1import { useEffect, useState } from "react";
2import { createCollection, useLiveQuery } from "@tanstack/react-db";
3import { realtimeCollectionOptions } from "@neon/realtime-tanstack";
4import type { RealtimeClient, SealedLiveQuery } from "@neon/realtime/client";
5import type { JournalAPI } from "./session.js";
6​
7export type LiveSpec = {
8 kind: "devices" | "expeditions" | "expedition" | "entries" | "commands";
9 deviceID?: string;
10 expeditionID?: string;
11};
12function collectionFor<Row extends object>(
13 client: RealtimeClient,
14 query: SealedLiveQuery<Row>,
15 renew: () => Promise<SealedLiveQuery<Row>>,
16 key: (row: Row) => string,
17) {
18 return createCollection(
19 realtimeCollectionOptions({
20 client,
21 query,
22 refreshQuery: renew,
23 getKey: key,
24 }),
25 );
27type RemoteCollection<Row extends object> = ReturnType<
28 typeof collectionFor<Row>
29>;
30​
31export function useRemoteRows<Row extends object>(
32 api: JournalAPI,
33 client: RealtimeClient | undefined,
34 spec: LiveSpec | undefined,
35 path: string | undefined,
36 key: (row: Row) => string,
37) {
38 const signature = spec ? JSON.stringify(spec) : undefined;
39 const [source, setSource] = useState<{
40 signature: string;
41 collection: RemoteCollection<Row>;
42 }>();
43 const [snapshot, setSnapshot] = useState<{ path: string; rows: Row[] }>();
44 const [fallbackFor, setFallbackFor] = useState<string>();
45 const [retries, setRetries] = useState(0);
46 const collection =
47 source?.signature === signature ? source?.collection : undefined;
48 const live = useLiveQuery(() => collection);
49​
50 useEffect(() => {
51 if (!client || !signature) return;
52 let stopped = false;
53 let active: RemoteCollection<Row> | undefined;
54 setSource(undefined);
55 const seal = () =>
56 api.read<SealedLiveQuery<Row>>("/live", JSON.parse(signature));
57 void seal()
58 .then((query) => {
59 if (stopped) return;
60 active = collectionFor(client, query, seal, key);
61 setSource({ signature, collection: active });
62 })
63 .catch(() => {
64 if (!stopped) setFallbackFor(signature);
65 });
66 return () => {
67 stopped = true;
68 void active?.cleanup({ dependents: true }).catch(() => {});
69 };
70 }, [api, client, key, signature, retries]);
71​
72 const healthy = !!collection && live.isReady && !live.isSyncError;
73 const terminal = live.isLoadingError || live.status === "error";
74 useEffect(() => {
75 if (!signature || !client) return;
76 if (healthy) {
77 setFallbackFor((value) => (value === signature ? undefined : value));
78 return;
79 }
80 const timer = setTimeout(
81 () => setFallbackFor(signature),
82 terminal || live.isSyncError ? 0 : 4000,
83 );
84 return () => clearTimeout(timer);
85 }, [signature, client, healthy, terminal, live.isSyncError]);
86​
87 const fallback =
88 !!path && (!client || (!healthy && fallbackFor === signature));
89 const needsNewSubscription = !collection || terminal;
90 useEffect(() => {
91 if (!client || !fallback || !needsNewSubscription) return;
92 const timer = setTimeout(() => setRetries((attempt) => attempt + 1), 8000);
93 return () => clearTimeout(timer);
94 }, [client, fallback, needsNewSubscription, retries, signature]);
95​
96 useEffect(() => {
97 if (!path || !fallback) return;
98 let stopped = false;
99 let timer: ReturnType<typeof setTimeout>;
100 async function refresh() {
101 try {
102 const rows = await api.read<Row[]>(path!);
103 if (!stopped) setSnapshot({ path: path!, rows });
104 } catch {
105 // Keep the last visible rows while reconnecting.
106 }
107 if (!stopped) timer = setTimeout(refresh, 15_000);
108 }
109 void refresh();
110 return () => {
111 stopped = true;
112 clearTimeout(timer);
113 };
114 }, [api, path, fallback]);
115​
116 const rows = healthy
117 ? live.data
118 : snapshot?.path === path
119 ? snapshot?.rows
120 : live.data;
121 return {
122 rows,
123 fallback,
124 ready: healthy || (snapshot?.path === path && !!snapshot),
125 };