diff --git a/src/hooks/useSolarPosition.test.ts b/src/hooks/useSolarPosition.test.ts new file mode 100644 index 00000000..1011a553 --- /dev/null +++ b/src/hooks/useSolarPosition.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + currentSolarPosition: vi.fn(), +})); + +vi.mock("@/ipc", () => ({ + currentSolarPosition: mocks.currentSolarPosition, +})); +vi.mock("@/store/settings.store", () => ({ + settingsStore: { config: { position_source: { type: "AUTOMATIC" } } }, +})); + +const source = { type: "AUTOMATIC" as const, cache_minutes: 15 }; + +async function freshLoader() { + vi.resetModules(); + + return await import("./useSolarPosition"); +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(0)); + mocks.currentSolarPosition.mockImplementation(async () => ({ + altitude: 12, + azimuth: 34, + })); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("solar position polling", () => { + test("simultaneous callers share one backend call", async () => { + const { loadSolarPosition } = await freshLoader(); + + const [a, b] = await Promise.all([ + loadSolarPosition(source), + loadSolarPosition(source), + ]); + + expect(a).toEqual(b); + expect(mocks.currentSolarPosition).toHaveBeenCalledTimes(1); + }); + + test("a reading younger than the TTL is reused", async () => { + const { loadSolarPosition } = await freshLoader(); + + await loadSolarPosition(source); + await loadSolarPosition(source); + + expect(mocks.currentSolarPosition).toHaveBeenCalledTimes(1); + }); + + test("the next poll after the TTL asks the backend again", async () => { + const { loadSolarPosition } = await freshLoader(); + + await loadSolarPosition(source); + vi.advanceTimersByTime(30_001); + await loadSolarPosition(source); + + expect(mocks.currentSolarPosition).toHaveBeenCalledTimes(2); + }); + + test("different position sources are not shared", async () => { + const { loadSolarPosition } = await freshLoader(); + + await loadSolarPosition(source); + await loadSolarPosition({ + type: "MANUAL", + latitude: 1, + longitude: 2, + altitude: 0, + }); + + expect(mocks.currentSolarPosition).toHaveBeenCalledTimes(2); + }); + + test("a failed read is retried instead of cached", async () => { + const { loadSolarPosition } = await freshLoader(); + mocks.currentSolarPosition.mockRejectedValueOnce(new Error("denied")); + + await expect(loadSolarPosition(source)).rejects.toThrow("denied"); + await loadSolarPosition(source); + + expect(mocks.currentSolarPosition).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/hooks/useSolarPosition.ts b/src/hooks/useSolarPosition.ts index e9e73455..e3b76b87 100644 --- a/src/hooks/useSolarPosition.ts +++ b/src/hooks/useSolarPosition.ts @@ -12,13 +12,61 @@ interface Options { pollMs?: number; } +type PositionSource = Parameters[0]; +type SolarPosition = Awaited>; + +/** + * How long a reading is shared between callers. + * + * The stage and the engine panel each poll once a minute, so three windows of the same + * reading overlapped and each invoke landed on a different blocking thread. The Rust + * position cache is thread-local, so those calls did not share a sensor read either. + * Sharing the result here makes the window cost one call per interval, while staying + * well below the backend's 60 s maximum reading age. + */ +const POSITION_CACHE_TTL_MS = 30_000; + +let cached: { key: string; at: number; value: SolarPosition } | undefined; +let inflight: { key: string; promise: Promise } | undefined; + +/** + * Loads a position, sharing a fresh reading and an in-flight request between callers. + * + * Errors are not cached: a denied location or a starting sensor must be retried by the + * next poll rather than replayed for the TTL. + */ +export const loadSolarPosition = ( + source: PositionSource, +): Promise => { + const key = JSON.stringify(source); + const now = Date.now(); + + if (cached?.key === key && now - cached.at < POSITION_CACHE_TTL_MS) { + return Promise.resolve(cached.value); + } + + if (inflight?.key === key) return inflight.promise; + + const promise = currentSolarPosition(source) + .then((value) => { + cached = { key, at: Date.now(), value }; + return value; + }) + .finally(() => { + if (inflight?.promise === promise) inflight = undefined; + }); + + inflight = { key, promise }; + return promise; +}; + export function useSolarPosition(options: Options = {}) { const [position, { refetch }] = createResource( () => (options.enabled?.() ?? true) ? settingsStore.config?.position_source : undefined, - (ps) => currentSolarPosition(ps), + (ps) => loadSolarPosition(ps), ); const pollMs = options.pollMs;