spur-board 0.79.0 → 0.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.mjs CHANGED
@@ -15,6 +15,7 @@ import { Kysely, SqliteDialect, sql } from "kysely";
15
15
  import { AsyncLocalStorage } from "node:async_hooks";
16
16
  import perf_hooks from "node:perf_hooks";
17
17
  import Fastify from "fastify";
18
+ import { PassThrough } from "node:stream";
18
19
  import { pino } from "pino";
19
20
  import { WebAPIHTTPError, WebAPIPlatformError, WebAPIRateLimitedError, WebClient } from "@slack/web-api";
20
21
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
@@ -11235,7 +11236,7 @@ async function createApiServer(options) {
11235
11236
  });
11236
11237
  const snapshot = await buildCatalogSnapshot(OPERATIONS);
11237
11238
  /** Lets clients notice a daemon restart and check its catalog again. */
11238
- const instance = randomUUID();
11239
+ const instance = options.instance ?? randomUUID();
11239
11240
  const callers = /* @__PURE__ */ new WeakMap();
11240
11241
  let doctorInFlight = null;
11241
11242
  let doctorCached = null;
@@ -19702,6 +19703,268 @@ function createInbound(input) {
19702
19703
  };
19703
19704
  }
19704
19705
  //#endregion
19706
+ //#region ../core/src/api/sse.ts
19707
+ const POLL_MS = 300;
19708
+ const HEARTBEAT_MS = 15e3;
19709
+ const STATUS_MS = 3e4;
19710
+ const END_GRACE_MS = 1e3;
19711
+ const MAX_STREAMS = 32;
19712
+ const BATCH = 500;
19713
+ function frame(event, head, data) {
19714
+ return `event: ${event}\nid: ${String(head)}\ndata: ${JSON.stringify(data)}\n\n`;
19715
+ }
19716
+ /**
19717
+ * Tails the journal for open web streams: one poll every `POLL_MS` while any stream is open,
19718
+ * one `invalidate` per read batch, filtered per caller. Reads only through `db`, never inside
19719
+ * a transaction, so it sees committed rows only.
19720
+ */
19721
+ function createEventHub(options) {
19722
+ const subscribers = /* @__PURE__ */ new Set();
19723
+ let pending = 0;
19724
+ let closed = false;
19725
+ let closing;
19726
+ let cursor = 0;
19727
+ let pollTimer;
19728
+ let heartbeatTimer;
19729
+ let statusTimer;
19730
+ let polling;
19731
+ let statusRound;
19732
+ const isClosed = () => closed;
19733
+ const idle = () => closed || subscribers.size === 0;
19734
+ async function readHead() {
19735
+ return (await options.db.selectFrom("event").select(sql`max(id)`.as("head")).executeTakeFirst())?.head ?? 0;
19736
+ }
19737
+ function send(subscriber, chunk) {
19738
+ if (isClosed() || subscriber.done) return;
19739
+ if (subscriber.blocked) {
19740
+ subscriber.skipped = true;
19741
+ return;
19742
+ }
19743
+ if (subscriber.sink.write(chunk)) return;
19744
+ subscriber.blocked = true;
19745
+ subscriber.sink.once("drain", () => {
19746
+ subscriber.blocked = false;
19747
+ if (!subscriber.skipped) return;
19748
+ subscriber.skipped = false;
19749
+ send(subscriber, frame("reset", cursor, { head: cursor }));
19750
+ });
19751
+ }
19752
+ function deliver(rows) {
19753
+ const head = rows.at(-1)?.id ?? cursor;
19754
+ for (const subscriber of subscribers) {
19755
+ const projects = /* @__PURE__ */ new Set();
19756
+ const tasks = /* @__PURE__ */ new Set();
19757
+ for (const row of rows) {
19758
+ if (!subscriber.visible.has(row.project)) continue;
19759
+ projects.add(row.project);
19760
+ if (row.key !== null) tasks.add(row.key);
19761
+ }
19762
+ if (projects.size === 0) continue;
19763
+ send(subscriber, frame("invalidate", head, {
19764
+ head,
19765
+ projects: [...projects],
19766
+ tasks: [...tasks]
19767
+ }));
19768
+ }
19769
+ }
19770
+ async function poll() {
19771
+ while (!idle()) {
19772
+ let rows;
19773
+ try {
19774
+ rows = await options.db.selectFrom("event").leftJoin("task", "task.id", "event.task_id").select([
19775
+ "event.id as id",
19776
+ "event.project as project",
19777
+ "task.key as key"
19778
+ ]).where("event.id", ">", cursor).orderBy("event.id").limit(BATCH).execute();
19779
+ } catch (err) {
19780
+ options.onError?.({
19781
+ err,
19782
+ step: "poll"
19783
+ });
19784
+ return;
19785
+ }
19786
+ const last = rows.at(-1);
19787
+ if (last === void 0) return;
19788
+ cursor = Math.max(cursor, last.id);
19789
+ if (isClosed()) return;
19790
+ deliver(rows);
19791
+ if (rows.length < BATCH) return;
19792
+ }
19793
+ }
19794
+ function armPoll() {
19795
+ if (idle() || pollTimer !== void 0 || polling !== void 0) return;
19796
+ pollTimer = setTimeout(() => {
19797
+ pollTimer = void 0;
19798
+ polling = poll().finally(() => {
19799
+ polling = void 0;
19800
+ armPoll();
19801
+ });
19802
+ }, POLL_MS);
19803
+ }
19804
+ function armHeartbeat() {
19805
+ if (idle() || heartbeatTimer !== void 0) return;
19806
+ heartbeatTimer = setTimeout(() => {
19807
+ heartbeatTimer = void 0;
19808
+ for (const subscriber of subscribers) send(subscriber, ": heartbeat\n\n");
19809
+ armHeartbeat();
19810
+ }, HEARTBEAT_MS);
19811
+ }
19812
+ async function readStatuses() {
19813
+ const callers = new Set([...subscribers].map((subscriber) => subscriber.caller));
19814
+ for (const caller of callers) {
19815
+ if (idle()) return;
19816
+ let status;
19817
+ try {
19818
+ status = await options.readStatus(caller);
19819
+ } catch (err) {
19820
+ options.onError?.({
19821
+ err,
19822
+ step: "status"
19823
+ });
19824
+ continue;
19825
+ }
19826
+ const { warmingUp, spurUnavailable, hostLoad, transport, sources } = status;
19827
+ const chunk = `event: status\ndata: ${JSON.stringify({
19828
+ warmingUp,
19829
+ spurUnavailable,
19830
+ hostLoad,
19831
+ transport,
19832
+ sources
19833
+ })}\n\n`;
19834
+ for (const subscriber of subscribers) if (subscriber.caller === caller) send(subscriber, chunk);
19835
+ }
19836
+ }
19837
+ function armStatus() {
19838
+ if (idle() || statusTimer !== void 0 || statusRound !== void 0) return;
19839
+ statusTimer = setTimeout(() => {
19840
+ statusTimer = void 0;
19841
+ statusRound = readStatuses().finally(() => {
19842
+ statusRound = void 0;
19843
+ armStatus();
19844
+ });
19845
+ }, STATUS_MS);
19846
+ }
19847
+ function stopTimers() {
19848
+ clearTimeout(pollTimer);
19849
+ clearTimeout(heartbeatTimer);
19850
+ clearTimeout(statusTimer);
19851
+ pollTimer = heartbeatTimer = statusTimer = void 0;
19852
+ }
19853
+ async function shut(subscriber) {
19854
+ subscriber.done = true;
19855
+ if (subscriber.blocked) {
19856
+ await subscriber.sink.destroy();
19857
+ return;
19858
+ }
19859
+ let grace;
19860
+ const ended = await Promise.race([subscriber.sink.end().then(() => true, () => true), new Promise((resolve) => {
19861
+ grace = setTimeout(() => {
19862
+ resolve(false);
19863
+ }, END_GRACE_MS);
19864
+ })]);
19865
+ clearTimeout(grace);
19866
+ if (!ended) await subscriber.sink.destroy();
19867
+ }
19868
+ return {
19869
+ async subscribe(caller, lastId, sink) {
19870
+ if (isClosed() || subscribers.size + pending >= MAX_STREAMS) return "full";
19871
+ pending += 1;
19872
+ let head;
19873
+ try {
19874
+ head = await readHead();
19875
+ } finally {
19876
+ pending -= 1;
19877
+ }
19878
+ if (isClosed()) return "full";
19879
+ const subscriber = {
19880
+ caller,
19881
+ sink,
19882
+ visible: /* @__PURE__ */ new Set([...visibleProjects(options.config, caller), RESERVED_PROJECT]),
19883
+ blocked: false,
19884
+ skipped: false,
19885
+ done: false
19886
+ };
19887
+ const first = subscribers.size === 0;
19888
+ subscribers.add(subscriber);
19889
+ if (first) {
19890
+ cursor = Math.max(cursor, head);
19891
+ armPoll();
19892
+ armHeartbeat();
19893
+ armStatus();
19894
+ }
19895
+ send(subscriber, frame("hello", head, {
19896
+ head,
19897
+ instance: options.instance
19898
+ }));
19899
+ if (lastId !== void 0 && lastId !== "" && (!/^\d+$/.test(lastId) || Number(lastId) > head)) send(subscriber, frame("reset", head, { head }));
19900
+ return { unsubscribe() {
19901
+ subscriber.done = true;
19902
+ if (!subscribers.delete(subscriber)) return;
19903
+ if (subscribers.size === 0) stopTimers();
19904
+ } };
19905
+ },
19906
+ close() {
19907
+ closing ??= (async () => {
19908
+ closed = true;
19909
+ stopTimers();
19910
+ const open = [...subscribers];
19911
+ subscribers.clear();
19912
+ await Promise.all([
19913
+ ...open.map(shut),
19914
+ polling,
19915
+ statusRound
19916
+ ]);
19917
+ })();
19918
+ return closing;
19919
+ }
19920
+ };
19921
+ }
19922
+ /**
19923
+ * `GET /v1/events` on the web listener: an SSE stream fed by `hub`. The listener's `onRequest`
19924
+ * guard has already checked Host and fetch metadata; the route adds the Origin check.
19925
+ */
19926
+ function installEventStream(app, options) {
19927
+ app.get("/v1/events", { exposeHeadRoute: false }, async (request, reply) => {
19928
+ const browserOrigin = request.headers.origin;
19929
+ if (browserOrigin !== void 0 && browserOrigin !== options.origin()) throw new CommandError("forbidden", "Use the configured web origin.");
19930
+ if (!options.ready()) throw new CommandError(options.stopping?.() === true ? "stopping" : "starting", "Wait until the daemon is ready.");
19931
+ const raw = reply.raw;
19932
+ raw.once("close", () => {
19933
+ options.audit(request, reply);
19934
+ });
19935
+ const closed = new Promise((resolve) => {
19936
+ if (raw.destroyed) resolve();
19937
+ else raw.once("close", () => {
19938
+ resolve();
19939
+ });
19940
+ });
19941
+ const pass = new PassThrough();
19942
+ const writable = () => !pass.writableEnded && !pass.destroyed;
19943
+ const sink = {
19944
+ write: (chunk) => writable() ? pass.write(chunk) : true,
19945
+ end() {
19946
+ if (writable()) pass.end();
19947
+ return closed;
19948
+ },
19949
+ destroy() {
19950
+ raw.destroy();
19951
+ return closed;
19952
+ },
19953
+ once(event, listener) {
19954
+ pass.once(event, listener);
19955
+ }
19956
+ };
19957
+ const lastId = request.headers["last-event-id"];
19958
+ const subscription = await options.hub.subscribe("operator", typeof lastId === "string" ? lastId : void 0, sink);
19959
+ if (subscription === "full") return reply.code(503).header("retry-after", "5").type("text/plain; charset=utf-8").send("Too many open event streams: close a board tab or retry later.");
19960
+ if (raw.destroyed) subscription.unsubscribe();
19961
+ else raw.once("close", () => {
19962
+ subscription.unsubscribe();
19963
+ });
19964
+ return reply.header("content-type", "text/event-stream").header("cache-control", "no-cache").header("x-accel-buffering", "no").send(pass);
19965
+ });
19966
+ }
19967
+ //#endregion
19705
19968
  //#region ../core/src/api/web-server.ts
