@glydeunity/unity-healthcheck-mesh 0.0.0-stage → 0.1.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +21 -0
  3. package/README.md +343 -2
  4. package/dist/cjs/config.js +408 -0
  5. package/dist/cjs/ids.js +53 -0
  6. package/dist/cjs/index.js +35 -0
  7. package/dist/cjs/package.json +1 -0
  8. package/dist/cjs/probe.js +81 -0
  9. package/dist/cjs/reporters.js +334 -0
  10. package/dist/cjs/runner.js +234 -0
  11. package/dist/cjs/schedule.js +23 -0
  12. package/dist/cjs/types.js +2 -0
  13. package/dist/cjs/uuid5.js +45 -0
  14. package/dist/cjs/version.js +10 -0
  15. package/dist/esm/config.d.ts +85 -0
  16. package/dist/esm/config.js +402 -0
  17. package/dist/esm/config.js.map +1 -0
  18. package/dist/esm/ids.d.ts +47 -0
  19. package/dist/esm/ids.js +47 -0
  20. package/dist/esm/ids.js.map +1 -0
  21. package/dist/esm/index.d.ts +10 -0
  22. package/dist/esm/index.js +8 -0
  23. package/dist/esm/index.js.map +1 -0
  24. package/dist/esm/probe.d.ts +45 -0
  25. package/dist/esm/probe.js +77 -0
  26. package/dist/esm/probe.js.map +1 -0
  27. package/dist/esm/reporters.d.ts +75 -0
  28. package/dist/esm/reporters.js +330 -0
  29. package/dist/esm/reporters.js.map +1 -0
  30. package/dist/esm/runner.d.ts +25 -0
  31. package/dist/esm/runner.js +230 -0
  32. package/dist/esm/runner.js.map +1 -0
  33. package/dist/esm/schedule.d.ts +15 -0
  34. package/dist/esm/schedule.js +20 -0
  35. package/dist/esm/schedule.js.map +1 -0
  36. package/dist/esm/types.d.ts +101 -0
  37. package/dist/esm/types.js +2 -0
  38. package/dist/esm/types.js.map +1 -0
  39. package/dist/esm/uuid5.d.ts +12 -0
  40. package/dist/esm/uuid5.js +42 -0
  41. package/dist/esm/uuid5.js.map +1 -0
  42. package/dist/esm/version.d.ts +7 -0
  43. package/dist/esm/version.js +8 -0
  44. package/dist/esm/version.js.map +1 -0
  45. package/package.json +53 -4
