Files
radicle-explorer/desktop/src/lib/startup.svelte.ts
T
Rūdolfs Ošiņš 05d1a99fef desktop: Stop losing and wasting refreshes on events
An update that arrived while a route was still loading was lost, since the
loader's result then counted as fresh, so the events now invalidate through
the shared helper that marks such fetches stale. A repo arriving or renamed
without the update naming its refs left the sidebar list as it was, and
updates that changed nothing still dropped the hover caches.

A test now checks the frontend's ref update type against the generated
one.
2026-11-20 19:32:17 +01:00

150 lines
5.2 KiB
TypeScript

import type { Key } from "@radicle-gui/core/keys";
import type { RefUpdate } from "@radicle-gui/core/refUpdates";
import type { UnlistenFn } from "@tauri-apps/api/event";
import { isJobsKey, isRepoInfoKey, keys } from "@radicle-gui/core/keys";
import { affectedKeys } from "@radicle-gui/core/refUpdates";
import { invalidate } from "@radicle-gui/ui/lib/query.svelte";
import { listen } from "@tauri-apps/api/event";
import once from "lodash/once";
import { get } from "svelte/store";
import type { RepoList } from "@app/lib/cobQueries";
import { clearEntityCaches, invoke } from "@app/lib/invoke";
import { queryClient } from "@app/lib/query";
import { repoListScope } from "@app/lib/repoListScope";
import { artifactNodeRunning, nodeEvents, nodeRunning } from "./events";
// Collects keys and invalidates them together after `delay`. Job lists under
// a key are left to their own batch unless `jobs` says the keys are theirs.
export function batch(delay: number, jobs: boolean): (affected: Key[]) => void {
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- never rendered
const pending = new Map<string, Key>();
let flush: ReturnType<typeof setTimeout> | undefined;
return affected => {
if (affected.length === 0) return;
for (const key of affected) pending.set(key.join("\0"), key);
flush ??= setTimeout(() => {
flush = undefined;
const queryKeys = [...pending.values()];
pending.clear();
if (!jobs) clearEntityCaches();
for (const queryKey of queryKeys) {
void invalidate(queryClient, {
queryKey,
predicate: query => jobs || !isJobsKey(query.queryKey as Key),
});
}
}, delay);
};
}
// A fetch often updates many refs in a burst, so invalidations are batched.
const invalidateBatched = batch(100, false);
// Listing CI jobs scans every job in the repository, and a running
// job updates often, so job lists refresh at most every few seconds.
const invalidateJobs = batch(5_000, true);
// Whether the repository list shows `rid` as arrived.
function listed(rid: string): boolean {
const list = queryClient.getQueryData<RepoList>(
keys.repoList(repoListScope.value),
);
return (
list !== undefined &&
list.repos.some(repo => repo.rid === rid) &&
!list.seededNotReplicated.includes(rid)
);
}
export function onRefUpdate(update: RefUpdate) {
const affected = affectedKeys(update);
// A key for the whole repository covers its jobs too.
const repoWide = affected.some(key => key.length === 2 && key[0] === "repo");
invalidateJobs([
...affected.filter(isJobsKey),
...(repoWide ? [keys.jobs(update.rid)] : []),
]);
invalidateBatched([
...affected.filter(key => !isJobsKey(key)),
// The repository list changes when a seeded repository arrives, or when an
// identity update renames one.
...(repoWide ||
!listed(update.rid) ||
update.refs?.some(ref => ref.endsWith("refs/rad/id"))
? [keys.repos()]
: []),
]);
}
export let unlistenNodeEvents: UnlistenFn | undefined = undefined;
export function setUnlistenNodeEvents(unlisten: UnlistenFn) {
unlistenNodeEvents = unlisten;
}
// Will be called once in the startup of the app
export const createEventEmittersOnce = once(async (): Promise<UnlistenFn> => {
if (!window.__TAURI_INTERNALS__) {
// The test backend can't emit events, so poll at the backend's pace.
const pollNodes = () => {
invoke<boolean>("node_running")
.then(running => nodeRunning.set(running))
.catch(console.error);
invoke<boolean>("artifact_node_running")
.then(running => artifactNodeRunning.set(running))
.catch(console.error);
};
pollNodes();
const interval = setInterval(pollNodes, 2_000);
return () => clearInterval(interval);
}
const unlisteners = await Promise.all([
listen<boolean>("node_running", event => {
nodeRunning.set(event.payload);
}),
listen<boolean>("artifact_node_running", event => {
artifactNodeRunning.set(event.payload);
}),
listen<boolean>("node_events", event => {
nodeEvents.set(event.payload);
}),
listen<RefUpdate>("ref_update", event => onRefUpdate(event.payload)),
// Another process changed the notifications, such as by clearing some.
listen("notifications_changed", () => {
invalidateBatched([keys.notifications()]);
}),
listen("policies_changed", () => {
invalidateBatched([keys.repos()]);
void invalidate(queryClient, {
predicate: query => isRepoInfoKey(query.queryKey as Key),
});
}),
// The backend may have missed events while it wasn't subscribed.
listen("ref_resync", () => {
clearEntityCaches();
void invalidate(queryClient);
}),
]);
// Without the node's events, refetch what is shown whenever the user comes
// back to the window. CI jobs only arrive through the node, so they can't
// have changed.
const onFocus = () => {
if (!get(nodeEvents)) {
clearEntityCaches();
void invalidate(queryClient, {
predicate: query => !isJobsKey(query.queryKey as Key),
});
}
};
window.addEventListener("focus", onFocus);
return () => {
unlisteners.forEach(unlisten => unlisten());
window.removeEventListener("focus", onFocus);
};
});