19706
19969
  const mime = {
19707
19970
  ".html": "text/html; charset=utf-8",
@@ -19754,10 +20017,13 @@ async function createWebServer(options) {
19754
20017
  }
19755
20018
  });
19756
20019
  const errorHandler = installOperationErrors(app, options);
20020
+ function resolvedOrigin() {
20021
+ const address = app.server.address();
20022
+ return resolveWebOrigin(options.config.web, address !== null && typeof address === "object" ? address.port : void 0);
20023
+ }
19757
20024
  function guard(request, reply) {
19758
20025
  reply.header("x-request-id", request.id);
19759
- const address = app.server.address();
19760
- const origin = resolveWebOrigin(options.config.web, address !== null && typeof address === "object" ? address.port : void 0);
20026
+ const origin = resolvedOrigin();
19761
20027
  if (origin === void 0 || request.headers.host !== new URL(origin).host) throw new CommandError("forbidden", "Use the configured web host.");
19762
20028
  if (request.headers["sec-fetch-site"] === "cross-site") throw new CommandError("forbidden", "Cross-site requests are not accepted.");
19763
20029
  if (request.method !== "GET" && request.method !== "HEAD" && request.headers.origin !== origin) throw new CommandError("forbidden", "Use the configured web origin.");
@@ -19777,7 +20043,10 @@ async function createWebServer(options) {
19777
20043
  reply.header("x-content-type-options", "nosniff");
19778
20044
  reply.header("referrer-policy", "no-referrer");
19779
20045
  }
20046
+ const audited = /* @__PURE__ */ new WeakSet();
19780
20047
  function audit(request, reply) {
20048
+ if (audited.has(request)) return;
20049
+ audited.add(request);
19781
20050
  const forwardedFor = request.headers["x-forwarded-for"];
19782
20051
  const userAgent = request.headers["user-agent"];
19783
20052
  options.logRequest({
@@ -19811,6 +20080,21 @@ async function createWebServer(options) {
19811
20080
  if (options.firstPollDone === void 0) throw new CommandError("not_found", "Health is unavailable.");
19812
20081
  return { firstPollDone: await options.firstPollDone() };
19813
20082
  });
20083
+ const hub = createEventHub({
20084
+ db: options.store.db,
20085
+ config: options.config,
20086
+ instance: options.instance ?? randomUUID(),
20087
+ readStatus: (caller) => dispatchOperation(options, "status.get", {}, caller),
20088
+ onError: options.logStreamError
20089
+ });
20090
+ installEventStream(app, {
20091
+ hub,
20092
+ ready: options.ready,
20093
+ stopping: options.stopping,
20094
+ origin: resolvedOrigin,
20095
+ audit
20096
+ });
20097
+ app.addHook("preClose", () => hub.close());
19814
20098
  app.setNotFoundHandler(async (request, reply) => {
19815
20099
  const path = request.url.split("?", 1)[0] ?? "/";
19816
20100
  if (request.method !== "GET" && request.method !== "HEAD" || path === "/v1" || path.startsWith("/v1/")) throw new CommandError("not_found", "This web route is not available.");
@@ -25186,6 +25470,7 @@ function createHttpModule(ctx, options = {}) {
25186
25470
  store: ctx.store,
25187
25471
  config: ctx.config,
25188
25472
  port: ctx.config.http.port,
25473
+ ...options.instance === void 0 ? {} : { instance: options.instance },
25189
25474
  ready: () => ctx.state() === "ready",
25190
25475
  stopping: () => ctx.state() === "stopping",
25191
25476
  clock: ctx.clock,
@@ -25263,7 +25548,14 @@ function createWebModule(ctx, options) {
25263
25548
  requestId,
25264
25549
  err
25265
25550
  }, "web request failed");
25266
- }
25551
+ },
25552
+ logStreamError: ({ err, step }) => {
25553
+ ctx.log.warn({
25554
+ err,
25555
+ step
25556
+ }, "event stream read failed");
25557
+ },
25558
+ ...options.instance === void 0 ? {} : { instance: options.instance }
25267
25559
  });
25268
25560
  if (aborted()) return;
25269
25561
  const address = await server.listen({
@@ -25646,9 +25938,11 @@ function createDaemonModules(ctxFor, ports = {}) {
25646
25938
  module: outbox
25647
25939
  });
25648
25940
  const runOperation = (id, input, run) => id === "item.retry" && inbound !== void 0 && isItemInput(input) ? inbound.retrying(input.item, run) : run();
25941
+ const instance = randomUUID();
25649
25942
  const web = board.config.web.port === void 0 ? void 0 : createWebModule(ctxFor("web"), {
25650
25943
  registry,
25651
25944
  runOperation,
25945
+ instance,
25652
25946
  firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
25653
25947
  ...ports.afterOperation === void 0 ? {} : { afterOperation: ports.afterOperation },
25654
25948
  ...ports.webRoot === void 0 ? {} : { webRoot: ports.webRoot },
@@ -25668,6 +25962,7 @@ function createDaemonModules(ctxFor, ports = {}) {
25668
25962
  module: createHttpModule(ctxFor("http"), {
25669
25963
  registry,
25670
25964
  runOperation,
25965
+ instance,
25671
25966
  webListening: () => web?.listening() === true,
25672
25967
  firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
25673
25968
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.79.0",
3
+ "version": "0.80.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"
@@ -15,13 +15,16 @@ web:
15
15
 
16
16
  The listener binds `127.0.0.1`. Configure a reverse proxy to preserve the original Host and
17
17
  use the exact resolved public origin. Every `{port}` is replaced with the actual listener port.
18
+ The browser gets live updates from `GET /v1/events`: turn proxy response buffering off for that
19
+ path (the stream sends `X-Accel-Buffering: no`, which nginx honours; other proxies need it
20
+ disabled) and keep the proxy read timeout above 15 seconds, the heartbeat interval.
18
21
  After restarting the daemon, run `board doctor --json`: `web` checks the configuration and
19
22
  `web.listening` checks whether the listener bound. A busy port leaves the agent API running;
20
23
  free it or choose another web port and restart.
21
24
 
22
- A missing UI build returns 503 with
25
+ The listener serves the packaged browser UI and its assets. A missing UI build returns 503 with
23
26
  ``UI is not built: run `pnpm --filter @spur-board/web build` ``.
24
- Run that build when the UI package is available. Health and catalog operations remain usable.
25
- The listener does not supply the SPA. Request logs record the web channel and untrusted
27
+ Run that build, then restart the daemon: it loads the assets at startup. Health and catalog
28
+ operations remain usable. Request logs record the web channel and untrusted
26
29
  forwarded client metadata and user agent. Journal events and history retain `via: web` beside
27
30
  the operator actor.
@@ -65,8 +65,12 @@ failed attempts while continuing recovery. The first valid stream handshake refr
65
65
  to close the startup read race; later changes to the stream head or instance also refresh it.
66
66
  Reconnects retain valid SSE cursors, including ID-only records, until the server clears them.
67
67
 
68
- The configured daemon web listener serves the packaged SPA and its local assets. The stream
69
- client connects with `GET /v1/events`, as specified by #533. That server remains pending, so
70
- the shell currently reports reconnecting then offline/stale while status reads and theme controls
71
- remain available. The footer version is `daemon.version` from `status.get`, so a stale bundle never
68
+ The configured daemon web listener serves the packaged SPA and its local assets, and streams
69
+ live updates from `GET /v1/events` as server-sent events. The stream opens with `hello` (journal
70
+ head and daemon instance), then sends one `invalidate` per committed batch of journal events,
71
+ naming the projects and task keys it touched; the shell then rereads its status. A `reset` asks for
72
+ a full reread: after a client fell behind, or when its last event ID is ahead of the journal.
73
+ A `status` frame every 30 seconds carries source and transport health; a comment line every 15
74
+ seconds keeps proxies from closing the stream. A restarted daemon sends a new instance in
75
+ `hello`, which also makes the shell reread everything. The footer version is `daemon.version` from `status.get`, so a stale bundle never
72
76
  claims the daemon's version; it stays empty until the first status read.