Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,47 @@
// @vitest-environment node
import { describe, expect, it, vi } from "vitest";
import { eventStream } from "./event-stream";
describe("eventStream", () => {
it("disposes once and ignores late sends after reader cancellation", async () => {
const abortController = new AbortController();
const cleanup = vi.fn();
let sendAfterCancel: ((args: { event?: string; data: string }) => void) | undefined;
const response = eventStream(abortController.signal, (send) => {
sendAfterCancel = send;
send({ event: "ready", data: "initial" });
return cleanup;
});
const reader = response.body!.getReader();
await expect(reader.read()).resolves.toMatchObject({ done: false });
await reader.cancel(new Error("client disconnected"));
expect(cleanup).toHaveBeenCalledTimes(1);
expect(() => sendAfterCancel?.({ event: "heartbeat", data: "late" })).not.toThrow();
abortController.abort();
expect(cleanup).toHaveBeenCalledTimes(1);
});
it("closes and disposes once when the request aborts", async () => {
const abortController = new AbortController();
const cleanup = vi.fn();
let sendAfterAbort: ((args: { event?: string; data: string }) => void) | undefined;
const response = eventStream(abortController.signal, (send) => {
sendAfterAbort = send;
send({ data: "initial" });
return cleanup;
});
const reader = response.body!.getReader();
await expect(reader.read()).resolves.toMatchObject({ done: false });
await expect(reader.read()).resolves.toMatchObject({ done: false });
abortController.abort();
await expect(reader.read()).resolves.toEqual({ done: true, value: undefined });
expect(cleanup).toHaveBeenCalledTimes(1);
expect(() => sendAfterAbort?.({ data: "late" })).not.toThrow();
await reader.cancel();
expect(cleanup).toHaveBeenCalledTimes(1);
});
});
@@ -29,34 +29,57 @@ interface InitFunction {
* @returns A Response object that can be returned from a loader
*/
export function eventStream(signal: AbortSignal, init: InitFunction, options: ResponseInit = {}) {
let stream = new ReadableStream({
let dispose = () => undefined;
const stream = new ReadableStream({
start(controller) {
let encoder = new TextEncoder();
const encoder = new TextEncoder();
let closed = false;
let cleanup: CleanupFunction | undefined;
let cleanupComplete = false;
function runCleanup() {
if (!cleanup || cleanupComplete) return;
cleanupComplete = true;
cleanup();
}
dispose = () => {
if (closed) return;
// Mark the stream closed before invoking user cleanup. A cleanup can
// synchronously publish one final event, which must become a no-op.
closed = true;
signal.removeEventListener("abort", close);
runCleanup();
};
function send({ event = "message", data }: SendFunctionArgs) {
if (closed) return;
controller.enqueue(encoder.encode(`event: ${event}\n`));
controller.enqueue(encoder.encode(`data: ${data}\n\n`));
}
let cleanup = init(send, close);
let closed = false;
function close() {
if (closed) return;
cleanup();
closed = true;
signal.removeEventListener("abort", close);
dispose();
controller.close();
}
signal.addEventListener("abort", close);
cleanup = init(send, close);
// `init` may synchronously close the stream before returning cleanup.
if (closed) runCleanup();
if (signal.aborted) return close();
},
cancel() {
// Cancellation already closes the Web Stream controller. Only dispose
// subscriptions/timers here; calling controller.close() would throw.
dispose();
},
});
let headers = new Headers(options.headers);
const headers = new Headers(options.headers);
if (headers.has("Content-Type")) {
// eslint-disable-next-line no-console
@@ -0,0 +1,98 @@
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PROJECT_BOARD_SSE_EVENT } from "~/utils/integrations/projects/projectBoardEvents.shared";
import { useBoardLiveUpdates } from "./useBoardLiveUpdates";
const mocks = vi.hoisted(() => ({
revalidate: vi.fn(),
state: "idle" as "idle" | "loading",
}));
vi.mock("react-router", () => ({
useRevalidator: () => ({
revalidate: mocks.revalidate,
state: mocks.state,
}),
}));
class FakeEventSource {
static instances: FakeEventSource[] = [];
readonly listeners = new Map<string, Set<EventListenerOrEventListenerObject>>();
closed = false;
constructor(readonly url: string) {
FakeEventSource.instances.push(this);
}
addEventListener(type: string, listener: EventListenerOrEventListenerObject) {
const listeners = this.listeners.get(type) ?? new Set();
listeners.add(listener);
this.listeners.set(type, listeners);
}
removeEventListener(type: string, listener: EventListenerOrEventListenerObject) {
this.listeners.get(type)?.delete(listener);
}
emit(type: string) {
const event = new Event(type);
for (const listener of this.listeners.get(type) ?? []) {
if (typeof listener === "function") listener(event);
else listener.handleEvent(event);
}
}
close() {
this.closed = true;
}
}
describe("useBoardLiveUpdates", () => {
beforeEach(() => {
mocks.revalidate.mockClear();
mocks.state = "idle";
FakeEventSource.instances = [];
vi.stubGlobal("EventSource", FakeEventSource);
});
afterEach(() => vi.unstubAllGlobals());
it("revalidates an idle board after a real change event", () => {
renderHook(() => useBoardLiveUpdates("/acme/projects/stream"));
expect(FakeEventSource.instances).toHaveLength(1);
act(() => FakeEventSource.instances[0]!.emit(PROJECT_BOARD_SSE_EVENT));
expect(mocks.revalidate).toHaveBeenCalledOnce();
});
it("does not duplicate route work while a navigation is active", () => {
const { rerender } = renderHook(
({ paused }) => useBoardLiveUpdates("/acme/projects/stream", { paused }),
{ initialProps: { paused: false } },
);
const source = FakeEventSource.instances[0]!;
rerender({ paused: true });
act(() => source.emit(PROJECT_BOARD_SSE_EVENT));
expect(mocks.revalidate).not.toHaveBeenCalled();
expect(FakeEventSource.instances).toHaveLength(1);
rerender({ paused: false });
act(() => source.emit(PROJECT_BOARD_SSE_EVENT));
expect(mocks.revalidate).toHaveBeenCalledOnce();
});
it("ignores an event while revalidation is busy and closes cleanly", () => {
mocks.state = "loading";
const { unmount } = renderHook(() => useBoardLiveUpdates("/acme/projects/stream"));
const source = FakeEventSource.instances[0]!;
act(() => source.emit(PROJECT_BOARD_SSE_EVENT));
expect(mocks.revalidate).not.toHaveBeenCalled();
unmount();
expect(source.closed).toBe(true);
expect(source.listeners.get(PROJECT_BOARD_SSE_EVENT)?.size).toBe(0);
});
});
@@ -0,0 +1,48 @@
// R-P8b (RA-C2) — client hook that turns the pipeline-board SSE stream into live
// board updates. Opens an EventSource on the board's `sseHref`, and on every real
// `projects.board.changed` change-event revalidates the route so the server
// rebuilds the KanbanBoardVM (loader/VM boundary intact — no client re-compute).
// Snapshot-on-connect and the heartbeat are ignored here; only real change-events
// trigger a revalidation, so there is no polling loop. Route-side wiring keeps the
// screen component pure (no router hooks in the presentational board).
import { useEffect, useRef } from "react";
import { useRevalidator } from "react-router";
import { PROJECT_BOARD_SSE_EVENT } from "~/utils/integrations/projects/projectBoardEvents.shared";
export type BoardLiveUpdatesOptions = {
/**
* The route is already loading/submitting. Its own completion revalidation
* will include the event, so starting another loader here only duplicates
* work and can make an optimistic drop stutter.
*/
paused?: boolean;
};
export function useBoardLiveUpdates(
sseHref: string | null | undefined,
options: BoardLiveUpdatesOptions = {},
): void {
const revalidator = useRevalidator();
// Keep the latest revalidate/state in a ref so the EventSource effect does not
// re-subscribe on every revalidator tick (which would tear down the stream).
const revalidateRef = useRef(revalidator.revalidate);
revalidateRef.current = revalidator.revalidate;
const stateRef = useRef(revalidator.state);
stateRef.current = revalidator.state;
const pausedRef = useRef(Boolean(options.paused));
pausedRef.current = Boolean(options.paused);
useEffect(() => {
if (!sseHref || typeof window === "undefined" || typeof EventSource === "undefined") return;
const source = new EventSource(sseHref);
const handler = () => {
if (!pausedRef.current && stateRef.current === "idle") revalidateRef.current();
};
source.addEventListener(PROJECT_BOARD_SSE_EVENT, handler);
return () => {
source.removeEventListener(PROJECT_BOARD_SSE_EVENT, handler);
source.close();
};
}, [sseHref]);
}