mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
Merge pull request #1145 from MBombeck/perf/dashboard-client
perf: faster charts and insights, no sidebar scrollbar flash, Umami events delivered
This commit is contained in:
33 files changed
+1458
-393
No files matched your search
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
extractUmamiCollectPath,
|
||||
resolveUmamiSendUrls,
|
||||
} from "@/lib/monitoring/umami";
|
||||
import { UMAMI_PROXY_PREFIX } from "@/lib/monitoring/umami-paths";
|
||||
|
||||
/** The endpoint template of a built Umami tracker. */
|
||||
function tracker(collectPath: string): string {
|
||||
return `const{currentScript:u}=c;const R=\`\${(x||""||u.src.split("/").slice(0,-1).join("/")).replace(/\\/$/,"")}${collectPath}\`,_=\`\${e}x\${a}\`;`;
|
||||
}
|
||||
|
||||
describe("extractUmamiCollectPath", () => {
|
||||
it("reads Umami's default endpoint", () => {
|
||||
expect(extractUmamiCollectPath(tracker("/api/send"))).toBe("/api/send");
|
||||
});
|
||||
|
||||
it("reads an endpoint renamed through COLLECT_API_ENDPOINT", () => {
|
||||
expect(extractUmamiCollectPath(tracker("/api/insight"))).toBe(
|
||||
"/api/insight",
|
||||
);
|
||||
expect(extractUmamiCollectPath(tracker("/collect"))).toBe("/collect");
|
||||
});
|
||||
|
||||
it("falls back to the default for an unrecognised build", () => {
|
||||
expect(extractUmamiCollectPath("/* umami disabled */")).toBe("/api/send");
|
||||
});
|
||||
|
||||
it("never accepts a traversal as the collect path", () => {
|
||||
expect(extractUmamiCollectPath(tracker("/../admin"))).toBe("/api/send");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveUmamiSendUrls", () => {
|
||||
it("tries the script directory, the host root and the /umami mount", () => {
|
||||
expect(
|
||||
resolveUmamiSendUrls(
|
||||
"https://stats.example.com/umami/script.js",
|
||||
"/api/insight",
|
||||
),
|
||||
).toEqual([
|
||||
"https://stats.example.com/umami/api/insight",
|
||||
"https://stats.example.com/api/insight",
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses a private host", () => {
|
||||
expect(
|
||||
resolveUmamiSendUrls("http://10.0.0.5/script.js", "/api/send"),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("UMAMI_PROXY_PREFIX", () => {
|
||||
it("sits under the public monitoring family the proxy gate admits", () => {
|
||||
expect(UMAMI_PROXY_PREFIX.startsWith("/api/monitoring/")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
// Client-safe: imported by the tracker tag, so it carries no server code.
|
||||
|
||||
/**
|
||||
* Where the browser's Umami tracker sends its events, relative to the app.
|
||||
*
|
||||
* The tracker posts to `${data-host-url}${collectPath}`, and the collect
|
||||
* path is compiled into the operator's tracker build: `/api/send` by
|
||||
* default, anything at all when the Umami instance sets
|
||||
* `COLLECT_API_ENDPOINT` (a common ad-blocker workaround). Pointing
|
||||
* `data-host-url` at the app origin therefore only worked for default
|
||||
* builds; a renamed endpoint posted every page view to an app path that did
|
||||
* not exist. Every path under this prefix is answered by the one proxy route
|
||||
* (`src/app/api/monitoring/umami/[...path]/route.ts`), so whatever the build
|
||||
* calls its endpoint, the request lands somewhere that forwards it.
|
||||
*/
|
||||
export const UMAMI_PROXY_PREFIX = "/api/monitoring/umami";
|
||||
|
||||
/** Umami's own default collect endpoint. */
|
||||
export const UMAMI_DEFAULT_COLLECT_PATH = "/api/send";
|
||||
@@ -0,0 +1,113 @@
|
||||
import { safeFetch } from "@/lib/safe-fetch";
|
||||
import { isPublicUrl } from "@/lib/validations/notifications";
|
||||
|
||||
import { UMAMI_DEFAULT_COLLECT_PATH } from "./umami-paths";
|
||||
|
||||
/**
|
||||
* The endpoint template in a built tracker:
|
||||
* `` `${(hostUrl || …).replace(/\/$/,"")}/api/send` ``. The capture is the
|
||||
* path the build appends to the host.
|
||||
*/
|
||||
const COLLECT_PATH_PATTERN =
|
||||
/\.replace\(\/\\\/\$\/,\s*(?:""|'')\)\}(\/[\w\-./~]{1,128})`/;
|
||||
|
||||
/** A collect path is a plain absolute path: no traversal, no query. */
|
||||
function isPlainPath(path: string): boolean {
|
||||
return /^\/[\w\-./~]{1,128}$/.test(path) && !path.split("/").includes("..");
|
||||
}
|
||||
|
||||
/**
|
||||
* The collect path compiled into a tracker build, or Umami's default when
|
||||
* the build does not carry a recognisable endpoint template.
|
||||
*/
|
||||
export function extractUmamiCollectPath(script: string): string {
|
||||
const match = COLLECT_PATH_PATTERN.exec(script)?.[1];
|
||||
return match && isPlainPath(match) ? match : UMAMI_DEFAULT_COLLECT_PATH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upstream URLs to try for an event, in order: the collect path under the
|
||||
* script's own directory (Umami served below a path prefix), at the host
|
||||
* root, and under the conventional `/umami` mount. Only public URLs survive.
|
||||
*/
|
||||
export function resolveUmamiSendUrls(
|
||||
scriptUrl: string | null,
|
||||
collectPath: string = UMAMI_DEFAULT_COLLECT_PATH,
|
||||
): string[] {
|
||||
if (!scriptUrl || !isPlainPath(collectPath)) return [];
|
||||
try {
|
||||
const parsed = new URL(scriptUrl);
|
||||
const origin = parsed.origin;
|
||||
const segments = parsed.pathname.split("/").filter(Boolean);
|
||||
// Drop the script file itself (script.js, umami.js, …).
|
||||
if (segments.length > 0 && segments[segments.length - 1]?.includes(".")) {
|
||||
segments.pop();
|
||||
}
|
||||
const prefix = segments.length > 0 ? `/${segments.join("/")}` : "";
|
||||
const candidates = [
|
||||
`${origin}${prefix}${collectPath}`,
|
||||
`${origin}${collectPath}`,
|
||||
`${origin}/umami${collectPath}`,
|
||||
];
|
||||
return Array.from(new Set(candidates.filter((url) => isPublicUrl(url))));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const COLLECT_PATH_TTL_MS = 60 * 60 * 1000;
|
||||
const collectPathCache = new Map<string, { path: string; expiresAt: number }>();
|
||||
|
||||
export type UmamiScriptFetch =
|
||||
{ ok: true; script: string } | { ok: false; reason: string };
|
||||
|
||||
/**
|
||||
* Fetch the operator's tracker. Fail-soft: an unreachable, slow, refused or
|
||||
* non-2xx upstream comes back as `{ ok: false, reason }`, never a throw. A
|
||||
* successful fetch also records the build's collect path, so the event proxy
|
||||
* learns it without a fetch of its own.
|
||||
*/
|
||||
export async function fetchUmamiScript(
|
||||
scriptUrl: string,
|
||||
): Promise<UmamiScriptFetch> {
|
||||
try {
|
||||
const response = await safeFetch(
|
||||
scriptUrl,
|
||||
{ next: { revalidate: 3600 } },
|
||||
// Operator-configured host: pin the connect-time IP so a low-TTL DNS
|
||||
// record cannot rebind the fetch at an internal range.
|
||||
{ requirePublicHost: true },
|
||||
);
|
||||
if (!response.ok) return { ok: false, reason: `HTTP ${response.status}` };
|
||||
const script = await response.text();
|
||||
collectPathCache.set(scriptUrl, {
|
||||
path: extractUmamiCollectPath(script),
|
||||
expiresAt: Date.now() + COLLECT_PATH_TTL_MS,
|
||||
});
|
||||
return { ok: true, script };
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: (err instanceof Error ? err.message : String(err)).slice(0, 200),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The collect path of the configured tracker, from the cache when fresh,
|
||||
* otherwise by fetching the script. `null` when the script cannot be read,
|
||||
* so the caller can refuse rather than guess.
|
||||
*/
|
||||
export async function resolveUmamiCollectPath(
|
||||
scriptUrl: string,
|
||||
): Promise<string | null> {
|
||||
const cached = collectPathCache.get(scriptUrl);
|
||||
if (cached && cached.expiresAt > Date.now()) return cached.path;
|
||||
const fetched = await fetchUmamiScript(scriptUrl);
|
||||
return fetched.ok ? extractUmamiCollectPath(fetched.script) : null;
|
||||
}
|
||||
|
||||
/** Test seam: forget every learnt collect path. */
|
||||
export function resetUmamiCollectPathCache(): void {
|
||||
collectPathCache.clear();
|
||||
}
|
||||
@@ -1,12 +1,17 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { QueryClient, QueryObserver } from "@tanstack/react-query";
|
||||
import { QUERY_CLIENT_DEFAULT_OPTIONS } from "@/lib/pwa/query-client-options";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
__resetRecordScopeForTests,
|
||||
setRecordScope,
|
||||
} from "@/lib/query-keys/record-scope";
|
||||
import { prefetchMedicationsList } from "../prefetch-medications";
|
||||
import {
|
||||
MEDICATIONS_PREFETCH_COVERS_MOUNT_MS,
|
||||
forgetMedicationsPrefetch,
|
||||
prefetchMedicationsList,
|
||||
refetchMedicationsOnMount,
|
||||
} from "../prefetch-medications";
|
||||
|
||||
function envelopeResponse(data: unknown): Response {
|
||||
return new Response(JSON.stringify({ data, error: null }), {
|
||||
@@ -17,7 +22,9 @@ function envelopeResponse(data: unknown): Response {
|
||||
|
||||
afterEach(() => {
|
||||
__resetRecordScopeForTests();
|
||||
forgetMedicationsPrefetch();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("prefetchMedicationsList", () => {
|
||||
@@ -70,3 +77,121 @@ describe("prefetchMedicationsList", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The page cells re-verify on every mount (#316), but a prefetch fired by the
|
||||
* same navigation already is that fresh read. Before, the hover / route-commit
|
||||
* prefetch landed and the mount sent the identical request again, on every
|
||||
* visit, for both the list and the compliance summary.
|
||||
*/
|
||||
describe("refetchMedicationsOnMount", () => {
|
||||
function setup() {
|
||||
const fetchMock = vi.fn(async () => envelopeResponse([]));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const client = new QueryClient({
|
||||
defaultOptions: QUERY_CLIENT_DEFAULT_OPTIONS,
|
||||
});
|
||||
const calls = (path: string) =>
|
||||
fetchMock.mock.calls.filter((call) => (call as unknown[])[0] === path)
|
||||
.length;
|
||||
return { client, calls };
|
||||
}
|
||||
|
||||
/** Mount a page observer the way the medications page does. */
|
||||
async function mountList(client: QueryClient) {
|
||||
const mountFetch = vi.fn(async () => []);
|
||||
const observer = new QueryObserver(client, {
|
||||
queryKey: queryKeys.medications(),
|
||||
queryFn: mountFetch,
|
||||
refetchOnMount: refetchMedicationsOnMount("list"),
|
||||
});
|
||||
const unsubscribe = observer.subscribe(() => {});
|
||||
await Promise.resolve();
|
||||
return { refetched: mountFetch.mock.calls.length > 0, unsubscribe };
|
||||
}
|
||||
|
||||
it("does not repeat a prefetch this navigation just answered", async () => {
|
||||
const { client, calls } = setup();
|
||||
prefetchMedicationsList(client);
|
||||
await vi.waitFor(() => expect(calls("/api/medications")).toBe(1));
|
||||
await vi.waitFor(() =>
|
||||
expect(client.getQueryState(queryKeys.medications())?.status).toBe(
|
||||
"success",
|
||||
),
|
||||
);
|
||||
|
||||
const { refetched, unsubscribe } = await mountList(client);
|
||||
expect(refetched).toBe(false);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("still refetches on mount when the cache holds an older read", async () => {
|
||||
const { client } = setup();
|
||||
const queryFn = vi.fn(async () => []);
|
||||
await client.fetchQuery({ queryKey: queryKeys.medications(), queryFn });
|
||||
|
||||
const { refetched, unsubscribe } = await mountList(client);
|
||||
// No prefetch answered this visit: the #316 re-verification runs.
|
||||
expect(refetched).toBe(true);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("refetches once the prefetch is older than the visit window", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
const { client, calls } = setup();
|
||||
prefetchMedicationsList(client);
|
||||
await vi.waitFor(() =>
|
||||
expect(client.getQueryState(queryKeys.medications())?.status).toBe(
|
||||
"success",
|
||||
),
|
||||
);
|
||||
expect(calls("/api/medications")).toBe(1);
|
||||
|
||||
vi.setSystemTime(Date.now() + MEDICATIONS_PREFETCH_COVERS_MOUNT_MS + 1);
|
||||
const { refetched, unsubscribe } = await mountList(client);
|
||||
expect(refetched).toBe(true);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("a prefetch skipped as fresh does not excuse the mount refetch", async () => {
|
||||
// The return-visit case: the list was read moments ago by a mount, so
|
||||
// the nav-link prefetch does not go to the network, and the remount
|
||||
// must still re-verify.
|
||||
const { client, calls } = setup();
|
||||
await client.fetchQuery({
|
||||
queryKey: queryKeys.medications(),
|
||||
queryFn: async () => [],
|
||||
});
|
||||
prefetchMedicationsList(client);
|
||||
await Promise.resolve();
|
||||
expect(calls("/api/medications")).toBe(0);
|
||||
|
||||
const { refetched, unsubscribe } = await mountList(client);
|
||||
expect(refetched).toBe(true);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("a prefetch from an earlier visit does not excuse a later mount", async () => {
|
||||
// Load the page (route-commit prefetch), leave, come straight back: the
|
||||
// nav-link prefetch finds the entry fresh and stays off the network, so
|
||||
// only the mount can re-verify, and it must.
|
||||
const { client, calls } = setup();
|
||||
prefetchMedicationsList(client);
|
||||
await vi.waitFor(() =>
|
||||
expect(client.getQueryState(queryKeys.medications())?.status).toBe(
|
||||
"success",
|
||||
),
|
||||
);
|
||||
const first = await mountList(client);
|
||||
expect(first.refetched).toBe(false);
|
||||
first.unsubscribe();
|
||||
|
||||
forgetMedicationsPrefetch(); // the route left /medications
|
||||
prefetchMedicationsList(client); // hover on the way back: still fresh
|
||||
expect(calls("/api/medications")).toBe(1);
|
||||
|
||||
const second = await mountList(client);
|
||||
expect(second.refetched).toBe(true);
|
||||
second.unsubscribe();
|
||||
});
|
||||
});
|
||||
@@ -29,20 +29,92 @@ import { apiGet } from "@/lib/api/api-fetch";
|
||||
*/
|
||||
export const MEDICATIONS_LIST_STALE_TIME_MS = 15_000;
|
||||
|
||||
/**
|
||||
* How long after a prefetch STARTED its data still counts as this visit's
|
||||
* fresh read. Wide enough to span hover → click → route commit → mount on a
|
||||
* slow device; far below any gap in which another surface could have
|
||||
* written something the user would expect to see.
|
||||
*/
|
||||
export const MEDICATIONS_PREFETCH_COVERS_MOUNT_MS = 10_000;
|
||||
|
||||
type MedicationsRead = "list" | "compliance";
|
||||
|
||||
/** When the last prefetch that actually went to the network started. */
|
||||
const prefetchStartedAt = new Map<MedicationsRead, number>();
|
||||
|
||||
function prefetchRead(
|
||||
queryClient: QueryClient,
|
||||
read: MedicationsRead,
|
||||
queryKey: readonly unknown[],
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): void {
|
||||
const state = queryClient.getQueryState(queryKey);
|
||||
const willFetch =
|
||||
state?.fetchStatus !== "fetching" &&
|
||||
(!state ||
|
||||
state.dataUpdatedAt < Date.now() - MEDICATIONS_LIST_STALE_TIME_MS);
|
||||
if (willFetch) prefetchStartedAt.set(read, Date.now());
|
||||
void queryClient.prefetchQuery({
|
||||
queryKey,
|
||||
queryFn: () => apiGet(path, { signal }),
|
||||
staleTime: MEDICATIONS_LIST_STALE_TIME_MS,
|
||||
});
|
||||
}
|
||||
|
||||
export function prefetchMedicationsList(
|
||||
queryClient: QueryClient,
|
||||
signal?: AbortSignal,
|
||||
): void {
|
||||
void queryClient.prefetchQuery({
|
||||
queryKey: queryKeys.medications(),
|
||||
queryFn: () => apiGet("/api/medications", { signal }),
|
||||
staleTime: MEDICATIONS_LIST_STALE_TIME_MS,
|
||||
});
|
||||
void queryClient.prefetchQuery({
|
||||
queryKey: queryKeys.medicationComplianceSummary(),
|
||||
queryFn: () => apiGet("/api/medications/compliance", { signal }),
|
||||
staleTime: MEDICATIONS_LIST_STALE_TIME_MS,
|
||||
});
|
||||
prefetchRead(
|
||||
queryClient,
|
||||
"list",
|
||||
queryKeys.medications(),
|
||||
"/api/medications",
|
||||
signal,
|
||||
);
|
||||
prefetchRead(
|
||||
queryClient,
|
||||
"compliance",
|
||||
queryKeys.medicationComplianceSummary(),
|
||||
"/api/medications/compliance",
|
||||
signal,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `refetchOnMount` for the medications reads that must re-verify on every
|
||||
* visit (#316: a take or skip on another device produces no event here).
|
||||
*
|
||||
* Still "always", except when the cached data is the answer to a prefetch
|
||||
* that this same navigation fired moments ago: the hover / touch / focus
|
||||
* intent on the nav link, or the route-commit preload. Leaving the page ends
|
||||
* that navigation (`forgetMedicationsPrefetch`). Re-asking then sent
|
||||
* the identical request a second time, a few hundred milliseconds after the
|
||||
* first answer landed, on every visit to the page. A return to the page with
|
||||
* an older cache entry, or a direct load, still refetches on mount.
|
||||
*/
|
||||
export function refetchMedicationsOnMount(
|
||||
read: MedicationsRead,
|
||||
): (query: { state: { dataUpdatedAt: number } }) => boolean | "always" {
|
||||
return (query) => {
|
||||
const startedAt = prefetchStartedAt.get(read);
|
||||
const answeredThisVisit =
|
||||
startedAt !== undefined &&
|
||||
query.state.dataUpdatedAt >= startedAt &&
|
||||
Date.now() - startedAt < MEDICATIONS_PREFETCH_COVERS_MOUNT_MS;
|
||||
return answeredThisVisit ? false : "always";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* End the visit a recorded prefetch belongs to. Called whenever the route is
|
||||
* anything but `/medications`, so a prefetch only ever excuses the mounts of
|
||||
* the visit it was fired for: leave the page and come back within seconds,
|
||||
* and the remount still re-verifies.
|
||||
*/
|
||||
export function forgetMedicationsPrefetch(): void {
|
||||
prefetchStartedAt.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { apiGet } from "@/lib/api/api-fetch";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { refetchMedicationsOnMount } from "@/lib/queries/prefetch-medications";
|
||||
import type { ComplianceDisplay } from "@/lib/analytics/compliance";
|
||||
|
||||
/**
|
||||
@@ -69,9 +70,10 @@ export function useMedicationComplianceSummary(medicationId: string): {
|
||||
// another surface (the iOS app) leaves this stale for up to the
|
||||
// window, so refetch on every mount: returning to the page reflects
|
||||
// cross-device intakes without a manual reload. The batched read is
|
||||
// one request per visit, server-cached.
|
||||
// one request per visit, server-cached. A prefetch fired by this same
|
||||
// navigation already is that request (see `refetchMedicationsOnMount`).
|
||||
staleTime: 5 * 60 * 1000,
|
||||
refetchOnMount: "always",
|
||||
refetchOnMount: refetchMedicationsOnMount("compliance"),
|
||||
select: (rows: MedicationComplianceSummaryEntry[]) =>
|
||||
rows.find((row) => row.medicationId === medicationId) ?? null,
|
||||
});
|
||||
@@ -92,7 +94,7 @@ export function useMedicationComplianceSummaryAll(): {
|
||||
queryFn: fetchComplianceSummary,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
// v1.16.12 (#316) — fresh on return-navigation (see the per-row hook).
|
||||
refetchOnMount: "always",
|
||||
refetchOnMount: refetchMedicationsOnMount("compliance"),
|
||||
});
|
||||
return { data };
|
||||
}
|
||||
Reference in new issue
Block a user