spur-board 0.47.0 → 0.47.1

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.
Files changed (2) hide show
  1. package/dist/daemon.mjs +253 -37
  2. package/package.json +1 -1
package/dist/daemon.mjs CHANGED
@@ -15,6 +15,7 @@ import perf_hooks from "node:perf_hooks";
15
15
  import Fastify from "fastify";
16
16
  import { pino } from "pino";
17
17
  import { WebAPIHTTPError, WebAPIPlatformError, WebAPIRateLimitedError, WebClient } from "@slack/web-api";
18
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
18
19
  import { SocketModeClient } from "@slack/socket-mode";
19
20
  //#region \0rolldown/runtime.js
20
21
  var __create = Object.create;
@@ -9591,7 +9592,8 @@ async function createApiServer(options) {
9591
9592
  const body = inputBody(request.body);
9592
9593
  const parsed = operation.input.safeParse(body.input);
9593
9594
  if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
9594
- const result = await dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
9595
+ const dispatch = () => dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
9596
+ const result = await (options.runOperation === void 0 ? dispatch() : options.runOperation(operation.id, parsed.data, dispatch));
9595
9597
  await options.afterOperation?.(reply.raw);
9596
9598
  return reply.send(successEnvelopeSchema.parse({
9597
9599
  ok: true,
@@ -15677,6 +15679,25 @@ async function skip(trx, input) {
15677
15679
  });
15678
15680
  return { status: "ignored" };
15679
15681
  }
15682
+ /**
15683
+ * The journal is the comment's edit cursor: a deletion, or a later edit, was already applied.
15684
+ * Times compare in milliseconds, since `at` precision varies. Distinct edits can share a
15685
+ * millisecond, so an edit at the same millisecond counts as applied only when the comment
15686
+ * already holds its text.
15687
+ */
15688
+ async function alreadyApplied(trx, event) {
15689
+ if (event.kind !== "message_edited" && event.kind !== "message_deleted") return false;
15690
+ const comment = await linkedComment(trx, event);
15691
+ if (comment === void 0 || comment.author !== "operator") return false;
15692
+ const rows = await trx.selectFrom("event").select(["kind", "at"]).where("task_id", "=", comment.task_id).where("kind", "in", ["comment_deleted", "comment_edited"]).where(sql`json_extract(payload, '$.comment')`, "=", `C${String(comment.id)}`).execute();
15693
+ if (rows.some((row) => row.kind === "comment_deleted")) return true;
15694
+ if (event.kind === "message_deleted") return false;
15695
+ const editedAt = Date.parse(event.at);
15696
+ return rows.some((row) => {
15697
+ const rowAt = Date.parse(row.at);
15698
+ return rowAt > editedAt || rowAt === editedAt && comment.text === event.text;
15699
+ });
15700
+ }
15680
15701
  async function linkedComment(trx, event) {
15681
15702
  return trx.selectFrom("comment").selectAll().where("conversation_ref", "=", event.conversation).where("message_ref", "=", event.message).executeTakeFirst();
15682
15703
  }
@@ -15713,11 +15734,20 @@ async function ringAuthor(trx, input) {
15713
15734
  retry: false
15714
15735
  });
15715
15736
  }
