forked from Vero-protocol/vero-core-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseRpcNodes.ts
More file actions
253 lines (232 loc) · 8.17 KB
/
Copy pathuseRpcNodes.ts
File metadata and controls
253 lines (232 loc) · 8.17 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
/**
* useRpcNodes — State hook for the user's RPC endpoint list plus active
* selection. Persisted to localStorage so a configured node survives
* reloads. Health probes are kicked off explicitly via `probeAll` rather
* than on mount, so the UI is responsive and requests don't fire from
* every renderer.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { RpcNode } from "../types";
import { probeEndpoint } from "../utils/rpcHealth";
const STORAGE_KEY = "vero.dashboard.rpcNodes";
const ACTIVE_KEY = "vero.dashboard.activeRpcId";
function loadInitial(): { nodes: RpcNode[]; activeId: string | null } {
if (typeof localStorage === "undefined") {
return { nodes: [], activeId: null };
}
try {
const raw = localStorage.getItem(STORAGE_KEY);
const nodes: RpcNode[] = raw ? (JSON.parse(raw) as RpcNode[]) : [];
const activeId = localStorage.getItem(ACTIVE_KEY);
return {
nodes,
activeId: activeId && nodes.some((n) => n.id === activeId) ? activeId : null,
};
} catch {
return { nodes: [], activeId: null };
}
}
/**
* Stable id derived from the URL. We deliberately don't pull in a UUID lib
* because the URL already encodes enough entropy and the result is opaque
* enough for local use.
*/
function deriveId(url: string): string {
let hash = 0;
for (let i = 0; i < url.length; i++) {
hash = (hash * 31 + url.charCodeAt(i)) | 0;
}
return `rpc-${Math.abs(hash).toString(36)}`;
}
export function useRpcNodes() {
const [{ nodes, activeId }, setState] = useState(loadInitial);
// keep a ref so async probes can compare against up-to-date list without
// re-firing effects.
const nodesRef = useRef(nodes);
nodesRef.current = nodes;
// Persist whenever the list or active id changes.
useEffect(() => {
if (typeof localStorage === "undefined") return;
localStorage.setItem(STORAGE_KEY, JSON.stringify(nodes));
}, [nodes]);
useEffect(() => {
if (typeof localStorage === "undefined") return;
if (activeId) {
localStorage.setItem(ACTIVE_KEY, activeId);
} else {
localStorage.removeItem(ACTIVE_KEY);
}
}, [activeId]);
const updateNode = useCallback((id: string, patch: Partial<RpcNode>) => {
setState((prev) => ({
...prev,
nodes: prev.nodes.map((n) => (n.id === id ? { ...n, ...patch } : n)),
}));
}, []);
const addNode = useCallback((label: string, url: string): { ok: boolean; reason?: string; id?: string } => {
const trimmed = normalizeRpcUrl(url.trim());
if (!trimmed) return { ok: false, reason: "URL is required" };
try {
const parsed = new URL(trimmed);
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
return { ok: false, reason: "Only http(s) URLs are supported" };
}
} catch {
return { ok: false, reason: "Invalid URL format" };
}
const id = deriveId(trimmed);
const exists = nodesRef.current.some((n) => n.id === id);
if (exists) {
return { ok: false, reason: "This endpoint is already configured" };
}
const next: RpcNode = {
id,
label: label.trim() || trimmed,
url: trimmed,
latencyMs: null,
status: "unknown",
};
setState((prev) => ({
nodes: [...prev.nodes, next],
// Activate the freshly-added node if there was no active selection.
activeId: prev.activeId ?? id,
}));
return { ok: true, id };
}, []);
const removeNode = useCallback((id: string) => {
setState((prev) => {
const nodes = prev.nodes.filter((n) => n.id !== id);
const activeId =
prev.activeId === id ? (nodes[0]?.id ?? null) : prev.activeId;
return { nodes, activeId };
});
}, []);
const setActive = useCallback((id: string) => {
setState((prev) =>
prev.nodes.some((n) => n.id === id) ? { ...prev, activeId: id } : prev
);
}, []);
const probeAll = useCallback(async () => {
for (const node of nodesRef.current) {
updateNode(node.id, { status: "checking", message: undefined });
}
await Promise.all(
nodesRef.current.map(async (node) => {
const res = await probeEndpoint(node.url);
updateNode(node.id, {
status: res.status,
latencyMs: res.latencyMs,
message: res.message,
lastChecked: new Date().toISOString(),
});
})
);
}, [updateNode]);
const activeNode = useMemo(
() => nodes.find((n) => n.id === activeId) ?? null,
[nodes, activeId]
);
return {
nodes,
activeId,
activeNode,
addNode,
removeNode,
setActive,
probeAll,
};
}
export type { RpcNode };
function readStoredNodes(): RpcNode[] {
if (typeof localStorage === "undefined") return [];
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return [];
try {
return JSON.parse(raw) as RpcNode[];
} catch {
return [];
}
}
/**
* Read the active RPC URL directly from localStorage. This is the
* bridge-friendly counterpart to {@link useRpcNodes} — a host application
* (e.g., one that instantiates `engine-bridge`'s `RpcClient`) can call
* this without mounting the React hook. Returns `null` if no active
* endpoint is configured.
*/
export function getActiveRpcUrl(): string | null {
if (typeof localStorage === "undefined") return null;
const activeId = localStorage.getItem(ACTIVE_KEY);
if (!activeId) return null;
const nodes = readStoredNodes();
const match = nodes.find((n) => n.id === activeId);
return match ? match.url : null;
}
/** Normalise an RPC URL by stripping a trailing slash, if present. */
export function normalizeRpcUrl(url: string): string {
return url.replace(/\/+$/, "");
}
/** Options for {@link getActiveRpcHostUrls}. */
export interface GetActiveRpcHostUrlsOptions {
/**
* Fallback URL(s) appended after the user's configured order. Empty or
* falsy entries are filtered out. Useful for keeping `RpcClient`
* constructors happy (which require a non-empty list) and ensuring
* production defaults are always reachable.
*/
fallback?: string | string[];
}
/**
* Resolve the user's Custom RPC configuration into an ordered, deduped
* URL list suitable for `@vero/engine-bridge`'s `RpcClient`.
*
* Behaviour:
* - Concatenates the active URL, all configured URLs, and any supplied
* fallback(s), filters out empty entries, and dedupes via `Set`
* (which preserves insertion order — so the first occurrence wins,
* keeping the user's active selection at the front).
* - The active URL is placed first so it is the primary candidate for
* the first request; remaining configured URLs follow so failover
* works out of the box.
* - If the `activeId` stored in localStorage no longer matches any node
* (orphan-id case), it is silently dropped — every other configured
* URL is still returned, followed by the fallback.
* - When nothing is configured, only `fallback` is returned. An empty
* fallback (and no fallback) yields `[]` — callers that require a
* non-empty list must supply a fallback.
*
* Host-app usage:
*
* ```ts
* import { RpcClient } from "@vero/engine-bridge";
* import { getActiveRpcHostUrls } from "./hooks/useRpcNodes";
*
* const DEFAULT_RPC = "https://soroban-testnet.stellar.org";
* const rpc = new RpcClient(getActiveRpcHostUrls({ fallback: DEFAULT_RPC }));
*
* await rpc.call(server => server.getLatestLedger());
* ```
*
* This intentionally keeps `dashboard` and `engine-bridge` decoupled:
* neither package imports from the other; the host glues them together.
*/
export function getActiveRpcHostUrls(
options: GetActiveRpcHostUrlsOptions = {}
): string[] {
const fallback = normalizeFallback(options.fallback);
const active = getActiveRpcUrl();
const others =
typeof localStorage === "undefined" ? [] : readStoredNodes().map((n) => n.url);
// Set preserves insertion order, so the highest-priority source wins.
return Array.from(
new Set(
[active, ...others, ...fallback].filter(Boolean) as string[]
)
);
}
function normalizeFallback(fallback?: string | string[]): string[] {
if (!fallback) return [];
const list = Array.isArray(fallback) ? fallback : [fallback];
// Dedupe so callers can pass [A, B, A] safely.
return Array.from(new Set(list.filter(Boolean)));
}