@@ -0,0 +1,334 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UP_GAUGE_NAME = void 0;
4
+ exports.createReporter = createReporter;
5
+ exports.importOtelApi = importOtelApi;
6
+ const node_buffer_1 = require("node:buffer");
7
+ const config_js_1 = require("./config.js");
8
+ const uuid5_js_1 = require("./uuid5.js");
9
+ const version_js_1 = require("./version.js");
10
+ /**
11
+ * Builds the reporter a report target asks for.
12
+ * @param context - Host process context for the mesh
13
+ * @param target - Resolved report target
14
+ * @returns The reporter
15
+ */
16
+ function createReporter(context, target) {
17
+ switch (target.format) {
18
+ case 'victorialogs/stdout':
19
+ return new StdoutReporter(context);
20
+ case 'victorialogs':
21
+ return new VictoriaLogsReporter(context, target);
22
+ case 'bugsnag':
23
+ return new BugsnagReporter(context, target);
24
+ case 'opentelemetry':
25
+ return new OpenTelemetryReporter(context);
26
+ }
27
+ }
28
+ /** Target URL as a person reads it; the port is always shown. */
29
+ function targetUrl(report) {
30
+ return `${report.scheme}://${report.server}:${report.port}${report.path}`;
31
+ }
32
+ function describeProbe(report) {
33
+ return (`mesh_probe mesh=${report.mesh} observer=${report.observer} target=${targetUrl(report)} ` +
34
+ `result=${report.result} healthy=${report.healthy} latency_ms=${report.latency_ms} check_id=${report.check_id}`);
35
+ }
36
+ function streamValue(value) {
37
+ return value.replace(/["\\]/g, '_');
38
+ }
39
+ async function postOrThrow(request) {
40
+ let response;
41
+ try {
42
+ response = await request.fetchImpl(request.url, {
43
+ method: 'POST',
44
+ headers: request.headers,
45
+ body: request.body,
46
+ signal: AbortSignal.timeout(request.timeoutMs),
47
+ });
48
+ }
49
+ catch (error) {
50
+ throw new Error(`request failed: ${error instanceof Error ? error.message : String(error)}`);
51
+ }
52
+ // The response body is never read; releasing it returns the socket to the pool.
53
+ void response.body?.cancel().catch(() => undefined);
54
+ if (!response.ok)
55
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
56
+ }
57
+ /** Prints one JSON line per report for a stdout shipper to forward. */
58
+ class StdoutReporter {
59
+ name = 'victorialogs/stdout';
60
+ context;
61
+ constructor(context) {
62
+ this.context = context;
63
+ }
64
+ report(reports) {
65
+ for (const report of reports) {
66
+ const line = JSON.stringify(report);
67
+ this.context.writeLine(line, report);
68
+ }
69
+ return Promise.resolve();
70
+ }
71
+ }
72
+ /** POSTs one JSON-line batch to a VictoriaLogs `/insert/jsonline` endpoint. */
73
+ class VictoriaLogsReporter {
74
+ name = 'victorialogs';
75
+ context;
76
+ ingestUrl;
77
+ timeoutMs;
78
+ authorization;
79
+ constructor(context, target) {
80
+ this.context = context;
81
+ this.ingestUrl = `${(target.url ?? '').replace(/\/+$/, '')}/insert/jsonline`;
82
+ this.timeoutMs = target.timeoutMs;
83
+ const username = context.env[target.usernameEnv]?.trim();
84
+ const password = context.env[target.passwordEnv]?.trim();
85
+ this.authorization =
86
+ username && password ? `Basic ${node_buffer_1.Buffer.from(`${username}:${password}`).toString('base64')}` : undefined;
87
+ }
88
+ async report(reports) {
89
+ if (reports.length === 0)
90
+ return;
91
+ const lines = reports.map((report) => JSON.stringify(this.toLine(report)));
92
+ const headers = { 'Content-Type': 'application/stream+json' };
93
+ if (this.authorization)
94
+ headers.Authorization = this.authorization;
95
+ await postOrThrow({
96
+ fetchImpl: this.context.fetchImpl,
97
+ url: this.ingestUrl,
98
+ body: lines.join('\n'),
99
+ headers,
100
+ timeoutMs: this.timeoutMs,
101
+ });
102
+ }
103
+ /**
104
+ * Shapes a report as a VictoriaLogs log entry. `mesh` and `observer` become
105
+ * stream labels; every other field stays a plain, queryable field.
106
+ */
107
+ toLine(report) {
108
+ const { mesh, observer, ...fields } = report;
109
+ return {
110
+ _time: report.at,
111
+ _msg: describeProbe(report),
112
+ _stream: `{mesh="${streamValue(mesh)}",observer="${streamValue(observer)}"}`,
113
+ ...fields,
114
+ };
115
+ }
116
+ }
117
+ /**
118
+ * Reports healthy/unhealthy transitions to Bugsnag.
119
+ *
120
+ * Bugsnag groups events under a `groupingHash`; it does not reject repeats. A
121
+ * per-minute hash would open a new error every minute, so the hash is stable
122
+ * per target and only transitions are sent: one event when a target first
123
+ * fails, one when it recovers. Every server observing the same target lands in
124
+ * the same error, with `user.id` naming which server saw it.
125
+ */
126
+ class BugsnagReporter {
127
+ name = 'bugsnag';
128
+ context;
129
+ target;
130
+ healthyByTarget = new Map();
131
+ warnedMissingKey = false;
132
+ constructor(context, target) {
133
+ this.context = context;
134
+ this.target = target;
135
+ }
136
+ async report(reports) {
137
+ if (reports.length === 0)
138
+ return;
139
+ const apiKey = this.context.env[this.target.apiKeyEnv]?.trim();
140
+ if (!apiKey) {
141
+ if (!this.warnedMissingKey) {
142
+ this.warnedMissingKey = true;
143
+ this.context.warn(`${this.context.mesh.id}:bugsnag:key`, `Bugsnag reporter is off: ${this.target.apiKeyEnv} is not set, so mesh failures will not reach Bugsnag`);
144
+ }
145
+ return;
146
+ }
147
+ const events = reports.flatMap((report) => this.transitions(report));
148
+ if (events.length === 0)
149
+ return;
150
+ await postOrThrow({
151
+ fetchImpl: this.context.fetchImpl,
152
+ url: this.target.url ?? config_js_1.DEFAULT_BUGSNAG_URL,
153
+ body: JSON.stringify({
154
+ apiKey,
155
+ payloadVersion: '5',
156
+ notifier: { name: version_js_1.PACKAGE_NAME, version: version_js_1.PACKAGE_VERSION, url: version_js_1.PACKAGE_URL },
157
+ events,
158
+ }),
159
+ headers: {
160
+ 'Content-Type': 'application/json',
161
+ 'Bugsnag-Api-Key': apiKey,
162
+ 'Bugsnag-Payload-Version': '5',
163
+ 'Bugsnag-Sent-At': new Date(this.context.now()).toISOString(),
164
+ },
165
+ timeoutMs: this.target.timeoutMs,
166
+ });
167
+ }
168
+ /** Updates the target's state and returns the event its transition warrants, if any. */
169
+ transitions(report) {
170
+ const key = targetUrl(report);
171
+ const previous = this.healthyByTarget.get(key);
172
+ this.healthyByTarget.set(key, report.healthy);
173
+ if (report.healthy) {
174
+ return previous === false ? [this.event(report, 'info', 'MeshProbeRecovered')] : [];
175
+ }
176
+ return previous === false ? [] : [this.event(report, 'error', 'MeshProbeUnhealthy')];
177
+ }
178
+ event(report, severity, errorClass) {
179
+ const request = `GET ${targetUrl(report)} from ${this.context.observer}`;
180
+ const message = severity === 'error'
181
+ ? `${request} returned ${report.result} after ${report.latency_ms} ms`
182
+ : `${request} recovered: ${report.result} in ${report.latency_ms} ms`;
183
+ return {
184
+ timestamp: report.at,
185
+ exceptions: [
186
+ {
187
+ errorClass,
188
+ message,
189
+ stacktrace: [{ file: 'unity-mesh/probe', lineNumber: 1, method: 'probe', type: 'node', inProject: false }],
190
+ },
191
+ ],
192
+ severity,
193
+ unhandled: false,
194
+ context: `mesh_probe ${report.mesh}`,
195
+ groupingHash: (0, uuid5_js_1.uuid5)(this.context.mesh.namespace, ['bugsnag', report.mesh, report.server, report.path].join('|')),
196
+ user: { id: this.context.observer },
197
+ app: { version: version_js_1.PACKAGE_VERSION, releaseStage: this.context.environment },
198
+ metaData: { mesh: { ...report } },
199
+ };
200
+ }
201
+ }
202
+ /** Gauge the `opentelemetry` reporter feeds: 1 when the last probe was healthy, else 0. */
203
+ exports.UP_GAUGE_NAME = 'mesh_probe_up';
204
+ /** Where the OpenTelemetry API keeps the providers registered in the process. */
205
+ const OTEL_GLOBAL_KEY = Symbol.for('opentelemetry.js.api.1');
206
+ const SEVERITY_INFO = 9;
207
+ const SEVERITY_ERROR = 17;
208
+ /**
209
+ * Loads `@opentelemetry/api`. It is an optional peer dependency: a process
210
+ * without it gets the reason once and sends nothing to OpenTelemetry.
211
+ *
212
+ * @param importer - Performs the dynamic import; tests substitute it
213
+ * @param unavailable - Receives the reason, at most once
214
+ * @returns The API, or `undefined` when it cannot be used
215
+ */
216
+ async function importOtelApi(importer, unavailable) {
217
+ let loaded;
218
+ try {
219
+ loaded = await importer();
220
+ }
221
+ catch (error) {
222
+ unavailable(`is not installed or could not be loaded (${error instanceof Error ? error.message : String(error)})`);
223
+ return undefined;
224
+ }
225
+ const candidate = loaded;
226
+ // An ESM build carries named exports; a CommonJS one arrives as `default`.
227
+ const chosen = candidate.logs && candidate.metrics ? candidate : candidate.default;
228
+ if (!hasLogsAndMeters(chosen)) {
229
+ unavailable('exposed neither logs nor meters');
230
+ return undefined;
231
+ }
232
+ return chosen;
233
+ }
234
+ function hasLogsAndMeters(api) {
235
+ return api?.logs !== undefined && api.metrics !== undefined;
236
+ }
237
+ /** Which OpenTelemetry signals have a provider registered in this process. */
238
+ function registeredOtelSignals() {
239
+ const global = globalThis[OTEL_GLOBAL_KEY];
240
+ return { logs: global?.logs !== undefined, metrics: global?.metrics !== undefined };
241
+ }
242
+ /** Report fields as OpenTelemetry attributes. A null status is left out; null is not an attribute value. */
243
+ function toOtelAttributes(report) {
244
+ const attributes = {};
245
+ for (const [key, value] of Object.entries(report)) {
246
+ if (value !== null)
247
+ attributes[key] = value;
248
+ }
249
+ return attributes;
250
+ }
251
+ /**
252
+ * Emits reports through the process's own OpenTelemetry providers.
253
+ *
254
+ * Every report becomes one log record, INFO when healthy and ERROR otherwise,
255
+ * with the report's fields as attributes. The reporter also feeds the
256
+ * {@link UP_GAUGE_NAME} gauge for each target it has seen. Where the host runs
257
+ * Azure Monitor's OpenTelemetry distro, both reach Application Insights, and
258
+ * through it the Log Analytics workspace, with no further setup.
259
+ *
260
+ * Nothing is sent when `@opentelemetry/api` is absent or no provider is
261
+ * registered; each case is reported once.
262
+ */
263
+ class OpenTelemetryReporter {
264
+ name = 'opentelemetry';
265
+ context;
266
+ upByTarget = new Map();
267
+ apiPromise;
268
+ logger;
269
+ gauge;
270
+ warnedUnregistered = false;
271
+ constructor(context) {
272
+ this.context = context;
273
+ }
274
+ async report(reports) {
275
+ if (reports.length === 0)
276
+ return;
277
+ this.apiPromise ??= (this.context.loadOtelApi ?? (() => this.importApi()))();
278
+ const api = await this.apiPromise;
279
+ if (!api)
280
+ return;
281
+ const signals = registeredOtelSignals();
282
+ if (!signals.logs && !signals.metrics) {
283
+ if (!this.warnedUnregistered) {
284
+ this.warnedUnregistered = true;
285
+ this.context.warn(`${this.context.mesh.id}:opentelemetry`, 'OpenTelemetry reporter has nowhere to send: no provider is registered in this process. Start telemetry before the probes.');
286
+ }
287
+ return;
288
+ }
289
+ for (const report of reports) {
290
+ this.upByTarget.set(`${report.server}${report.path}`, {
291
+ healthy: report.healthy,
292
+ attributes: { mesh: report.mesh, observer: report.observer, server: report.server, path: report.path },
293
+ });
294
+ }
295
+ if (signals.logs)
296
+ this.emitLogs(api, reports);
297
+ if (signals.metrics)
298
+ this.recordGauge(api);
299
+ }
300
+ importApi() {
301
+ return importOtelApi(() => import('@opentelemetry/api'), (message) => {
302
+ this.context.warn(`${this.context.mesh.id}:opentelemetry`, `OpenTelemetry reporter is off: @opentelemetry/api ${message}`);
303
+ });
304
+ }
305
+ emitLogs(api, reports) {
306
+ this.logger ??= api.logs.getLogger(version_js_1.PACKAGE_NAME, version_js_1.PACKAGE_VERSION);
307
+ for (const report of reports) {
308
+ this.logger.emit({
309
+ timestamp: new Date(report.at),
310
+ severityNumber: report.healthy ? SEVERITY_INFO : SEVERITY_ERROR,
311
+ severityText: report.healthy ? 'INFO' : 'ERROR',
312
+ body: describeProbe(report),
313
+ attributes: toOtelAttributes(report),
314
+ });
315
+ }
316
+ }
317
+ recordGauge(api) {
318
+ // Created, and given its single callback, the first time a round reports.
319
+ // A callback per round would make the metric reader observe every target again.
320
+ this.gauge ??= this.createGauge(api);
321
+ }
322
+ createGauge(api) {
323
+ const gauge = api.metrics.getMeter(version_js_1.PACKAGE_NAME, version_js_1.PACKAGE_VERSION).createObservableGauge(exports.UP_GAUGE_NAME, {
324
+ description: "1 when this observer's last probe of the target was healthy, 0 otherwise",
325
+ unit: '1',
326
+ });
327
+ gauge.addCallback((result) => {
328
+ for (const sample of this.upByTarget.values()) {
329
+ result.observe(sample.healthy ? 1 : 0, sample.attributes);
330
+ }
331
+ });
332
+ return gauge;
333
+ }
334
+ }
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DIAGNOSTIC_INTERVAL_MS = void 0;
4
+ exports.startMeshProbes = startMeshProbes;
5
+ exports.runProbeRound = runProbeRound;
6
+ const config_js_1 = require("./config.js");
7
+ const ids_js_1 = require("./ids.js");
8
+ const probe_js_1 = require("./probe.js");
9
+ const reporters_js_1 = require("./reporters.js");
10
+ const schedule_js_1 = require("./schedule.js");
11
+ const version_js_1 = require("./version.js");
12
+ /** How long a reporter problem stays quiet after being logged. */
13
+ exports.DIAGNOSTIC_INTERVAL_MS = 10 * 60_000;
14
+ function firstEnv(env, ...names) {
15
+ for (const name of names) {
16
+ const value = env[name]?.trim();
17
+ if (value)
18
+ return value;
19
+ }
20
+ return undefined;
21
+ }
22
+ function defaultLog(message, detail) {
23
+ if (detail) {
24
+ console.warn(message, detail);
25
+ }
26
+ else {
27
+ console.warn(message);
28
+ }
29
+ }
30
+ function defaultWriteLine(line, report) {
31
+ // The level split lets a stdout shipper that reads the console method file
32
+ // failures under a level of their own.
33
+ if (report.healthy) {
34
+ console.info(line);
35
+ }
36
+ else {
37
+ console.warn(line);
38
+ }
39
+ }
40
+ function isDefined(value) {
41
+ return value !== undefined;
42
+ }
43
+ function createEngine(options) {
44
+ const env = options.env ?? process.env;
45
+ const observer = (options.observer ?? firstEnv(env, 'WEBSITE_HOSTNAME', 'HOSTNAME') ?? 'unknown').replace(/[^A-Za-z0-9._:[\]-]+/g, '_');
46
+ const environment = options.environment ?? firstEnv(env, 'NODE_ENV') ?? 'unknown';
47
+ const now = options.now ?? Date.now;
48
+ const log = options.log ?? defaultLog;
49
+ const lastWarned = new Map();
50
+ const warn = (key, message, detail) => {
51
+ const nowMs = now();
52
+ const last = lastWarned.get(key);
53
+ if (last !== undefined && nowMs - last < exports.DIAGNOSTIC_INTERVAL_MS)
54
+ return;
55
+ lastWarned.set(key, nowMs);
56
+ log(`[unity-mesh] ${message}`, detail);
57
+ };
58
+ const entries = (0, config_js_1.toResolvedMeshes)((0, config_js_1.validateMeshConfig)(options.meshes))
59
+ .filter((mesh) => mesh.environments === undefined || mesh.environments.includes(environment))
60
+ .map((mesh) => ({ mesh, reporters: [], armed: false, timer: undefined, inFlight: undefined, controller: undefined }));
61
+ const engine = {
62
+ observer,
63
+ environment,
64
+ userAgent: `${version_js_1.PACKAGE_NAME}/${version_js_1.PACKAGE_VERSION} (${observer})`,
65
+ now,
66
+ fetchImpl: options.fetch ?? globalThis.fetch,
67
+ env,
68
+ writeLine: options.writeLine ?? defaultWriteLine,
69
+ entries,
70
+ warn,
71
+ };
72
+ const context = {
73
+ observer,
74
+ environment,
75
+ env,
76
+ fetchImpl: engine.fetchImpl,
77
+ now,
78
+ writeLine: engine.writeLine,
79
+ warn,
80
+ };
81
+ for (const entry of entries) {
82
+ const meshContext = { ...context, mesh: entry.mesh };
83
+ entry.reporters.push(...entry.mesh.reports.map((target) => (0, reporters_js_1.createReporter)(meshContext, target)));
84
+ }
85
+ return engine;
86
+ }
87
+ function toReport(engine, mesh, host, outcome, slotMs, finishedAtMs) {
88
+ return {
89
+ v: 1,
90
+ check_id: (0, ids_js_1.computeCheckId)(mesh.namespace, {
91
+ minute: slotMs,
92
+ server: host.server,
93
+ path: host.path,
94
+ result: outcome.result,
95
+ }),
96
+ mesh: mesh.id,
97
+ observer: engine.observer,
98
+ server: host.server,
99
+ scheme: host.scheme,
100
+ port: host.port ?? (host.scheme === 'https' ? 443 : 80),
101
+ path: host.path,
102
+ result: outcome.result,
103
+ healthy: outcome.healthy,
104
+ status: outcome.status,
105
+ latency_ms: outcome.latencyMs,
106
+ at: new Date(finishedAtMs).toISOString(),
107
+ minute: new Date(slotMs).toISOString(),
108
+ };
109
+ }
110
+ /**
111
+ * Probes every host of one mesh once and hands the reports to its reporters.
112
+ * A reporter failure is logged; a cancelled round reports nothing.
113
+ *
114
+ * @param engine - Process engine
115
+ * @param entry - Mesh to run
116
+ * @returns This round's reports; rejects only on a defect in this package
117
+ */
118
+ function runRound(engine, entry) {
119
+ const slotMs = (0, ids_js_1.floorToMinute)(engine.now());
120
+ const controller = new AbortController();
121
+ entry.controller = controller;
122
+ const round = (async () => {
123
+ const probed = await Promise.all(entry.mesh.hosts.map(async (host) => {
124
+ const outcome = await (0, probe_js_1.probe)(host, {
125
+ fetchImpl: engine.fetchImpl,
126
+ signal: controller.signal,
127
+ userAgent: engine.userAgent,
128
+ });
129
+ return controller.signal.aborted ? undefined : toReport(engine, entry.mesh, host, outcome, slotMs, engine.now());
130
+ }));
131
+ if (controller.signal.aborted)
132
+ return [];
133
+ const reports = probed.filter(isDefined);
134
+ for (const reporter of entry.reporters) {
135
+ try {
136
+ await reporter.report(reports);
137
+ }
138
+ catch (error) {
139
+ engine.warn(`${entry.mesh.id}:${reporter.name}`, `${reporter.name} reporter failed`, {
140
+ mesh: entry.mesh.id,
141
+ error: error instanceof Error ? error.message : String(error),
142
+ });
143
+ }
144
+ }
145
+ return reports;
146
+ })();
147
+ const tracked = round.finally(() => {
148
+ if (entry.controller === controller) {
149
+ entry.controller = undefined;
150
+ entry.inFlight = undefined;
151
+ }
152
+ });
153
+ entry.inFlight = tracked.then(() => undefined, () => undefined);
154
+ return tracked;
155
+ }
156
+ /** Schedules rounds on the mesh's interval until the entry is disarmed. */
157
+ function arm(engine, entry) {
158
+ if (entry.armed)
159
+ return;
160
+ entry.armed = true;
161
+ const schedule = () => {
162
+ if (!entry.armed)
163
+ return;
164
+ entry.timer = setTimeout(fire, (0, schedule_js_1.nextTickDelay)(entry.mesh.intervalMs, engine.now()));
165
+ };
166
+ const fire = () => {
167
+ entry.timer = undefined;
168
+ if (!entry.armed)
169
+ return;
170
+ if (entry.inFlight) {
171
+ schedule();
172
+ return;
173
+ }
174
+ void runRound(engine, entry)
175
+ .catch((error) => {
176
+ engine.warn(`${entry.mesh.id}:round`, 'probe round crashed', {
177
+ error: error instanceof Error ? error.message : String(error),
178
+ });
179
+ })
180
+ .finally(schedule);
181
+ };
182
+ schedule();
183
+ }
184
+ function disarm(entry) {
185
+ entry.armed = false;
186
+ if (entry.timer !== undefined) {
187
+ clearTimeout(entry.timer);
188
+ entry.timer = undefined;
189
+ }
190
+ entry.controller?.abort();
191
+ }
192
+ async function runAll(engine) {
193
+ const rounds = await Promise.all(engine.entries.map((entry) => runRound(engine, entry)));
194
+ return rounds.flat();
195
+ }
196
+ /**
197
+ * Starts probing: every mesh that applies to this environment runs on its own
198
+ * interval until `stop()` is called. Timers are ordinary ones, so they keep a
199
+ * bare script alive.
200
+ *
201
+ * @param options - Mesh list plus optional overrides. `meshes` may be the raw
202
+ * `unity-mesh` value or the output of `parseMeshConfig`
203
+ * @returns The running meshes
204
+ * @throws MeshConfigError when the mesh list is not usable
205
+ */
206
+ function startMeshProbes(options) {
207
+ const engine = createEngine(options);
208
+ for (const entry of engine.entries)
209
+ arm(engine, entry);
210
+ return {
211
+ get meshes() {
212
+ return engine.entries.map((entry) => entry.mesh.id);
213
+ },
214
+ run: () => runAll(engine),
215
+ stop: async () => {
216
+ for (const entry of engine.entries)
217
+ disarm(entry);
218
+ await Promise.all(engine.entries.map((entry) => entry.inFlight));
219
+ },
220
+ };
221
+ }
222
+ /**
223
+ * Runs one round on every mesh that applies to this environment, with no
224
+ * timers. Bugsnag's transition memory lives in the process, so a one-shot
225
+ * round reports every failure it sees as a new one.
226
+ *
227
+ * @param options - Mesh list plus optional overrides. `meshes` may be the raw
228
+ * `unity-mesh` value or the output of `parseMeshConfig`
229
+ * @returns This round's reports
230
+ * @throws MeshConfigError when the mesh list is not usable
231
+ */
232
+ async function runProbeRound(options) {
233
+ return runAll(createEngine(options));
234
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TICK_OFFSET_MS = void 0;
4
+ exports.nextTickDelay = nextTickDelay;
5
+ /** Seconds after each interval boundary that a round fires. */
6
+ exports.TICK_OFFSET_MS = 5_000;
7
+ /**
8
+ * Milliseconds until the next round. Rounds land on interval boundaries plus a
9
+ * fixed offset, so every server on a synced clock probes in the same second and
10
+ * their observations fall in one dedup minute.
11
+ *
12
+ * The result is always in `(0, intervalMs]`. A round that finishes in the same
13
+ * millisecond it fired must wait a whole interval, never refire at once.
14
+ *
15
+ * @param intervalMs - Milliseconds between rounds
16
+ * @param nowMs - Current time, milliseconds since the epoch
17
+ * @returns Delay to pass to `setTimeout`
18
+ */
19
+ function nextTickDelay(intervalMs, nowMs) {
20
+ const offset = exports.TICK_OFFSET_MS % intervalMs;
21
+ const next = (Math.floor((nowMs - offset) / intervalMs) + 1) * intervalMs + offset;
22
+ return next - nowMs;
23
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isUuid = isUuid;
4
+ exports.uuid5 = uuid5;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ /** True when `value` is a UUID in the 8-4-4-4-12 text form. */
8
+ function isUuid(value) {
9
+ return UUID_PATTERN.test(value);
10
+ }
11
+ /** Parses a UUID's 16 bytes from its text form. */
12
+ function uuidToBytes(uuid) {
13
+ const hex = uuid.replace(/-/g, '').toLowerCase();
14
+ const bytes = new Uint8Array(16);
15
+ for (let index = 0; index < bytes.length; index += 1) {
16
+ bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
17
+ }
18
+ return bytes;
19
+ }
20
+ /** Formats 16 bytes as the lowercase 8-4-4-4-12 text form. */
21
+ function bytesToUuid(bytes) {
22
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
23
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
24
+ }
25
+ /**
26
+ * RFC 4122 version 5 (name-based, SHA-1) UUID, identical to `uuid.v5` from the
27
+ * `uuid` package. Implemented here so the package has no runtime dependency and
28
+ * so the id recipe is small enough to port to a non-Node server.
29
+ *
30
+ * @param namespace - UUID naming the id space
31
+ * @param name - UTF-8 name to hash inside that space
32
+ * @returns Lowercase UUID v5 of `name` in `namespace`
33
+ */
34
+ function uuid5(namespace, name) {
35
+ if (!isUuid(namespace)) {
36
+ throw new TypeError(`uuid5: namespace must be a UUID, got "${namespace}"`);
37
+ }
38
+ const digest = (0, node_crypto_1.createHash)('sha1').update(uuidToBytes(namespace)).update(name, 'utf8').digest();
39
+ const bytes = new Uint8Array(digest.subarray(0, 16));
40
+ const versionByte = bytes[6] ?? 0;
41
+ const variantByte = bytes[8] ?? 0;
42
+ bytes[6] = (versionByte & 0x0f) | 0x50; // version 5
43
+ bytes[8] = (variantByte & 0x3f) | 0x80; // RFC 4122 variant
44
+ return bytesToUuid(bytes);
45
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PACKAGE_URL = exports.PACKAGE_VERSION = exports.PACKAGE_NAME = void 0;
4
+ /**
5
+ * Package identity. `PACKAGE_VERSION` is hand-maintained; tests/version.test.ts
6
+ * fails when it drifts from package.json.
7
+ */
8
+ exports.PACKAGE_NAME = '@glydeunity/unity-healthcheck-mesh';
9
+ exports.PACKAGE_VERSION = '0.1.0';
10
+ exports.PACKAGE_URL = 'https://github.com/Glyde-Inc/unity-healthcheck-mesh';