15737
+ function first(set) {
15738
+ for (const value of set) return value;
15739
+ }
15716
15740
  function createInbound(input) {
15717
15741
  const { store, gateway, config } = input;
15718
15742
  const clock = input.clock ?? { now: () => Date.now() };
15719
15743
  const registry = input.registry ?? {};
15720
15744
  let running = Promise.resolve();
15745
+ const stopping = new AbortController();
15746
+ const stopped = () => stopping.signal.aborted;
15747
+ /** Conversations the current or stopped scan selected and has not read yet. */
15748
+ const pending = /* @__PURE__ */ new Set();
15749
+ let since = new Date(clock.now());
15750
+ let scan;
15721
15751
  async function sourceContext(trx, event, at) {
15722
15752
  if (!("conversation" in event)) return void 0;
15723
15753
  const resolved = await resolveBlockConversation(trx, {
@@ -15739,6 +15769,7 @@ function createInbound(input) {
15739
15769
  return resolved?.conversation;
15740
15770
  }
15741
15771
  async function processMessage(trx, event, at) {
15772
+ if (await alreadyApplied(trx, event)) return void 0;
15742
15773
  const conversation = await sourceContext(trx, event, at);
15743
15774
  if (conversation?.block_id === null || conversation === void 0) return skip(trx, {
15744
15775
  event,
@@ -16107,41 +16138,174 @@ function createInbound(input) {
16107
16138
  });
16108
16139
  }
16109
16140
  async function applyEvent(event) {
16110
- if (event.kind === "connection") {
16111
- if (event.state === "up") await scan();
16112
- return;
16113
- }
16114
16141
  if (event.kind === "gap") return applyGap(event);
16115
16142
  return applyUser(event);
16116
16143
  }
16117
- async function scan() {
16118
- const selected = await conversationsForRecovery(store.db, gateway.kind, new Date(clock.now()));
16119
- const conversations = selected.rows.map((row) => ({
16120
- ref: conversationRefSchema.parse(row.ref),
16121
- ...row.after_message_ref === null ? {} : { after: messageRefSchema.parse(row.after_message_ref) }
16122
- }));
16144
+ /** Reads one conversation, or none to let a history-less gateway report its gap. */
16145
+ async function readSlice(ref) {
16146
+ let conversations = [];
16147
+ if (ref !== void 0) {
16148
+ const row = await store.db.selectFrom("conversation").select("after_message_ref").where("gateway", "=", gateway.kind).where("ref", "=", ref).executeTakeFirst();
16149
+ if (row === void 0) return;
16150
+ conversations = [{
16151
+ ref: conversationRefSchema.parse(ref),
16152
+ ...row.after_message_ref === null ? {} : { after: messageRefSchema.parse(row.after_message_ref) }
16153
+ }];
16154
+ }
16123
16155
  for await (const event of gateway.recover({
16124
16156
  conversations,
16125
- since: selected.since
16126
- })) await applyEvent(event);
16157
+ since,
16158
+ signal: stopping.signal
16159
+ })) {
16160
+ if (stopped()) return;
16161
+ if (event.kind === "connection") continue;
16162
+ await applyEvent(event);
16163
+ }
16164
+ }
16165
+ /** Reads `ref` now when the scan has not read it yet; a stopped scan leaves it unread. */
16166
+ async function sliceIfPending(ref) {
16167
+ if (!pending.has(ref) || stopped()) return;
16168
+ try {
16169
+ await readSlice(ref);
16170
+ } catch (error) {
16171
+ pending.delete(ref);
16172
+ throw error;
16173
+ }
16174
+ if (!stopped()) pending.delete(ref);
16175
+ }
16176
+ /**
16177
+ * Adds the selected conversations to `pending`. A selection merged into a running scan reads
16178
+ * from the earliest `since` of its selections, so no selection's window shrinks.
16179
+ */
16180
+ async function select(state) {
16181
+ if (scan !== state) return;
16182
+ const selected = await conversationsForRecovery(store.db, gateway.kind, new Date(clock.now()));
16183
+ since = state.selected && since.getTime() < selected.since.getTime() ? since : selected.since;
16184
+ state.selected = true;
16185
+ for (const row of selected.rows) pending.add(row.ref);
16186
+ if (selected.rows.length === 0) state.readEmpty = true;
16187
+ }
16188
+ /**
16189
+ * One slot per conversation, so live events run between slices, until `pending` is empty.
16190
+ * The scan ends where this decides to stop, in the same microtask, so a later request starts
16191
+ * a fresh scan instead of joining one that will not read again.
16192
+ */
16193
+ async function drain(state) {
16194
+ const end = () => {
16195
+ if (scan === state) scan = void 0;
16196
+ };
16197
+ try {
16198
+ for (;;) {
16199
+ const selection = state.selection;
16200
+ await selection;
16201
+ for (let ref = first(pending); ref !== void 0 && !stopped(); ref = first(pending)) {
16202
+ const next = ref;
16203
+ await serial(() => sliceIfPending(next));
16204
+ }
16205
+ if (state.readEmpty && !stopped()) {
16206
+ state.readEmpty = false;
16207
+ await serial(() => readSlice(void 0));
16208
+ }
16209
+ if (stopped() || state.selection === selection) {
16210
+ end();
16211
+ return;
16212
+ }
16213
+ }
16214
+ } catch (error) {
16215
+ end();
16216
+ pending.clear();
16217
+ throw error;
16218
+ }
16219
+ }
16220
+ /**
16221
+ * A request during a scan queues its selection at once, so later live events wait for it;
16222
+ * every caller waits until the merged selections are read.
16223
+ */
16224
+ function requestScan() {
16225
+ if (stopped()) return Promise.resolve();
16226
+ if (scan !== void 0) {
16227
+ queueSelection(scan);
16228
+ return scan.promise;
16229
+ }
16230
+ const state = {
16231
+ selected: false,
16232
+ readEmpty: false,
16233
+ selection: Promise.resolve(),
16234
+ promise: Promise.resolve()
16235
+ };
16236
+ scan = state;
16237
+ queueSelection(state);
16238
+ state.promise = drain(state);
16239
+ return state.promise;
16240
+ }
16241
+ function queueSelection(state) {
16242
+ const queued = serial(() => select(state));
16243
+ state.selection = state.selection.then(() => queued);
16244
+ state.selection.catch(() => void 0);
16245
+ }
16246
+ /** The conversation of the event an item stored for retry, if it has one. */
16247
+ async function storedConversation(itemId) {
16248
+ if (pending.size === 0) return void 0;
16249
+ const item = await store.db.selectFrom("operator_item").select("inbound_event_json").where("id", "=", itemId).executeTakeFirst();
16250
+ if (item?.inbound_event_json == null) return void 0;
16251
+ const stored = inboundEventSchema.safeParse(JSON.parse(item.inbound_event_json));
16252
+ return stored.success && "conversation" in stored.data ? stored.data.conversation : void 0;
16253
+ }
16254
+ /** The item a feed Retry button re-applies, so its stored event's thread is read first. */
16255
+ function retriedItem(event) {
16256
+ if (event.kind !== "action") return void 0;
16257
+ const { id, item } = interactionOperation(event);
16258
+ return id === "item.retry" && item !== void 0 ? Number(item.slice(1)) : void 0;
16259
+ }
16260
+ /** Reads `ref`'s unread history, or raises its gap once the scan stopped. */
16261
+ async function readPending(ref) {
16262
+ if (ref === void 0 || !pending.has(ref)) return;
16263
+ if (!stopped()) return sliceIfPending(ref);
16264
+ pending.delete(ref);
16265
+ await applyGap({
16266
+ kind: "gap",
16267
+ dedupeKey: `inbound:stopped-scan:${randomUUID()}`,
16268
+ conversation: conversationRefSchema.parse(ref)
16269
+ });
16270
+ }
16271
+ /**
16272
+ * Before a live event: its conversation's unread history, and for a Retry button the stored
16273
+ * event's, since re-applying that event can move its conversation's cursor.
16274
+ */
16275
+ async function beforeLive(event) {
16276
+ await readPending("conversation" in event ? event.conversation : void 0);
16277
+ const itemId = retriedItem(event);
16278
+ if (itemId !== void 0) await readPending(await storedConversation(itemId));
16127
16279
  }
16128
16280
  function serial(work) {
16129
16281
  const next = running.then(work);
16130
- running = next.catch(() => void 0);
16282
+ running = next.then(() => void 0, () => void 0);
16131
16283
  return next;
16132
16284
  }
16133
16285
  return {
16134
16286
  sink(event) {
16135
- return serial(() => applyEvent(event));
16287
+ if (event.kind === "connection") return event.state === "up" ? requestScan() : Promise.resolve();
16288
+ return serial(async () => {
16289
+ await beforeLive(event);
16290
+ await applyEvent(event);
16291
+ });
16136
16292
  },
16137
- recover() {
16138
- return serial(scan);
16293
+ recover: requestScan,
16294
+ async stop() {
16295
+ stopping.abort();
16296
+ await scan?.promise.catch(() => void 0);
16297
+ await running;
16139
16298
  },
16140
- stop() {
16141
- return running;
16299
+ retrying(item, run) {
16300
+ return serial(async () => {
16301
+ const itemId = /^I[1-9]\d*$/.test(item) ? Number(item.slice(1)) : void 0;
16302
+ if (itemId !== void 0) await readPending(await storedConversation(itemId));
16303
+ return run();
16304
+ });
16142
16305
  },
16143
16306
  retryStored(itemId) {
16144
16307
  return serial(async () => {
16308
+ await readPending(await storedConversation(itemId));
16145
16309
  const at = new Date(clock.now()).toISOString();
16146
16310
  await scanTransaction(store, config, async (trx) => {
16147
16311
  await reapply(trx, itemId, at);
@@ -18684,7 +18848,7 @@ function runSource(entry, options, runnerStartMs) {
18684
18848
  }
18685
18849
  const requested = [...context.observe.prs, ...context.observe.tickets];
18686
18850
  step = "poll";
18687
- const batch = await untilAborted(adapter.poll({
18851
+ const batch = await untilAborted$1(adapter.poll({
18688
18852
  ...context,
18689
18853
  signal: abort.signal
18690
18854
  }), abort.signal);
@@ -18797,13 +18961,13 @@ function runSource(entry, options, runnerStartMs) {
18797
18961
  const aborted = () => abort.signal.aborted;
18798
18962
  let step = "context";
18799
18963
  try {
18800
- const received = await untilAborted(core.context(source), abort.signal);
18964
+ const received = await untilAborted$1(core.context(source), abort.signal);
18801
18965
  if (aborted() || received === void 0) return err(stoppedError);
18802
18966
  const own = ({ ref: held }) => held.number === ref.number && held.repo.toLowerCase() === ref.repo.toLowerCase();
18803
18967
  const feedbackCursors = received.feedbackCursors?.filter(own) ?? [];
18804
18968
  const continuations = received.continuations?.filter(own) ?? [];
18805
18969
  step = "poll";
18806
- const batch = await untilAborted(adapter.pollPr(ref, {
18970
+ const batch = await untilAborted$1(adapter.pollPr(ref, {
18807
18971
  signal: abort.signal,
18808
18972
  ...feedbackCursors.length === 0 ? {} : { feedbackCursors },
18809
18973
  ...continuations.length === 0 ? {} : { continuations }
@@ -18940,7 +19104,7 @@ function demandValue(batch, observedAt) {
18940
19104
  * for an adapter that ignores its signal. A late result or rejection is dropped. The abort
18941
19105
  * listener is removed once either side settles, so a retained signal holds nothing.
18942
19106
  */
18943
- function untilAborted(work, signal) {
19107
+ function untilAborted$1(work, signal) {
18944
19108
  let settle = () => void 0;
18945
19109
  const abortion = new Promise((resolve) => {
18946
19110
  settle = resolve;
@@ -19314,7 +19478,10 @@ var IncompleteHistoryError = class extends Error {};
19314
19478
  function messageTs$1(message) {
19315
19479
  return typeof message === "object" && message !== null && "ts" in message && typeof message.ts === "string" ? message.ts : void 0;
19316
19480
  }
19317
- /** Read every page. An incomplete response is unknown, never an empty history. */
19481
+ /**
19482
+ * Read every page. An incomplete response is unknown, never an empty history. Once `signal`
19483
+ * aborts, no further page is requested.
19484
+ */
19318
19485
  async function readMessages(client, query) {
19319
19486
  const found = [];
19320
19487
  const seen = /* @__PURE__ */ new Set();
@@ -19345,6 +19512,7 @@ async function readMessages(client, query) {
19345
19512
  if (seen.has(key)) throw new IncompleteHistoryError("repeated cursor");
19346
19513
  seen.add(key);
19347
19514
  cursor = nextCursor;
19515
+ if (query.signal?.aborted === true) throw new IncompleteHistoryError("read aborted");
19348
19516
  continue;
19349
19517
  }
19350
19518
  if (!page.has_more) return found;
@@ -19355,6 +19523,7 @@ async function readMessages(client, query) {
19355
19523
  seen.add(key);
19356
19524
  cursor = void 0;
19357
19525
  latest = lastTs;
19526
+ if (query.signal?.aborted === true) throw new IncompleteHistoryError("read aborted");
19358
19527
  }
19359
19528
  }
19360
19529
  const DEFAULT_TIMEOUT_MS = 1e4;
@@ -20107,16 +20276,52 @@ function inInterval(ts, from, until) {
20107
20276
  const at = tsMillis(ts);
20108
20277
  return Number.isFinite(at) && at >= from && at <= until;
20109
20278
  }
20110
- async function readThread(client, channel, threadTs) {
20111
- for (;;) try {
20112
- return await readMessages(client, {
20113
- channel,
20114
- threadTs
20115
- });
20116
- } catch (error) {
20117
- const result = apiFailure(error);
20118
- if (result.status !== "retry" || result.uncertain) throw error;
20119
- await new Promise((resolve) => setTimeout(resolve, result.afterMs ?? 1e3));
20279
+ /** Total time one thread read may spend waiting on rate limits before it becomes a `gap`. */
20280
+ const READ_WAIT_BUDGET_MS = 1e4;
20281
+ /** Least budget one retry costs, so a `Retry-After: 0` cannot retry forever. */
20282
+ const MIN_RETRY_CHARGE_MS = 1e3;
20283
+ const ABORTED = Symbol("aborted");
20284
+ /**
20285
+ * Settles with `promise`, or with `ABORTED` once `signal` aborts. The SDK call cannot be
20286
+ * cancelled, so a losing read is left to its own timeout and its outcome is dropped.
20287
+ */
20288
+ function untilAborted(promise, signal) {
20289
+ if (signal === void 0) return promise;
20290
+ promise.catch(() => {});
20291
+ if (signal.aborted) return Promise.resolve(ABORTED);
20292
+ const abort = Promise.withResolvers();
20293
+ const onAbort = () => {
20294
+ abort.resolve(ABORTED);
20295
+ };
20296
+ signal.addEventListener("abort", onAbort, { once: true });
20297
+ return Promise.race([promise, abort.promise]).finally(() => {
20298
+ signal.removeEventListener("abort", onAbort);
20299
+ });
20300
+ }
20301
+ /**
20302
+ * Waits out rate limits within `READ_WAIT_BUDGET_MS`, each retry costing at least
20303
+ * `MIN_RETRY_CHARGE_MS`; a wait past what remains throws
20304
+ * `IncompleteHistoryError` without sleeping. Returns `ABORTED` once `signal` aborts.
20305
+ */
20306
+ async function readThread(client, channel, threadTs, signal) {
20307
+ let budget = READ_WAIT_BUDGET_MS;
20308
+ for (;;) {
20309
+ if (signal?.aborted === true) return ABORTED;
20310
+ try {
20311
+ return await untilAborted(readMessages(client, {
20312
+ channel,
20313
+ threadTs,
20314
+ signal
20315
+ }), signal);
20316
+ } catch (error) {
20317
+ const result = apiFailure(error);
20318
+ if (result.status !== "retry" || result.uncertain) throw error;
20319
+ const wait = result.afterMs ?? 1e3;
20320
+ const charge = Math.max(wait, MIN_RETRY_CHARGE_MS);
20321
+ if (charge > budget) throw new IncompleteHistoryError("rate limit wait exceeds the read budget");
20322
+ budget -= charge;
20323
+ await setTimeout$1(wait, void 0, { signal }).catch(() => void 0);
20324
+ }
20120
20325
  }
20121
20326
  }
20122
20327
  function gap(conversation) {
@@ -20131,8 +20336,11 @@ async function* recoverThreads(client, request, botIdentity, now) {
20131
20336
  const until = now();
20132
20337
  const from = request.since.getTime();
20133
20338
  if (!Number.isFinite(from) || from > until) return;
20134
- const bot = await botIdentity();
20339
+ const signal = request.signal;
20340
+ const bot = await untilAborted(botIdentity(), signal);
20341
+ if (bot === ABORTED) return;
20135
20342
  for (const conversation of request.conversations) {
20343
+ if (signal?.aborted === true) return;
20136
20344
  const addressed = parseRef(conversation.ref);
20137
20345
  if (addressed === null) {
20138
20346
  yield gap(conversation.ref);
@@ -20140,7 +20348,7 @@ async function* recoverThreads(client, request, botIdentity, now) {
20140
20348
  }
20141
20349
  let history;
20142
20350
  try {
20143
- history = await readThread(client, addressed.channel, addressed.threadTs);
20351
+ history = await readThread(client, addressed.channel, addressed.threadTs, signal);
20144
20352
  } catch (error) {
20145
20353
  const result = apiFailure(error);
20146
20354
  if (error instanceof IncompleteHistoryError || result.status === "failed") {
@@ -20149,6 +20357,7 @@ async function* recoverThreads(client, request, botIdentity, now) {
20149
20357
  }
20150
20358
  throw error;
20151
20359
  }
20360
+ if (history === ABORTED) return;
20152
20361
  const root = history.find((message) => string(record(message)?.ts) === addressed.threadTs);
20153
20362
  if (root === void 0) {
20154
20363
  yield gap(conversation.ref);
@@ -20943,6 +21152,7 @@ function createHttpModule(ctx, options = {}) {
20943
21152
  verifyToken: (token) => verifyOperatorToken(ctx.store, token),
20944
21153
  registry: options.registry ?? {},
20945
21154
  ...options.afterOperation === void 0 ? {} : { afterOperation: options.afterOperation },
21155
+ ...options.runOperation === void 0 ? {} : { runOperation: options.runOperation },
20946
21156
  doctor: options.doctor ?? (() => runDaemonDoctor(ctx, options.productVersion ?? "unknown", options.fetcher)),
20947
21157
  ...options.firstPollDone === void 0 ? {} : { firstPollDone: options.firstPollDone },
20948
21158
  logRequest: ({ requestId, method, url, status, tokenName }) => {
@@ -21002,11 +21212,13 @@ function createInboundModule(ctx, gateway, registry = {}) {
21002
21212
  return {
21003
21213
  sink: (event) => inbound.sink(event),
21004
21214
  reapply: inbound.reapply,
21215
+ retrying: (item, run) => inbound.retrying(item, run),
21005
21216
  awaitRecovery: () => recovery.settled(),
21006
21217
  start: (signal) => recovery.start(signal),
21007
21218
  async stop() {
21219
+ const draining = inbound.stop();
21008
21220
  await recovery.stop();
21009
- await inbound.stop();
21221
+ await draining;
21010
21222
  }
21011
21223
  };
21012
21224
  }
@@ -21326,6 +21538,7 @@ function createDaemonModules(ctxFor, ports = {}) {
21326
21538
  stopStage: "final",
21327
21539
  module: createHttpModule(ctxFor("http"), {
21328
21540
  registry,
21541
+ runOperation: (id, input, run) => id === "item.retry" && inbound !== void 0 && isItemInput(input) ? inbound.retrying(input.item, run) : run(),
21329
21542
  firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
21330
21543
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
21331
21544
  ...ports.sessionFetcher === void 0 ? {} : { fetcher: ports.sessionFetcher },
@@ -21345,6 +21558,9 @@ function createDaemonModules(ctxFor, ports = {}) {
21345
21558
  tick: boardModules.tick
21346
21559
  };
21347
21560
  }
21561
+ function isItemInput(input) {
21562
+ return typeof input === "object" && input !== null && "item" in input && typeof input.item === "string";
21563
+ }
21348
21564
  //#endregion
21349
21565
  //#region ../daemon/src/main.ts
21350
21566
  const KEEPALIVE_MS = 36e5;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.47.0",
3
+ "version": "0.47.1",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"