@leitwerk-dev/watcher-utils 0.1.9 → 0.2.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.
@@ -3,6 +3,14 @@ import {
3
3
  } from "./chunk-IU3L35PC.js";
4
4
 
5
5
  // src/poll-loop.ts
6
+ function createPollSchedule(now = () => Date.now()) {
7
+ const dueAt = /* @__PURE__ */ new Map();
8
+ return (key, interval = "30s", timestamp = now()) => {
9
+ if ((dueAt.get(key) ?? 0) > timestamp) return false;
10
+ dueAt.set(key, timestamp + parseDurationMs(interval, 3e4));
11
+ return true;
12
+ };
13
+ }
6
14
  function emptyPollResult() {
7
15
  return {
8
16
  created: [],
@@ -30,8 +38,12 @@ function createPollLoop(opts) {
30
38
  pollInFlight = running;
31
39
  return running;
32
40
  }
33
- function pollAndIgnoreUnhandledRejection() {
34
- void poll().catch(() => void 0);
41
+ function pollScheduled() {
42
+ const startedAt = Date.now();
43
+ void poll().then(
44
+ (result) => opts.onScheduledResult(result, Date.now() - startedAt),
45
+ (error) => opts.onScheduledError(error, Date.now() - startedAt)
46
+ );
35
47
  }
36
48
  return {
37
49
  poll,
@@ -43,8 +55,8 @@ function createPollLoop(opts) {
43
55
  return;
44
56
  }
45
57
  const ms = parseDurationMs(opts.pollInterval(), defaultMs);
46
- timer = setInterval(pollAndIgnoreUnhandledRejection, ms);
47
- pollAndIgnoreUnhandledRejection();
58
+ timer = setInterval(pollScheduled, ms);
59
+ pollScheduled();
48
60
  },
49
61
  stop() {
50
62
  if (!timer) {
@@ -57,7 +69,8 @@ function createPollLoop(opts) {
57
69
  }
58
70
 
59
71
  export {
72
+ createPollSchedule,
60
73
  emptyPollResult,
61
74
  createPollLoop
62
75
  };
63
- //# sourceMappingURL=chunk-XF2QQLPO.js.map
76
+ //# sourceMappingURL=chunk-HG5TEBHZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/poll-loop.ts"],"sourcesContent":["import { parseDurationMs } from \"./duration-parse.js\";\n\n/** Reserve the next poll time for a caller-owned key, before starting its work. */\nexport function createPollSchedule(now: () => number = () => Date.now()) {\n\tconst dueAt = new Map<string, number>();\n\treturn (key: string, interval = \"30s\", timestamp = now()): boolean => {\n\t\tif ((dueAt.get(key) ?? 0) > timestamp) return false;\n\t\tdueAt.set(key, timestamp + parseDurationMs(interval, 30_000));\n\t\treturn true;\n\t};\n}\n\nexport interface PollResult {\n\tcreated: string[];\n\taborted: string[];\n\tlabelExchanged: string[];\n\tskipped: string[];\n\terrors: string[];\n}\n\nexport function emptyPollResult(): PollResult {\n\treturn {\n\t\tcreated: [],\n\t\taborted: [],\n\t\tlabelExchanged: [],\n\t\tskipped: [],\n\t\terrors: [],\n\t};\n}\n\nexport interface PollResultWithErrors {\n\treadonly errors: readonly string[];\n}\n\nexport interface PollLoop<T extends PollResultWithErrors = PollResult> {\n\tpoll(): Promise<T>;\n\tstart(): void;\n\tstop(): void;\n}\n\n/**\n * Create a non-overlapping polling loop. `pollOnce` is the actual work;\n * concurrent calls to `poll()` coalesce into the in-flight promise.\n */\nexport function createPollLoop<T extends PollResultWithErrors>(opts: {\n\tpollOnce: () => Promise<T>;\n\tisEnabled: () => boolean;\n\tpollInterval: () => string;\n\tdefaultIntervalMs?: number;\n\tonScheduledResult: (result: T, durationMs: number) => void;\n\tonScheduledError: (error: unknown, durationMs: number) => void;\n}): PollLoop<T> {\n\tlet timer: ReturnType<typeof setInterval> | null = null;\n\tlet pollInFlight: Promise<T> | null = null;\n\tconst defaultMs = opts.defaultIntervalMs ?? 60_000;\n\n\tasync function poll(): Promise<T> {\n\t\tif (pollInFlight) {\n\t\t\treturn pollInFlight;\n\t\t}\n\t\tconst running = (async () => {\n\t\t\ttry {\n\t\t\t\treturn await opts.pollOnce();\n\t\t\t} finally {\n\t\t\t\tpollInFlight = null;\n\t\t\t}\n\t\t})();\n\t\tpollInFlight = running;\n\t\treturn running;\n\t}\n\n\tfunction pollScheduled(): void {\n\t\tconst startedAt = Date.now();\n\t\tvoid poll().then(\n\t\t\t(result) => opts.onScheduledResult(result, Date.now() - startedAt),\n\t\t\t(error: unknown) => opts.onScheduledError(error, Date.now() - startedAt),\n\t\t);\n\t}\n\n\treturn {\n\t\tpoll,\n\t\tstart() {\n\t\t\tif (timer) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!opts.isEnabled()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst ms = parseDurationMs(opts.pollInterval(), defaultMs);\n\t\t\ttimer = setInterval(pollScheduled, ms);\n\t\t\tpollScheduled();\n\t\t},\n\t\tstop() {\n\t\t\tif (!timer) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearInterval(timer);\n\t\t\ttimer = null;\n\t\t},\n\t};\n}\n"],"mappings":";;;;;AAGO,SAAS,mBAAmB,MAAoB,MAAM,KAAK,IAAI,GAAG;AACxE,QAAM,QAAQ,oBAAI,IAAoB;AACtC,SAAO,CAAC,KAAa,WAAW,OAAO,YAAY,IAAI,MAAe;AACrE,SAAK,MAAM,IAAI,GAAG,KAAK,KAAK,UAAW,QAAO;AAC9C,UAAM,IAAI,KAAK,YAAY,gBAAgB,UAAU,GAAM,CAAC;AAC5D,WAAO;AAAA,EACR;AACD;AAUO,SAAS,kBAA8B;AAC7C,SAAO;AAAA,IACN,SAAS,CAAC;AAAA,IACV,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,SAAS,CAAC;AAAA,IACV,QAAQ,CAAC;AAAA,EACV;AACD;AAgBO,SAAS,eAA+C,MAO/C;AACf,MAAI,QAA+C;AACnD,MAAI,eAAkC;AACtC,QAAM,YAAY,KAAK,qBAAqB;AAE5C,iBAAe,OAAmB;AACjC,QAAI,cAAc;AACjB,aAAO;AAAA,IACR;AACA,UAAM,WAAW,YAAY;AAC5B,UAAI;AACH,eAAO,MAAM,KAAK,SAAS;AAAA,MAC5B,UAAE;AACD,uBAAe;AAAA,MAChB;AAAA,IACD,GAAG;AACH,mBAAe;AACf,WAAO;AAAA,EACR;AAEA,WAAS,gBAAsB;AAC9B,UAAM,YAAY,KAAK,IAAI;AAC3B,SAAK,KAAK,EAAE;AAAA,MACX,CAAC,WAAW,KAAK,kBAAkB,QAAQ,KAAK,IAAI,IAAI,SAAS;AAAA,MACjE,CAAC,UAAmB,KAAK,iBAAiB,OAAO,KAAK,IAAI,IAAI,SAAS;AAAA,IACxE;AAAA,EACD;AAEA,SAAO;AAAA,IACN;AAAA,IACA,QAAQ;AACP,UAAI,OAAO;AACV;AAAA,MACD;AACA,UAAI,CAAC,KAAK,UAAU,GAAG;AACtB;AAAA,MACD;AACA,YAAM,KAAK,gBAAgB,KAAK,aAAa,GAAG,SAAS;AACzD,cAAQ,YAAY,eAAe,EAAE;AACrC,oBAAc;AAAA,IACf;AAAA,IACA,OAAO;AACN,UAAI,CAAC,OAAO;AACX;AAAA,MACD;AACA,oBAAc,KAAK;AACnB,cAAQ;AAAA,IACT;AAAA,EACD;AACD;","names":[]}
@@ -0,0 +1,44 @@
1
+ import {
2
+ createPollLoop
3
+ } from "./chunk-HG5TEBHZ.js";
4
+
5
+ // src/polling-coordinator.ts
6
+ function createPollingCoordinator(logger) {
7
+ const loops = /* @__PURE__ */ new Map();
8
+ let sealed = false;
9
+ return {
10
+ create(registration) {
11
+ const id = registration.id.trim();
12
+ if (!id) throw new Error("Polling registration id must not be empty");
13
+ if (sealed) throw new Error(`Cannot register poller '${id}' after polling has started`);
14
+ if (loops.has(id)) throw new Error(`Duplicate poller '${id}'`);
15
+ const loop = createPollLoop({
16
+ pollOnce: registration.pollOnce,
17
+ isEnabled: registration.isEnabled,
18
+ pollInterval: registration.pollInterval,
19
+ defaultIntervalMs: registration.defaultIntervalMs,
20
+ onScheduledResult(result, durationMs) {
21
+ if (result.errors.length === 0) return;
22
+ logger.warn({ pollerId: id, durationMs, result }, "Poll completed with errors");
23
+ },
24
+ onScheduledError(error, durationMs) {
25
+ logger.error({ pollerId: id, durationMs, err: error }, "Poll failed");
26
+ }
27
+ });
28
+ loops.set(id, loop);
29
+ return { poll: loop.poll };
30
+ },
31
+ start() {
32
+ sealed = true;
33
+ for (const loop of loops.values()) loop.start();
34
+ },
35
+ stop() {
36
+ for (const loop of loops.values()) loop.stop();
37
+ }
38
+ };
39
+ }
40
+
41
+ export {
42
+ createPollingCoordinator
43
+ };
44
+ //# sourceMappingURL=chunk-USTHXEZJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/polling-coordinator.ts"],"sourcesContent":["import { createPollLoop, type PollResult, type PollResultWithErrors } from \"./poll-loop.js\";\n\nexport interface PollingLogger {\n\twarn(payload: Record<string, unknown>, message?: string): void;\n\terror(payload: Record<string, unknown>, message?: string): void;\n}\n\nexport interface PollingRegistration<T extends PollResultWithErrors> {\n\tid: string;\n\tpollOnce(): Promise<T>;\n\tisEnabled(): boolean;\n\tpollInterval(): string;\n\tdefaultIntervalMs?: number;\n}\n\nexport interface RegisteredPoller<T extends PollResultWithErrors = PollResult> {\n\tpoll(): Promise<T>;\n}\n\nexport interface PollingCoordinator {\n\tcreate<T extends PollResultWithErrors>(registration: PollingRegistration<T>): RegisteredPoller<T>;\n\tstart(): void;\n\tstop(): void;\n}\n\nexport function createPollingCoordinator(logger: PollingLogger): PollingCoordinator {\n\tconst loops = new Map<string, ReturnType<typeof createPollLoop>>();\n\tlet sealed = false;\n\n\treturn {\n\t\tcreate<T extends PollResultWithErrors>(\n\t\t\tregistration: PollingRegistration<T>,\n\t\t): RegisteredPoller<T> {\n\t\t\tconst id = registration.id.trim();\n\t\t\tif (!id) throw new Error(\"Polling registration id must not be empty\");\n\t\t\tif (sealed) throw new Error(`Cannot register poller '${id}' after polling has started`);\n\t\t\tif (loops.has(id)) throw new Error(`Duplicate poller '${id}'`);\n\n\t\t\tconst loop = createPollLoop({\n\t\t\t\tpollOnce: registration.pollOnce,\n\t\t\t\tisEnabled: registration.isEnabled,\n\t\t\t\tpollInterval: registration.pollInterval,\n\t\t\t\tdefaultIntervalMs: registration.defaultIntervalMs,\n\t\t\t\tonScheduledResult(result, durationMs) {\n\t\t\t\t\tif (result.errors.length === 0) return;\n\t\t\t\t\tlogger.warn({ pollerId: id, durationMs, result }, \"Poll completed with errors\");\n\t\t\t\t},\n\t\t\t\tonScheduledError(error, durationMs) {\n\t\t\t\t\tlogger.error({ pollerId: id, durationMs, err: error }, \"Poll failed\");\n\t\t\t\t},\n\t\t\t});\n\t\t\tloops.set(id, loop);\n\t\t\treturn { poll: loop.poll };\n\t\t},\n\t\tstart() {\n\t\t\tsealed = true;\n\t\t\tfor (const loop of loops.values()) loop.start();\n\t\t},\n\t\tstop() {\n\t\t\tfor (const loop of loops.values()) loop.stop();\n\t\t},\n\t};\n}\n"],"mappings":";;;;;AAyBO,SAAS,yBAAyB,QAA2C;AACnF,QAAM,QAAQ,oBAAI,IAA+C;AACjE,MAAI,SAAS;AAEb,SAAO;AAAA,IACN,OACC,cACsB;AACtB,YAAM,KAAK,aAAa,GAAG,KAAK;AAChC,UAAI,CAAC,GAAI,OAAM,IAAI,MAAM,2CAA2C;AACpE,UAAI,OAAQ,OAAM,IAAI,MAAM,2BAA2B,EAAE,6BAA6B;AACtF,UAAI,MAAM,IAAI,EAAE,EAAG,OAAM,IAAI,MAAM,qBAAqB,EAAE,GAAG;AAE7D,YAAM,OAAO,eAAe;AAAA,QAC3B,UAAU,aAAa;AAAA,QACvB,WAAW,aAAa;AAAA,QACxB,cAAc,aAAa;AAAA,QAC3B,mBAAmB,aAAa;AAAA,QAChC,kBAAkB,QAAQ,YAAY;AACrC,cAAI,OAAO,OAAO,WAAW,EAAG;AAChC,iBAAO,KAAK,EAAE,UAAU,IAAI,YAAY,OAAO,GAAG,4BAA4B;AAAA,QAC/E;AAAA,QACA,iBAAiB,OAAO,YAAY;AACnC,iBAAO,MAAM,EAAE,UAAU,IAAI,YAAY,KAAK,MAAM,GAAG,aAAa;AAAA,QACrE;AAAA,MACD,CAAC;AACD,YAAM,IAAI,IAAI,IAAI;AAClB,aAAO,EAAE,MAAM,KAAK,KAAK;AAAA,IAC1B;AAAA,IACA,QAAQ;AACP,eAAS;AACT,iBAAW,QAAQ,MAAM,OAAO,EAAG,MAAK,MAAM;AAAA,IAC/C;AAAA,IACA,OAAO;AACN,iBAAW,QAAQ,MAAM,OAAO,EAAG,MAAK,KAAK;AAAA,IAC9C;AAAA,EACD;AACD;","names":[]}
@@ -1,16 +1,7 @@
1
- import ms from "ms";
2
- /**
3
- * Parse a human-friendly duration string (e.g. "150ms", "1.5s", "2 min") into
4
- * milliseconds. Returns `defaultMs` when the input cannot be parsed.
5
- *
6
- * `options.allowHours` is retained for existing callers; the underlying `ms`
7
- * parser supports hours and other common duration units by default.
8
- */
9
- export function parseDurationMs(value, defaultMs, _options = {}) {
10
- const parsed = ms(value.trim());
11
- if (!Number.isFinite(parsed) || parsed < 0) {
12
- return defaultMs;
13
- }
14
- return parsed;
15
- }
1
+ import {
2
+ parseDurationMs
3
+ } from "./chunk-IU3L35PC.js";
4
+ export {
5
+ parseDurationMs
6
+ };
16
7
  //# sourceMappingURL=duration-parse.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"duration-parse.js","sourceRoot":"","sources":["../src/duration-parse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC9B,KAAa,EACb,SAAiB,EACjB,WAAqC,EAAE;IAEvC,MAAM,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,EAAoB,CAAC,CAAC;IAClD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;QAC5C,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC"}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { parseDurationMs } from "./duration-parse.js";
2
- export { createPollLoop, emptyPollResult, type PollLoop, type PollResult, } from "./poll-loop.js";
2
+ export { createPollLoop, createPollSchedule, emptyPollResult, type PollLoop, type PollResult, type PollResultWithErrors, } from "./poll-loop.js";
3
+ export { createPollingCoordinator, type PollingCoordinator, type PollingLogger, type PollingRegistration, type RegisteredPoller, } from "./polling-coordinator.js";
3
4
  export { ensureWorkerForActiveAgent, hasProcessEvent, type ProcessEventRepoLike, processNeedsWorker, type WorkerSupervisorLike, } from "./process-helpers.js";
4
5
  export { consumeTriggerFile, errorCode, readTriggerFile, type TriggerFileReadResult, } from "./trigger-files.js";
5
6
  export { type AgentRepoAccessorLike, type BroadcasterLike, type CompletionReconciliationOptions, type CompletionReconciliationResult, type ContinueWatcherAgentStartupOptions, continueWatcherAgentStartup, type DiscoveryPassOptions, deferWatcherLaunchStart, launchFailureMessage, requireWatcherStartTurnId, runWatcherAbortReconciliation, runWatcherCompletionReconciliation, runWatcherDiscoveryPass, shouldEnsureWorkerForExistingActiveAgent, type WatcherCommandResult, type WatcherCommandServiceLike, type WatcherStartupDeps, } from "./watcher-coordinator.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EACN,cAAc,EACd,eAAe,EACf,KAAK,QAAQ,EACb,KAAK,UAAU,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,0BAA0B,EAC1B,eAAe,EACf,KAAK,oBAAoB,EACzB,kBAAkB,EAClB,KAAK,oBAAoB,GACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,kBAAkB,EAClB,SAAS,EACT,eAAe,EACf,KAAK,qBAAqB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,eAAe,EACpB,KAAK,+BAA+B,EACpC,KAAK,8BAA8B,EACnC,KAAK,kCAAkC,EACvC,2BAA2B,EAC3B,KAAK,oBAAoB,EACzB,uBAAuB,EACvB,oBAAoB,EACpB,yBAAyB,EACzB,6BAA6B,EAC7B,kCAAkC,EAClC,uBAAuB,EACvB,wCAAwC,EACxC,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,KAAK,kBAAkB,GACvB,MAAM,0BAA0B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EACN,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,KAAK,QAAQ,EACb,KAAK,UAAU,EACf,KAAK,oBAAoB,GACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,wBAAwB,EACxB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,GACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACN,0BAA0B,EAC1B,eAAe,EACf,KAAK,oBAAoB,EACzB,kBAAkB,EAClB,KAAK,oBAAoB,GACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,kBAAkB,EAClB,SAAS,EACT,eAAe,EACf,KAAK,qBAAqB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,eAAe,EACpB,KAAK,+BAA+B,EACpC,KAAK,8BAA8B,EACnC,KAAK,kCAAkC,EACvC,2BAA2B,EAC3B,KAAK,oBAAoB,EACzB,uBAAuB,EACvB,oBAAoB,EACpB,yBAAyB,EACzB,6BAA6B,EAC7B,kCAAkC,EAClC,uBAAuB,EACvB,wCAAwC,EACxC,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,KAAK,kBAAkB,GACvB,MAAM,0BAA0B,CAAC"}
package/dist/index.js CHANGED
@@ -1,6 +1,78 @@
1
- export { parseDurationMs } from "./duration-parse.js";
2
- export { createPollLoop, emptyPollResult, } from "./poll-loop.js";
3
- export { ensureWorkerForActiveAgent, hasProcessEvent, processNeedsWorker, } from "./process-helpers.js";
4
- export { consumeTriggerFile, errorCode, readTriggerFile, } from "./trigger-files.js";
5
- export { continueWatcherAgentStartup, deferWatcherLaunchStart, launchFailureMessage, requireWatcherStartTurnId, runWatcherAbortReconciliation, runWatcherCompletionReconciliation, runWatcherDiscoveryPass, shouldEnsureWorkerForExistingActiveAgent, } from "./watcher-coordinator.js";
1
+ import {
2
+ createPollingCoordinator
3
+ } from "./chunk-USTHXEZJ.js";
4
+ import {
5
+ createPollLoop,
6
+ createPollSchedule,
7
+ emptyPollResult
8
+ } from "./chunk-HG5TEBHZ.js";
9
+ import {
10
+ parseDurationMs
11
+ } from "./chunk-IU3L35PC.js";
12
+ import {
13
+ continueWatcherAgentStartup,
14
+ deferWatcherLaunchStart,
15
+ launchFailureMessage,
16
+ requireWatcherStartTurnId,
17
+ runWatcherAbortReconciliation,
18
+ runWatcherCompletionReconciliation,
19
+ runWatcherDiscoveryPass,
20
+ shouldEnsureWorkerForExistingActiveAgent
21
+ } from "./chunk-XLVMFO6W.js";
22
+ import {
23
+ ensureWorkerForActiveAgent,
24
+ hasProcessEvent,
25
+ processNeedsWorker
26
+ } from "./chunk-3KGAUQIG.js";
27
+
28
+ // src/trigger-files.ts
29
+ import { readFile, unlink } from "fs/promises";
30
+ function errorCode(error) {
31
+ if (typeof error !== "object" || error === null || !("code" in error)) {
32
+ return null;
33
+ }
34
+ const code = error.code;
35
+ return typeof code === "string" ? code : null;
36
+ }
37
+ async function readTriggerFile(filePath) {
38
+ try {
39
+ return { exists: true, content: await readFile(filePath, "utf8") };
40
+ } catch (error) {
41
+ if (errorCode(error) === "ENOENT") {
42
+ return { exists: false };
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+ async function consumeTriggerFile(filePath) {
48
+ try {
49
+ await unlink(filePath);
50
+ } catch (error) {
51
+ if (errorCode(error) === "ENOENT") {
52
+ return;
53
+ }
54
+ throw error;
55
+ }
56
+ }
57
+ export {
58
+ consumeTriggerFile,
59
+ continueWatcherAgentStartup,
60
+ createPollLoop,
61
+ createPollSchedule,
62
+ createPollingCoordinator,
63
+ deferWatcherLaunchStart,
64
+ emptyPollResult,
65
+ ensureWorkerForActiveAgent,
66
+ errorCode,
67
+ hasProcessEvent,
68
+ launchFailureMessage,
69
+ parseDurationMs,
70
+ processNeedsWorker,
71
+ readTriggerFile,
72
+ requireWatcherStartTurnId,
73
+ runWatcherAbortReconciliation,
74
+ runWatcherCompletionReconciliation,
75
+ runWatcherDiscoveryPass,
76
+ shouldEnsureWorkerForExistingActiveAgent
77
+ };
6
78
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EACN,cAAc,EACd,eAAe,GAGf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,0BAA0B,EAC1B,eAAe,EAEf,kBAAkB,GAElB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,kBAAkB,EAClB,SAAS,EACT,eAAe,GAEf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAMN,2BAA2B,EAE3B,uBAAuB,EACvB,oBAAoB,EACpB,yBAAyB,EACzB,6BAA6B,EAC7B,kCAAkC,EAClC,uBAAuB,EACvB,wCAAwC,GAIxC,MAAM,0BAA0B,CAAC"}
1
+ {"version":3,"sources":["../src/trigger-files.ts"],"sourcesContent":["import { readFile, unlink } from \"node:fs/promises\";\n\nexport type TriggerFileReadResult = { exists: false } | { exists: true; content: string };\n\nexport function errorCode(error: unknown): string | null {\n\tif (typeof error !== \"object\" || error === null || !(\"code\" in error)) {\n\t\treturn null;\n\t}\n\tconst code = (error as { code?: unknown }).code;\n\treturn typeof code === \"string\" ? code : null;\n}\n\nexport async function readTriggerFile(filePath: string): Promise<TriggerFileReadResult> {\n\ttry {\n\t\treturn { exists: true, content: await readFile(filePath, \"utf8\") };\n\t} catch (error) {\n\t\tif (errorCode(error) === \"ENOENT\") {\n\t\t\treturn { exists: false };\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport async function consumeTriggerFile(filePath: string): Promise<void> {\n\ttry {\n\t\tawait unlink(filePath);\n\t} catch (error) {\n\t\tif (errorCode(error) === \"ENOENT\") {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,UAAU,cAAc;AAI1B,SAAS,UAAU,OAA+B;AACxD,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,EAAE,UAAU,QAAQ;AACtE,WAAO;AAAA,EACR;AACA,QAAM,OAAQ,MAA6B;AAC3C,SAAO,OAAO,SAAS,WAAW,OAAO;AAC1C;AAEA,eAAsB,gBAAgB,UAAkD;AACvF,MAAI;AACH,WAAO,EAAE,QAAQ,MAAM,SAAS,MAAM,SAAS,UAAU,MAAM,EAAE;AAAA,EAClE,SAAS,OAAO;AACf,QAAI,UAAU,KAAK,MAAM,UAAU;AAClC,aAAO,EAAE,QAAQ,MAAM;AAAA,IACxB;AACA,UAAM;AAAA,EACP;AACD;AAEA,eAAsB,mBAAmB,UAAiC;AACzE,MAAI;AACH,UAAM,OAAO,QAAQ;AAAA,EACtB,SAAS,OAAO;AACf,QAAI,UAAU,KAAK,MAAM,UAAU;AAClC;AAAA,IACD;AACA,UAAM;AAAA,EACP;AACD;","names":[]}
@@ -1,3 +1,5 @@
1
+ /** Reserve the next poll time for a caller-owned key, before starting its work. */
2
+ export declare function createPollSchedule(now?: () => number): (key: string, interval?: string, timestamp?: number) => boolean;
1
3
  export interface PollResult {
2
4
  created: string[];
3
5
  aborted: string[];
@@ -6,7 +8,10 @@ export interface PollResult {
6
8
  errors: string[];
7
9
  }
8
10
  export declare function emptyPollResult(): PollResult;
9
- export interface PollLoop<T extends PollResult = PollResult> {
11
+ export interface PollResultWithErrors {
12
+ readonly errors: readonly string[];
13
+ }
14
+ export interface PollLoop<T extends PollResultWithErrors = PollResult> {
10
15
  poll(): Promise<T>;
11
16
  start(): void;
12
17
  stop(): void;
@@ -15,10 +20,12 @@ export interface PollLoop<T extends PollResult = PollResult> {
15
20
  * Create a non-overlapping polling loop. `pollOnce` is the actual work;
16
21
  * concurrent calls to `poll()` coalesce into the in-flight promise.
17
22
  */
18
- export declare function createPollLoop<T extends PollResult>(opts: {
23
+ export declare function createPollLoop<T extends PollResultWithErrors>(opts: {
19
24
  pollOnce: () => Promise<T>;
20
25
  isEnabled: () => boolean;
21
26
  pollInterval: () => string;
22
27
  defaultIntervalMs?: number;
28
+ onScheduledResult: (result: T, durationMs: number) => void;
29
+ onScheduledError: (error: unknown, durationMs: number) => void;
23
30
  }): PollLoop<T>;
24
31
  //# sourceMappingURL=poll-loop.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"poll-loop.d.ts","sourceRoot":"","sources":["../src/poll-loop.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,UAAU;IAC1B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,MAAM,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,wBAAgB,eAAe,IAAI,UAAU,CAQ5C;AAED,MAAM,WAAW,QAAQ,CAAC,CAAC,SAAS,UAAU,GAAG,UAAU;IAC1D,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;IACnB,KAAK,IAAI,IAAI,CAAC;IACd,IAAI,IAAI,IAAI,CAAC;CACb;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,UAAU,EAAE,IAAI,EAAE;IAC1D,QAAQ,EAAE,MAAM,OAAO,C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I,CAAC;IAC3D,gBAAgB,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/D,GAAG,QAAQ,CAAC,CAAC,CAAC,CAiDd"}
package/dist/poll-loop.js CHANGED
@@ -1,59 +1,12 @@
1
- import { parseDurationMs } from "./duration-parse.js";
2
- export function emptyPollResult() {
3
- return {
4
- created: [],
5
- aborted: [],
6
- labelExchanged: [],
7
- skipped: [],
8
- errors: [],
9
- };
10
- }
11
- /**
12
- * Create a non-overlapping polling loop. `pollOnce` is the actual work;
13
- * concurrent calls to `poll()` coalesce into the in-flight promise.
14
- */
15
- export function createPollLoop(opts) {
16
- let timer = null;
17
- let pollInFlight = null;
18
- const defaultMs = opts.defaultIntervalMs ?? 60_000;
19
- async function poll() {
20
- if (pollInFlight) {
21
- return pollInFlight;
22
- }
23
- const running = (async () => {
24
- try {
25
- return await opts.pollOnce();
26
- }
27
- finally {
28
- pollInFlight = null;
29
- }
30
- })();
31
- pollInFlight = running;
32
- return running;
33
- }
34
- function pollAndIgnoreUnhandledRejection() {
35
- void poll().catch(() => undefined);
36
- }
37
- return {
38
- poll,
39
- start() {
40
- if (timer) {
41
- return;
42
- }
43
- if (!opts.isEnabled()) {
44
- return;
45
- }
46
- const ms = parseDurationMs(opts.pollInterval(), defaultMs);
47
- timer = setInterval(pollAndIgnoreUnhandledRejection, ms);
48
- pollAndIgnoreUnhandledRejection();
49
- },
50
- stop() {
51
- if (!timer) {
52
- return;
53
- }
54
- clearInterval(timer);
55
- timer = null;
56
- },
57
- };
58
- }
1
+ import {
2
+ createPollLoop,
3
+ createPollSchedule,
4
+ emptyPollResult
5
+ } from "./chunk-HG5TEBHZ.js";
6
+ import "./chunk-IU3L35PC.js";
7
+ export {
8
+ createPollLoop,
9
+ createPollSchedule,
10
+ emptyPollResult
11
+ };
59
12
  //# sourceMappingURL=poll-loop.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"poll-loop.js","sourceRoot":"","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,CAAC;YACzD,+BAA+B,EAAE,CAAC;QACnC,CAAC;QACD,IAAI;YACH,IAAI,CAAC,KAAK,EAAE,CAAC;gBACZ,OAAO;YACR,CAAC;YACD,aAAa,CAAC,KAAK,CAAC,CAAC;YACrB,KAAK,GAAG,IAAI,CAAC;QACd,CAAC;KACD,CAAC;AACH,CAAC"}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,22 @@
1
+ import { type PollResult, type PollResultWithErrors } from "./poll-loop.js";
2
+ export interface PollingLogger {
3
+ warn(payload: Record<string, unknown>, message?: string): void;
4
+ error(payload: Record<string, unknown>, message?: string): void;
5
+ }
6
+ export interface PollingRegistration<T extends PollResultWithErrors> {
7
+ id: string;
8
+ pollOnce(): Promise<T>;
9
+ isEnabled(): boolean;
10
+ pollInterval(): string;
11
+ defaultIntervalMs?: number;
12
+ }
13
+ export interface RegisteredPoller<T extends PollResultWithErrors = PollResult> {
14
+ poll(): Promise<T>;
15
+ }
16
+ export interface PollingCoordinator {
17
+ create<T extends PollResultWithErrors>(registration: PollingRegistration<T>): RegisteredPoller<T>;
18
+ start(): void;
19
+ stop(): void;
20
+ }
21
+ export declare function createPollingCoordinator(logger: PollingLogger): PollingCoordinator;
22
+ //# sourceMappingURL=polling-coordinator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"polling-coordinator.d.ts","sourceRoot":"","sources":["../src/polling-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,UAAU,EAAE,KAAK,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAE5F,MAAM,WAAW,aAAa;IAC7B,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/D,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChE;AAED,MAAM,WAAW,mBAAmB,CAAC,CAAC,SAAS,oBAAoB;IAClE,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;IACvB,SAAS,IAAI,OAAO,CAAC;IACrB,YAAY,IAAI,MAAM,CAAC;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,gBAAgB,CAAC,CAAC,SAAS,oBAAoB,GAAG,UAAU;IAC5E,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IAClC,MAAM,CAAC,CAAC,SAAS,oBAAoB,EAAE,YAAY,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAClG,KAAK,IAAI,IAAI,CAAC;IACd,IAAI,IAAI,IAAI,CAAC;CACb;AAED,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,aAAa,GAAG,kBAAkB,CAqClF"}
@@ -0,0 +1,9 @@
1
+ import {
2
+ createPollingCoordinator
3
+ } from "./chunk-USTHXEZJ.js";
4
+ import "./chunk-HG5TEBHZ.js";
5
+ import "./chunk-IU3L35PC.js";
6
+ export {
7
+ createPollingCoordinator
8
+ };
9
+ //# sourceMappingURL=polling-coordinator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,33 +1,11 @@
1
- /**
2
- * Check whether a process already has an event of the given type.
3
- */
4
- export function hasProcessEvent(events, instanceId, eventType) {
5
- return events.listByInstance(instanceId, 200).some((event) => event.eventType === eventType);
6
- }
7
- export function processNeedsWorker(process) {
8
- return process.selectedTurnId !== null && process.lifecycleStatus === "active";
9
- }
10
- /**
11
- * Spawn a worker for a process whose selected turn is runnable but currently has
12
- * no running worker. No-ops when the process is not worker-runnable or already
13
- * has a worker.
14
- */
15
- export async function ensureWorkerForActiveAgent(deps, process) {
16
- if (!processNeedsWorker(process) || deps.supervisor.getWorker(process.id)) {
17
- return;
18
- }
19
- try {
20
- await deps.supervisor.spawnWorker(process.id);
21
- }
22
- catch (error) {
23
- deps.events.create({
24
- instanceId: process.id,
25
- eventType: "worker_spawn_failed",
26
- data: {
27
- reason: error instanceof Error ? error.message : "Failed to spawn worker",
28
- },
29
- });
30
- throw error;
31
- }
32
- }
1
+ import {
2
+ ensureWorkerForActiveAgent,
3
+ hasProcessEvent,
4
+ processNeedsWorker
5
+ } from "./chunk-3KGAUQIG.js";
6
+ export {
7
+ ensureWorkerForActiveAgent,
8
+ hasProcessEvent,
9
+ processNeedsWorker
10
+ };
33
11
  //# sourceMappingURL=process-helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"process-helpers.js","sourceRoot":"","sources":["../src/process-helpers.ts"],"names":[],"mappings":"AAYA;;GAEG;AACH,MAAM,UAAU,eAAe,CAC9B,MAA4B,EAC5B,UAAkB,EAClB,SAAiB;IAEjB,OAAO,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC;AAC9F,CAAC;AAED,MAAM,UAAU,kBAAkB,CACjC,OAAoE;IAEpE,OAAO,OAAO,CAAC,cAAc,KAAK,IAAI,IAAI,OAAO,CAAC,eAAe,KAAK,QAAQ,CAAC;AAChF,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC/C,IAAwE,EACxE,OAAwB;IAExB,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;QAC3E,OAAO;IACR,CAAC;IACD,IAAI,CAAC;QACJ,MAAM,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;YAClB,UAAU,EAAE,OAAO,CAAC,EAAE;YACtB,SAAS,EAAE,qBAAqB;YAChC,IAAI,EAAE;gBACL,MAAM,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,wBAAwB;aACzE;SACD,CAAC,CAAC;QACH,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC"}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,131 +1,22 @@
1
- import { recordWriteIfMissing, } from "@leitwerk-dev/external-writes";
2
- import { ensureWorkerForActiveAgent, hasProcessEvent, processNeedsWorker, } from "./process-helpers.js";
3
- export function requireWatcherStartTurnId(launchPlan, targetLabel) {
4
- if (launchPlan.startTurnId) {
5
- return launchPlan.startTurnId;
6
- }
7
- throw new Error(`Watcher launcher '${launchPlan.launcherId}' did not declare a startTurnId for ${targetLabel}`);
8
- }
9
- export async function continueWatcherAgentStartup(deps, opts) {
10
- const { process } = opts;
11
- if (!hasProcessEvent(deps.events, process.id, "agent_created")) {
12
- deps.events.create({
13
- instanceId: process.id,
14
- eventType: "agent_created",
15
- data: opts.createdEventData,
16
- });
17
- }
18
- await opts.afterCreatedEvent?.(process);
19
- await opts.beforeStart?.(process);
20
- let currentProcess = deps.processes.getById(process.id) ?? process;
21
- if (currentProcess.lifecycleStatus === "discovered") {
22
- const startResult = await deps.commands.startProcess(currentProcess.id, opts.startTurnId);
23
- if (!startResult.ok) {
24
- currentProcess = startResult.process ?? currentProcess;
25
- throw new Error(startResult.message ?? "Failed to start process");
26
- }
27
- currentProcess = startResult.process ?? currentProcess;
28
- if (opts.broadcastCreated !== false) {
29
- deps.broadcaster.sendDurable("process.created", {
30
- process: currentProcess,
31
- processId: currentProcess.processId,
32
- ...opts.createdBroadcastData,
33
- }, currentProcess.id);
34
- }
35
- }
36
- await ensureWorkerForActiveAgent(deps, currentProcess);
37
- return currentProcess.id;
38
- }
39
- export async function runWatcherDiscoveryPass(opts) {
40
- for (const item of opts.items) {
41
- try {
42
- const existingAgent = opts.findExistingAgent(item);
43
- if (existingAgent) {
44
- if (existingAgent.lifecycleStatus === "discovered") {
45
- const resumeResult = await opts.resumeDiscoveredAgent(existingAgent, item);
46
- if (resumeResult === "skipped") {
47
- opts.result.skipped.push(opts.getResultLabel(item));
48
- }
49
- continue;
50
- }
51
- if (opts.ensureWorkerForExistingAgent) {
52
- const handled = await opts.ensureWorkerForExistingAgent(existingAgent, item);
53
- if (handled) {
54
- continue;
55
- }
56
- }
57
- opts.result.skipped.push(opts.getResultLabel(item));
58
- continue;
59
- }
60
- const createResult = await opts.createAgent(item);
61
- if (createResult?.outcome === "created") {
62
- opts.result.created.push(opts.getResultLabel(item));
63
- continue;
64
- }
65
- if (createResult?.outcome === "skipped") {
66
- opts.result.skipped.push(opts.getResultLabel(item));
67
- }
68
- }
69
- catch (error) {
70
- opts.result.errors.push(opts.formatError(item, error));
71
- }
72
- }
73
- }
74
- export async function runWatcherAbortReconciliation(opts) {
75
- for (const process of opts.candidates) {
76
- try {
77
- const shouldAbort = await opts.shouldAbort(process);
78
- if (!shouldAbort) {
79
- continue;
80
- }
81
- const abortResult = await opts.commands.abortProcess(process.id);
82
- if (!abortResult.ok) {
83
- if (abortResult.code === "worker_reconcile_failed") {
84
- throw new Error(abortResult.message ?? "Failed to abort process");
85
- }
86
- continue;
87
- }
88
- const abortedAgent = abortResult.process ?? process;
89
- if (!hasProcessEvent(opts.events, abortedAgent.id, "aborted_label_removed")) {
90
- opts.events.create({
91
- instanceId: abortedAgent.id,
92
- eventType: "aborted_label_removed",
93
- data: opts.getAbortedEventData(abortedAgent),
94
- });
95
- }
96
- opts.result.aborted.push(opts.getResultLabel(process));
97
- }
98
- catch (error) {
99
- opts.result.errors.push(`${opts.getErrorLabel(process)}: ${error instanceof Error ? error.message : String(error)}`);
100
- }
101
- }
102
- }
103
- export async function runWatcherCompletionReconciliation(opts) {
104
- for (const process of opts.candidates) {
105
- try {
106
- const reconciliation = await opts.reconcile(process);
107
- if (!reconciliation.changed) {
108
- continue;
109
- }
110
- if (reconciliation.writeIdentity) {
111
- recordWriteIfMissing(opts.externalWrites, process.id, reconciliation.writeIdentity, reconciliation.metadata);
112
- }
113
- opts.result.labelExchanged.push(opts.getResultLabel(process));
114
- }
115
- catch (error) {
116
- opts.result.errors.push(`${opts.getErrorLabel(process)}: ${error instanceof Error ? error.message : String(error)}`);
117
- }
118
- }
119
- }
120
- export function shouldEnsureWorkerForExistingActiveAgent(deps, process) {
121
- return processNeedsWorker(process) && !deps.supervisor.getWorker(process.id);
122
- }
123
- export function deferWatcherLaunchStart(launchPlan) {
124
- return launchPlan.startTurnId === null ? launchPlan : { ...launchPlan, startTurnId: null };
125
- }
126
- export function launchFailureMessage(result) {
127
- return typeof result.body.error === "string" && result.body.error.trim().length > 0
128
- ? result.body.error
129
- : `Process launch failed with status ${result.status}`;
130
- }
1
+ import {
2
+ continueWatcherAgentStartup,
3
+ deferWatcherLaunchStart,
4
+ launchFailureMessage,
5
+ requireWatcherStartTurnId,
6
+ runWatcherAbortReconciliation,
7
+ runWatcherCompletionReconciliation,
8
+ runWatcherDiscoveryPass,
9
+ shouldEnsureWorkerForExistingActiveAgent
10
+ } from "./chunk-XLVMFO6W.js";
11
+ import "./chunk-3KGAUQIG.js";
12
+ export {
13
+ continueWatcherAgentStartup,
14
+ deferWatcherLaunchStart,
15
+ launchFailureMessage,
16
+ requireWatcherStartTurnId,
17
+ runWatcherAbortReconciliation,
18
+ runWatcherCompletionReconciliation,
19
+ runWatcherDiscoveryPass,
20
+ shouldEnsureWorkerForExistingActiveAgent
21
+ };
131
22
  //# sourceMappingURL=watcher-coordinator.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"watcher-coordinator.js","sourceRoot":"","sources":["../src/watcher-coordinator.ts"],"names":[],"mappings":"AACA,OA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cesContent":[],"mappings":"","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leitwerk-dev/watcher-utils",
3
- "version": "0.1.9",
3
+ "version": "0.2.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
@@ -18,9 +18,9 @@
18
18
  "build": "tsup --silent"
19
19
  },
20
20
  "dependencies": {
21
- "@leitwerk-dev/domain": "0.1.9",
22
- "@leitwerk-dev/external-writes": "0.1.9",
23
- "@leitwerk-dev/protocol": "0.1.9",
21
+ "@leitwerk-dev/domain": "0.2.0",
22
+ "@leitwerk-dev/external-writes": "0.2.0",
23
+ "@leitwerk-dev/protocol": "0.2.0",
24
24
  "ms": "^2.1.3"
25
25
  },
26
26
  "devDependencies": {
@@ -32,7 +32,7 @@
32
32
  "access": "public"
33
33
  },
34
34
  "engines": {
35
- "node": ">=22"
35
+ "node": ">=26 <27"
36
36
  },
37
37
  "files": [
38
38
  "dist/**",
package/src/index.ts CHANGED
@@ -1,10 +1,19 @@
1
1
  export { parseDurationMs } from "./duration-parse.js";
2
2
  export {
3
3
  createPollLoop,
4
+ createPollSchedule,
4
5
  emptyPollResult,
5
6
  type PollLoop,
6
7
  type PollResult,
8
+ type PollResultWithErrors,
7
9
  } from "./poll-loop.js";
10
+ export {
11
+ createPollingCoordinator,
12
+ type PollingCoordinator,
13
+ type PollingLogger,
14
+ type PollingRegistration,
15
+ type RegisteredPoller,
16
+ } from "./polling-coordinator.js";
8
17
  export {
9
18
  ensureWorkerForActiveAgent,
10
19
  hasProcessEvent,
package/src/poll-loop.ts CHANGED
@@ -1,5 +1,15 @@
1
1
  import { parseDurationMs } from "./duration-parse.js";
2
2
 
3
+ /** Reserve the next poll time for a caller-owned key, before starting its work. */
4
+ export function createPollSchedule(now: () => number = () => Date.now()) {
5
+ const dueAt = new Map<string, number>();
6
+ return (key: string, interval = "30s", timestamp = now()): boolean => {
7
+ if ((dueAt.get(key) ?? 0) > timestamp) return false;
8
+ dueAt.set(key, timestamp + parseDurationMs(interval, 30_000));
9
+ return true;
10
+ };
11
+ }
12
+
3
13
  export interface PollResult {
4
14
  created: string[];
5
15
  aborted: string[];
@@ -18,7 +28,11 @@ export function emptyPollResult(): PollResult {
18
28
  };
19
29
  }
20
30
 
21
- export interface PollLoop<T extends PollResult = PollResult> {
31
+ export interface PollResultWithErrors {
32
+ readonly errors: readonly string[];
33
+ }
34
+
35
+ export interface PollLoop<T extends PollResultWithErrors = PollResult> {
22
36
  poll(): Promise<T>;
23
37
  start(): void;
24
38
  stop(): void;
@@ -28,11 +42,13 @@ export interface PollLoop<T extends PollResult = PollResult> {
28
42
  * Create a non-overlapping polling loop. `pollOnce` is the actual work;
29
43
  * concurrent calls to `poll()` coalesce into the in-flight promise.
30
44
  */
31
- export function createPollLoop<T extends PollResult>(opts: {
45
+ export function createPollLoop<T extends PollResultWithErrors>(opts: {
32
46
  pollOnce: () => Promise<T>;
33
47
  isEnabled: () => boolean;
34
48
  pollInterval: () => string;
35
49
  defaultIntervalMs?: number;
50
+ onScheduledResult: (result: T, durationMs: number) => void;
51
+ onScheduledError: (error: unknown, durationMs: number) => void;
36
52
  }): PollLoop<T> {
37
53
  let timer: ReturnType<typeof setInterval> | null = null;
38
54
  let pollInFlight: Promise<T> | null = null;
@@ -53,8 +69,12 @@ export function createPollLoop<T extends PollResult>(opts: {
53
69
  return running;
54
70
  }
55
71
 
56
- function pollAndIgnoreUnhandledRejection(): void {
57
- void poll().catch(() => undefined);
72
+ function pollScheduled(): void {
73
+ const startedAt = Date.now();
74
+ void poll().then(
75
+ (result) => opts.onScheduledResult(result, Date.now() - startedAt),
76
+ (error: unknown) => opts.onScheduledError(error, Date.now() - startedAt),
77
+ );
58
78
  }
59
79
 
60
80
  return {
@@ -67,8 +87,8 @@ export function createPollLoop<T extends PollResult>(opts: {
67
87
  return;
68
88
  }
69
89
  const ms = parseDurationMs(opts.pollInterval(), defaultMs);
70
- timer = setInterval(pollAndIgnoreUnhandledRejection, ms);
71
- pollAndIgnoreUnhandledRejection();
90
+ timer = setInterval(pollScheduled, ms);
91
+ pollScheduled();
72
92
  },
73
93
  stop() {
74
94
  if (!timer) {
@@ -0,0 +1,63 @@
1
+ import { createPollLoop, type PollResult, type PollResultWithErrors } from "./poll-loop.js";
2
+
3
+ export interface PollingLogger {
4
+ warn(payload: Record<string, unknown>, message?: string): void;
5
+ error(payload: Record<string, unknown>, message?: string): void;
6
+ }
7
+
8
+ export interface PollingRegistration<T extends PollResultWithErrors> {
9
+ id: string;
10
+ pollOnce(): Promise<T>;
11
+ isEnabled(): boolean;
12
+ pollInterval(): string;
13
+ defaultIntervalMs?: number;
14
+ }
15
+
16
+ export interface RegisteredPoller<T extends PollResultWithErrors = PollResult> {
17
+ poll(): Promise<T>;
18
+ }
19
+
20
+ export interface PollingCoordinator {
21
+ create<T extends PollResultWithErrors>(registration: PollingRegistration<T>): RegisteredPoller<T>;
22
+ start(): void;
23
+ stop(): void;
24
+ }
25
+
26
+ export function createPollingCoordinator(logger: PollingLogger): PollingCoordinator {
27
+ const loops = new Map<string, ReturnType<typeof createPollLoop>>();
28
+ let sealed = false;
29
+
30
+ return {
31
+ create<T extends PollResultWithErrors>(
32
+ registration: PollingRegistration<T>,
33
+ ): RegisteredPoller<T> {
34
+ const id = registration.id.trim();
35
+ if (!id) throw new Error("Polling registration id must not be empty");
36
+ if (sealed) throw new Error(`Cannot register poller '${id}' after polling has started`);
37
+ if (loops.has(id)) throw new Error(`Duplicate poller '${id}'`);
38
+
39
+ const loop = createPollLoop({
40
+ pollOnce: registration.pollOnce,
41
+ isEnabled: registration.isEnabled,
42
+ pollInterval: registration.pollInterval,
43
+ defaultIntervalMs: registration.defaultIntervalMs,
44
+ onScheduledResult(result, durationMs) {
45
+ if (result.errors.length === 0) return;
46
+ logger.warn({ pollerId: id, durationMs, result }, "Poll completed with errors");
47
+ },
48
+ onScheduledError(error, durationMs) {
49
+ logger.error({ pollerId: id, durationMs, err: error }, "Poll failed");
50
+ },
51
+ });
52
+ loops.set(id, loop);
53
+ return { poll: loop.poll };
54
+ },
55
+ start() {
56
+ sealed = true;
57
+ for (const loop of loops.values()) loop.start();
58
+ },
59
+ stop() {
60
+ for (const loop of loops.values()) loop.stop();
61
+ },
62
+ };
63
+ }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/poll-loop.ts"],"sourcesContent":["import { parseDurationMs } from \"./duration-parse.js\";\n\nexport interface PollResult {\n\tcreated: string[];\n\taborted: string[];\n\tlabelExchanged: string[];\n\tskipped: string[];\n\terrors: string[];\n}\n\nexport function emptyPollResult(): PollResult {\n\treturn {\n\t\tcreated: [],\n\t\taborted: [],\n\t\tlabelExchanged: [],\n\t\tskipped: [],\n\t\terrors: [],\n\t};\n}\n\nexport interface PollLoop<T extends PollResult = PollResult> {\n\tpoll(): Promise<T>;\n\tstart(): void;\n\tstop(): void;\n}\n\n/**\n * Create a non-overlapping polling loop. `pollOnce` is the actual work;\n * concurrent calls to `poll()` coalesce into the in-flight promise.\n */\nexport function createPollLoop<T extends PollResult>(opts: {\n\tpollOnce: () => Promise<T>;\n\tisEnabled: () => boolean;\n\tpollInterval: () => string;\n\tdefaultIntervalMs?: number;\n}): PollLoop<T> {\n\tlet timer: ReturnType<typeof setInterval> | null = null;\n\tlet pollInFlight: Promise<T> | null = null;\n\tconst defaultMs = opts.defaultIntervalMs ?? 60_000;\n\n\tasync function poll(): Promise<T> {\n\t\tif (pollInFlight) {\n\t\t\treturn pollInFlight;\n\t\t}\n\t\tconst running = (async () => {\n\t\t\ttry {\n\t\t\t\treturn await opts.pollOnce();\n\t\t\t} finally {\n\t\t\t\tpollInFlight = null;\n\t\t\t}\n\t\t})();\n\t\tpollInFlight = running;\n\t\treturn running;\n\t}\n\n\tfunction pollAndIgnoreUnhandledRejection(): void {\n\t\tvoid poll().catch(() => undefined);\n\t}\n\n\treturn {\n\t\tpoll,\n\t\tstart() {\n\t\t\tif (timer) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!opts.isEnabled()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst ms = parseDurationMs(opts.pollInterval(), defaultMs);\n\t\t\ttimer = setInterval(pollAndIgnoreUnhandledRejection, ms);\n\t\t\tpollAndIgnoreUnhandledRejection();\n\t\t},\n\t\tstop() {\n\t\t\tif (!timer) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearInterval(timer);\n\t\t\ttimer = null;\n\t\t},\n\t};\n}\n"],"mappings":";;;;;AAUO,SAAS,kBAA8B;AAC7C,SAAO;AAAA,IACN,SAAS,CAAC;AAAA,IACV,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,SAAS,CAAC;AAAA,IACV,QAAQ,CAAC;AAAA,EACV;AACD;AAYO,SAAS,eAAqC,MAKrC;AACf,MAAI,QAA+C;AACnD,MAAI,eAAkC;AACtC,QAAM,YAAY,KAAK,qBAAqB;AAE5C,iBAAe,OAAmB;AACjC,QAAI,cAAc;AACjB,aAAO;AAAA,IACR;AACA,UAAM,WAAW,YAAY;AAC5B,UAAI;AACH,eAAO,MAAM,KAAK,SAAS;AAAA,MAC5B,UAAE;AACD,uBAAe;AAAA,MAChB;AAAA,IACD,GAAG;AACH,mBAAe;AACf,WAAO;AAAA,EACR;AAEA,WAAS,kCAAwC;AAChD,SAAK,KAAK,EAAE,MAAM,MAAM,MAAS;AAAA,EAClC;AAEA,SAAO;AAAA,IACN;AAAA,IACA,QAAQ;AACP,UAAI,OAAO;AACV;AAAA,MACD;AACA,UAAI,CAAC,KAAK,UAAU,GAAG;AACtB;AAAA,MACD;AACA,YAAM,KAAK,gBAAgB,KAAK,aAAa,GAAG,SAAS;AACzD,cAAQ,YAAY,iCAAiC,EAAE;AACvD,sCAAgC;AAAA,IACjC;AAAA,IACA,OAAO;AACN,UAAI,CAAC,OAAO;AACX;AAAA,MACD;AACA,oBAAc,KAAK;AACnB,cAAQ;AAAA,IACT;AAAA,EACD;AACD;","names":[]}
@@ -1,31 +0,0 @@
1
- import { readFile, unlink } from "node:fs/promises";
2
- export function errorCode(error) {
3
- if (typeof error !== "object" || error === null || !("code" in error)) {
4
- return null;
5
- }
6
- const code = error.code;
7
- return typeof code === "string" ? code : null;
8
- }
9
- export async function readTriggerFile(filePath) {
10
- try {
11
- return { exists: true, content: await readFile(filePath, "utf8") };
12
- }
13
- catch (error) {
14
- if (errorCode(error) === "ENOENT") {
15
- return { exists: false };
16
- }
17
- throw error;
18
- }
19
- }
20
- export async function consumeTriggerFile(filePath) {
21
- try {
22
- await unlink(filePath);
23
- }
24
- catch (error) {
25
- if (errorCode(error) === "ENOENT") {
26
- return;
27
- }
28
- throw error;
29
- }
30
- }
31
- //# sourceMappingURL=trigger-files.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"trigger-files.js","sourceRoot":"","sources":["../src/trigger-files.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAIpD,MAAM,UAAU,SAAS,CAAC,KAAc;IACvC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,EAAE,CAAC;QACvE,OAAO,IAAI,CAAC;IACb,CAAC;IACD,MAAM,IAAI,GAAI,KAA4B,CAAC,IAAI,CAAC;IAChD,OAAO,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AAC/C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,QAAgB;IACrD,IAAI,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC;IACpE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,SAAS,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE,CAAC;YACnC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;QAC1B,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,QAAgB;IACxD,IAAI,CAAC;QACJ,MAAM,MAAM,CAAC,QAAQ,CAAC,CAAC;IACxB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,SAAS,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE,CAAC;YACnC,OAAO;QACR,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC"}