Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+52
-4
@@ -1,19 +1,67 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loadDashboardStreamSnapshot } from "~/services/dashboard/dashboard.server";
|
||||
import { openDashboardStreamSession } from "~/services/dashboard/dashboard.server";
|
||||
import { subscribeToDashboardChanges } from "~/services/dashboard/dashboardEvents.server";
|
||||
import { eventStream } from "~/utils/stream/event-stream";
|
||||
|
||||
// Debounce window for change-triggered snapshot refreshes: a mutation burst
|
||||
// (e.g. a bulk stage move) collapses into one recomputed snapshot.
|
||||
const DASHBOARD_STREAM_REFRESH_DEBOUNCE_MS = 2_000;
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
// Authorize before the stream opens so auth failures surface as a proper
|
||||
// error response instead of an empty event stream.
|
||||
const session = await openDashboardStreamSession({ request, params });
|
||||
|
||||
return eventStream(request.signal, (send) => {
|
||||
let closed = false;
|
||||
void loadDashboardStreamSnapshot({ request, params }).then((snapshot) => {
|
||||
if (!closed) send({ event: "dashboard.snapshot", data: JSON.stringify(snapshot) });
|
||||
});
|
||||
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let refreshing = false;
|
||||
let refreshQueued = false;
|
||||
|
||||
function pushSnapshot() {
|
||||
if (closed) return;
|
||||
if (refreshing) {
|
||||
refreshQueued = true;
|
||||
return;
|
||||
}
|
||||
refreshing = true;
|
||||
void session
|
||||
.loadSnapshot()
|
||||
.then((snapshot) => {
|
||||
if (!closed) send({ event: "dashboard.snapshot", data: JSON.stringify(snapshot) });
|
||||
})
|
||||
.catch(() => {
|
||||
// A failed refresh keeps the last delivered snapshot visible; the
|
||||
// next change event or a reconnect retries.
|
||||
})
|
||||
.finally(() => {
|
||||
refreshing = false;
|
||||
if (refreshQueued && !closed) {
|
||||
refreshQueued = false;
|
||||
scheduleRefresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleRefresh() {
|
||||
if (closed || refreshTimer) return;
|
||||
refreshTimer = setTimeout(() => {
|
||||
refreshTimer = null;
|
||||
pushSnapshot();
|
||||
}, DASHBOARD_STREAM_REFRESH_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
pushSnapshot();
|
||||
const unsubscribe = subscribeToDashboardChanges(session.tenantId, scheduleRefresh);
|
||||
const heartbeat = setInterval(() => {
|
||||
send({ event: "dashboard.heartbeat", data: JSON.stringify({ at: new Date().toISOString() }) });
|
||||
}, 30_000);
|
||||
|
||||
return () => {
|
||||
closed = true;
|
||||
unsubscribe();
|
||||
clearInterval(heartbeat);
|
||||
if (refreshTimer) clearTimeout(refreshTimer);
|
||||
};
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user