headplane/app/utils/ws.ts

48 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-12-30 13:48:10 +05:30
// This is a "side-effect" but we want a lifecycle cache map of
// peer statuses to prevent unnecessary fetches to the agent.
2024-12-31 10:30:14 +05:30
import type { LoaderFunctionArgs } from 'react-router';
2024-12-30 13:48:10 +05:30
2024-12-31 10:30:14 +05:30
type Context = LoaderFunctionArgs['context'];
const cache: { [nodeID: string]: unknown } = {};
2024-12-30 13:48:10 +05:30
export async function queryWS(context: Context, nodeIDs: string[]) {
2024-12-31 10:30:14 +05:30
const ws = context.ws;
const firstClient = ws.clients.values().next().value;
2024-12-30 13:48:10 +05:30
if (!firstClient) {
2024-12-31 10:30:14 +05:30
return cache;
2024-12-30 13:48:10 +05:30
}
const cached = nodeIDs.map((nodeID) => {
2024-12-31 10:30:14 +05:30
const cached = cache[nodeID];
2024-12-30 13:48:10 +05:30
if (cached) {
2024-12-31 10:30:14 +05:30
return cached;
2024-12-30 13:48:10 +05:30
}
2024-12-31 10:30:14 +05:30
});
2024-12-30 13:48:10 +05:30
// We only need to query the nodes that are not cached
2024-12-31 10:30:14 +05:30
const uncached = nodeIDs.filter((nodeID) => !cached.includes(nodeID));
2024-12-30 13:48:10 +05:30
if (uncached.length === 0) {
2024-12-31 10:30:14 +05:30
return cache;
2024-12-30 13:48:10 +05:30
}
2024-12-31 10:30:14 +05:30
firstClient.send(JSON.stringify({ NodeIDs: uncached }));
await new Promise<void>((resolve) => {
2024-12-30 13:48:10 +05:30
const timeout = setTimeout(() => {
2024-12-31 10:30:14 +05:30
resolve();
}, 3000);
2024-12-30 13:48:10 +05:30
2024-12-31 10:30:14 +05:30
firstClient.on('message', (message: string) => {
const data = JSON.parse(message.toString());
2024-12-30 13:48:10 +05:30
if (Object.keys(data).length === 0) {
2024-12-31 10:30:14 +05:30
resolve();
2024-12-30 13:48:10 +05:30
}
for (const [nodeID, status] of Object.entries(data)) {
2024-12-31 10:30:14 +05:30
cache[nodeID] = status;
2024-12-30 13:48:10 +05:30
}
2024-12-31 10:30:14 +05:30
});
});
2024-12-30 13:48:10 +05:30
2024-12-31 10:30:14 +05:30
return cache;
2024-12-30 13:48:10 +05:30
}