@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,408 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MeshConfigError = exports.FETCH_BLOCKED_PORTS = exports.DEFAULT_BUGSNAG_URL = exports.DEFAULT_REPORT_TIMEOUT_MS = exports.DEFAULT_PROBE_TIMEOUT_MS = exports.DEFAULT_INTERVAL_SECONDS = exports.PAYLOAD_FORMATS = void 0;
4
+ exports.parseMeshConfig = parseMeshConfig;
5
+ exports.validateMeshConfig = validateMeshConfig;
6
+ exports.toResolvedMeshes = toResolvedMeshes;
7
+ const ids_js_1 = require("./ids.js");
8
+ const uuid5_js_1 = require("./uuid5.js");
9
+ exports.PAYLOAD_FORMATS = [
10
+ 'victorialogs/stdout',
11
+ 'victorialogs',
12
+ 'bugsnag',
13
+ 'opentelemetry',
14
+ ];
15
+ exports.DEFAULT_INTERVAL_SECONDS = 60;
16
+ exports.DEFAULT_PROBE_TIMEOUT_MS = 5_000;
17
+ exports.DEFAULT_REPORT_TIMEOUT_MS = 10_000;
18
+ /** Bugsnag's notify endpoint for dashboards on app.bugsnag.com. */
19
+ exports.DEFAULT_BUGSNAG_URL = 'https://notify.bugsnag.com';
20
+ const MAX_INTERVAL_SECONDS = 86_400;
21
+ const MIN_TIMEOUT_MS = 250;
22
+ const MAX_TIMEOUT_MS = 60_000;
23
+ const MESH_KEYS = ['mesh-id', 'namespace', 'environments', 'interval-seconds', 'hosts', 'report'];
24
+ const HOST_KEYS = ['server', 'path', 'scheme', 'port', 'expect', 'timeout-ms'];
25
+ const REPORT_KEYS = [
26
+ 'target-url',
27
+ 'payload-format',
28
+ 'timeout-ms',
29
+ 'api-key-env',
30
+ 'username-env',
31
+ 'password-env',
32
+ ];
33
+ const MESH_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
34
+ const HOSTNAME_PATTERN = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;
35
+ const ENV_NAME_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
36
+ const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '[::1]'];
37
+ /**
38
+ * Ports Node's fetch refuses outright (the Fetch standard's blocked-port list).
39
+ * A probe can never reach them, so they are rejected at validation; otherwise
40
+ * such a target would report NETWORK for as long as it is configured.
41
+ * Derived from Node 24; a test checks it against the running Node.
42
+ */
43
+ exports.FETCH_BLOCKED_PORTS = new Set([
44
+ 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102, 103, 104, 109, 110,
45
+ 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,
46
+ 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061,
47
+ 6000, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697, 10080,
48
+ ]);
49
+ /** Thrown by `parseMeshConfig` and `startMeshProbes` when the config is not usable. */
50
+ class MeshConfigError extends Error {
51
+ /** Every problem found, each naming the config path it concerns. */
52
+ problems;
53
+ constructor(problems) {
54
+ super(`Invalid unity-mesh config (${problems.length} problem${problems.length === 1 ? '' : 's'}):\n` +
55
+ ` - ${problems.join('\n - ')}`);
56
+ this.name = 'MeshConfigError';
57
+ this.problems = problems;
58
+ }
59
+ }
60
+ exports.MeshConfigError = MeshConfigError;
61
+ function isPlainObject(value) {
62
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
63
+ }
64
+ function isNonEmptyStringArray(value) {
65
+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === 'string' && item.length > 0);
66
+ }
67
+ function isStatusCode(value) {
68
+ return Number.isInteger(value) && value >= 100 && value <= 599;
69
+ }
70
+ function isPayloadFormat(value) {
71
+ return exports.PAYLOAD_FORMATS.includes(value);
72
+ }
73
+ /** Names a value's JSON shape for error messages. */
74
+ function describe(value) {
75
+ if (value === undefined)
76
+ return 'nothing';
77
+ if (value === null)
78
+ return 'null';
79
+ if (Array.isArray(value))
80
+ return 'an array';
81
+ return typeof value === 'object' ? 'an object' : typeof value === 'string' ? JSON.stringify(value) : `a ${typeof value}`;
82
+ }
83
+ /**
84
+ * Checks `value` is an object holding only `keys`, reporting anything else.
85
+ * @returns The object, or `undefined` when it is not one
86
+ */
87
+ function shape(value, path, keys, problems) {
88
+ if (!isPlainObject(value)) {
89
+ problems.push(`${path}: must be an object, got ${describe(value)}`);
90
+ return undefined;
91
+ }
92
+ for (const key of Object.keys(value)) {
93
+ if (!keys.includes(key)) {
94
+ problems.push(`${path}.${key}: unknown key (allowed: ${keys.join(', ')})`);
95
+ }
96
+ }
97
+ return value;
98
+ }
99
+ /** Reads an optional string. An absent key is not a problem; a wrong type is. */
100
+ function text(object, key, path, problems) {
101
+ const value = object[key];
102
+ if (value === undefined)
103
+ return undefined;
104
+ if (typeof value !== 'string') {
105
+ problems.push(`${path}.${key}: must be a string, got ${describe(value)}`);
106
+ return undefined;
107
+ }
108
+ return value;
109
+ }
110
+ /** Reads a required string. */
111
+ function requiredText(object, key, path, problems) {
112
+ const value = text(object, key, path, problems);
113
+ if (object[key] === undefined) {
114
+ problems.push(`${path}.${key}: is required`);
115
+ return undefined;
116
+ }
117
+ return value;
118
+ }
119
+ /** Reads an optional integer inside `[min, max]`. An absent key is not a problem. */
120
+ function integer(object, key, path, problems, min, max) {
121
+ const value = object[key];
122
+ if (value === undefined)
123
+ return undefined;
124
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
125
+ problems.push(`${path}.${key}: must be a number, got ${describe(value)}`);
126
+ return undefined;
127
+ }
128
+ if (!Number.isInteger(value) || value < min || value > max) {
129
+ problems.push(`${path}.${key}: must be an integer from ${min} to ${max}, got ${value}`);
130
+ return undefined;
131
+ }
132
+ return value;
133
+ }
134
+ /**
135
+ * Validates the `unity-mesh` value and fills in defaults.
136
+ *
137
+ * The result keeps the config's own keys, so it can be passed straight back as
138
+ * the `meshes` option of `startMeshProbes` or `runProbeRound`.
139
+ *
140
+ * @param input - Value of the `unity-mesh` key
141
+ * @returns One validated mesh per entry, in config order
142
+ * @throws MeshConfigError listing every problem found
143
+ */
144
+ function parseMeshConfig(input) {
145
+ return validateMeshConfig(input);
146
+ }
147
+ /** Validates the `unity-mesh` value, keeping the defaults the runtime relies on. */
148
+ function validateMeshConfig(input) {
149
+ if (!Array.isArray(input)) {
150
+ throw new MeshConfigError(['unity-mesh: must be an array of meshes']);
151
+ }
152
+ const problems = [];
153
+ const meshes = [];
154
+ input.forEach((entry, index) => {
155
+ const mesh = parseMesh(entry, `unity-mesh[${index}]`, problems);
156
+ if (mesh)
157
+ meshes.push(mesh);
158
+ });
159
+ const seen = new Set();
160
+ for (const mesh of meshes) {
161
+ if (seen.has(mesh['mesh-id'])) {
162
+ problems.push(`unity-mesh: mesh-id "${mesh['mesh-id']}" is listed more than once`);
163
+ }
164
+ seen.add(mesh['mesh-id']);
165
+ }
166
+ if (problems.length > 0)
167
+ throw new MeshConfigError(problems);
168
+ return meshes;
169
+ }
170
+ /** Folds validated config into the shape the runtime reads. */
171
+ function toResolvedMeshes(meshes) {
172
+ return meshes.map((mesh) => ({
173
+ id: mesh['mesh-id'],
174
+ namespace: mesh.namespace ?? (0, ids_js_1.defaultMeshNamespace)(mesh['mesh-id']),
175
+ environments: mesh.environments,
176
+ intervalMs: mesh['interval-seconds'] * 1000,
177
+ hosts: mesh.hosts.map((host) => ({
178
+ server: host.server,
179
+ path: host.path,
180
+ scheme: host.scheme,
181
+ port: host.port,
182
+ expect: host.expect,
183
+ timeoutMs: host['timeout-ms'],
184
+ })),
185
+ reports: mesh.report.map((target) => ({
186
+ format: target['payload-format'],
187
+ url: target['target-url'],
188
+ timeoutMs: target['timeout-ms'],
189
+ apiKeyEnv: target['api-key-env'],
190
+ usernameEnv: target['username-env'],
191
+ passwordEnv: target['password-env'],
192
+ })),
193
+ }));
194
+ }
195
+ function parseMesh(entry, path, problems) {
196
+ const object = shape(entry, path, MESH_KEYS, problems);
197
+ if (!object)
198
+ return undefined;
199
+ const id = requiredText(object, 'mesh-id', path, problems);
200
+ if (id !== undefined && !MESH_ID_PATTERN.test(id)) {
201
+ problems.push(`${path}.mesh-id: must match ${MESH_ID_PATTERN} (lowercase letters, digits, dot, underscore, hyphen; 64 characters at most), got "${id}"`);
202
+ }
203
+ const namespace = text(object, 'namespace', path, problems);
204
+ if (namespace !== undefined && !(0, uuid5_js_1.isUuid)(namespace)) {
205
+ problems.push(`${path}.namespace: must be a UUID, got "${namespace}"`);
206
+ }
207
+ const environmentsRaw = object['environments'];
208
+ let environments;
209
+ if (environmentsRaw !== undefined) {
210
+ if (isNonEmptyStringArray(environmentsRaw)) {
211
+ environments = [...environmentsRaw];
212
+ }
213
+ else {
214
+ problems.push(`${path}.environments: must be a non-empty array of environment names, got ${describe(environmentsRaw)}`);
215
+ }
216
+ }
217
+ const intervalSeconds = integer(object, 'interval-seconds', path, problems, 60, MAX_INTERVAL_SECONDS);
218
+ if (intervalSeconds !== undefined && intervalSeconds % 60 !== 0) {
219
+ problems.push(`${path}.interval-seconds: must be a multiple of 60, got ${intervalSeconds}`);
220
+ }
221
+ const hosts = parseHosts(object['hosts'], path, problems);
222
+ const report = parseReports(object['report'], path, problems);
223
+ if (id === undefined || hosts === undefined || report === undefined)
224
+ return undefined;
225
+ return {
226
+ 'mesh-id': id,
227
+ ...(namespace === undefined ? {} : { namespace }),
228
+ ...(environments === undefined ? {} : { environments }),
229
+ 'interval-seconds': intervalSeconds ?? exports.DEFAULT_INTERVAL_SECONDS,
230
+ hosts,
231
+ report,
232
+ };
233
+ }
234
+ function parseHosts(raw, path, problems) {
235
+ if (!Array.isArray(raw) || raw.length === 0) {
236
+ problems.push(`${path}.hosts: must be an array with at least one host, got ${describe(raw)}`);
237
+ return undefined;
238
+ }
239
+ const hosts = [];
240
+ raw.forEach((entry, index) => {
241
+ const host = parseHost(entry, `${path}.hosts[${index}]`, problems);
242
+ if (host)
243
+ hosts.push(host);
244
+ });
245
+ const targets = new Set();
246
+ for (const host of hosts) {
247
+ const target = `${host.server}${host.path}`;
248
+ if (targets.has(target)) {
249
+ problems.push(`${path}.hosts: "${target}" is listed more than once; both entries would report under one check_id`);
250
+ }
251
+ targets.add(target);
252
+ }
253
+ return hosts.length > 0 ? hosts : undefined;
254
+ }
255
+ function parseHost(entry, path, problems) {
256
+ const object = shape(entry, path, HOST_KEYS, problems);
257
+ if (!object)
258
+ return undefined;
259
+ const server = requiredText(object, 'server', path, problems)?.toLowerCase();
260
+ if (server !== undefined && !HOSTNAME_PATTERN.test(server)) {
261
+ problems.push(`${path}.server: must be a bare hostname (no scheme, port or path), got "${server}"`);
262
+ }
263
+ const requestPath = text(object, 'path', path, problems) ?? '/';
264
+ if (!requestPath.startsWith('/') || /[\s|]/.test(requestPath)) {
265
+ problems.push(`${path}.path: must start with "/" and contain no whitespace or "|", got "${requestPath}"`);
266
+ }
267
+ const scheme = text(object, 'scheme', path, problems) ?? 'https';
268
+ if (scheme !== 'https' && scheme !== 'http') {
269
+ problems.push(`${path}.scheme: must be "https" or "http", got "${scheme}"`);
270
+ return undefined;
271
+ }
272
+ const port = integer(object, 'port', path, problems, 1, 65_535);
273
+ if (port !== undefined && exports.FETCH_BLOCKED_PORTS.has(port)) {
274
+ problems.push(`${path}.port: ${port} is a port fetch refuses to connect to; probe the target on another port`);
275
+ return undefined;
276
+ }
277
+ const expect = parseExpect(object['expect'], path, problems);
278
+ const timeoutMs = integer(object, 'timeout-ms', path, problems, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS) ?? exports.DEFAULT_PROBE_TIMEOUT_MS;
279
+ if (server === undefined)
280
+ return undefined;
281
+ return {
282
+ server,
283
+ path: requestPath,
284
+ scheme,
285
+ ...(port === undefined ? {} : { port }),
286
+ expect: expect ?? [200],
287
+ 'timeout-ms': timeoutMs,
288
+ };
289
+ }
290
+ function parseExpect(raw, path, problems) {
291
+ if (raw === undefined)
292
+ return undefined;
293
+ const list = Array.isArray(raw) ? raw : [raw];
294
+ if (list.length === 0) {
295
+ problems.push(`${path}.expect: must list at least one status code`);
296
+ return undefined;
297
+ }
298
+ const codes = [];
299
+ for (const [index, item] of list.entries()) {
300
+ if (!isStatusCode(item)) {
301
+ problems.push(`${path}.expect${Array.isArray(raw) ? `[${index}]` : ''}: must be an HTTP status code from 100 to 599, got ${describe(item)}`);
302
+ return undefined;
303
+ }
304
+ if (!codes.includes(item))
305
+ codes.push(item);
306
+ }
307
+ return codes;
308
+ }
309
+ function parseReports(raw, path, problems) {
310
+ const isList = Array.isArray(raw);
311
+ const list = isList ? raw : [raw];
312
+ if (list.length === 0) {
313
+ problems.push(`${path}.report: must list at least one report target`);
314
+ return undefined;
315
+ }
316
+ const reports = [];
317
+ list.forEach((entry, index) => {
318
+ const report = parseReport(entry, isList ? `${path}.report[${index}]` : `${path}.report`, problems);
319
+ if (report)
320
+ reports.push(report);
321
+ });
322
+ return reports.length === list.length ? reports : undefined;
323
+ }
324
+ function parseReport(entry, path, problems) {
325
+ const object = shape(entry, path, REPORT_KEYS, problems);
326
+ if (!object)
327
+ return undefined;
328
+ const format = requiredText(object, 'payload-format', path, problems);
329
+ if (format === undefined)
330
+ return undefined;
331
+ if (!isPayloadFormat(format)) {
332
+ problems.push(`${path}.payload-format: must be one of ${exports.PAYLOAD_FORMATS.join(', ')}, got ${describe(format)}`);
333
+ return undefined;
334
+ }
335
+ const url = parseReportUrl(format, object['target-url'], path, problems);
336
+ const timeoutMs = integer(object, 'timeout-ms', path, problems, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS) ?? exports.DEFAULT_REPORT_TIMEOUT_MS;
337
+ const envNames = {
338
+ apiKeyEnv: parseEnvName(object['api-key-env'], `${path}.api-key-env`, problems) ?? 'BUGSNAG_API_KEY',
339
+ usernameEnv: parseEnvName(object['username-env'], `${path}.username-env`, problems) ?? 'VICTORIA_LOGS_USERNAME',
340
+ passwordEnv: parseEnvName(object['password-env'], `${path}.password-env`, problems) ?? 'VICTORIA_LOGS_PASSWORD',
341
+ };
342
+ if (url === undefined && format !== 'victorialogs/stdout' && format !== 'opentelemetry')
343
+ return undefined;
344
+ return {
345
+ ...(url === undefined ? {} : { 'target-url': url }),
346
+ 'payload-format': format,
347
+ 'timeout-ms': timeoutMs,
348
+ 'api-key-env': envNames.apiKeyEnv,
349
+ 'username-env': envNames.usernameEnv,
350
+ 'password-env': envNames.passwordEnv,
351
+ };
352
+ }
353
+ function parseEnvName(raw, path, problems) {
354
+ if (raw === undefined)
355
+ return undefined;
356
+ if (typeof raw !== 'string' || !ENV_NAME_PATTERN.test(raw)) {
357
+ problems.push(`${path}: must be an environment variable name (${ENV_NAME_PATTERN}), got ${describe(raw)}`);
358
+ return undefined;
359
+ }
360
+ return raw;
361
+ }
362
+ /** Validates a report destination for its format. */
363
+ function parseReportUrl(format, raw, path, problems) {
364
+ if (format === 'opentelemetry') {
365
+ if (raw !== undefined) {
366
+ problems.push(`${path}.target-url: must be omitted when payload-format is opentelemetry; reports go through this process's OpenTelemetry providers`);
367
+ }
368
+ return undefined;
369
+ }
370
+ if (format === 'victorialogs/stdout') {
371
+ if (raw !== undefined && raw !== 'stdout') {
372
+ problems.push(`${path}.target-url: must be "stdout" or omitted when payload-format is victorialogs/stdout, got ${describe(raw)}`);
373
+ }
374
+ return undefined;
375
+ }
376
+ if (raw === undefined) {
377
+ if (format === 'bugsnag')
378
+ return exports.DEFAULT_BUGSNAG_URL;
379
+ problems.push(`${path}.target-url: is required when payload-format is victorialogs`);
380
+ return undefined;
381
+ }
382
+ if (typeof raw !== 'string') {
383
+ problems.push(`${path}.target-url: must be a URL, got ${describe(raw)}`);
384
+ return undefined;
385
+ }
386
+ let url;
387
+ try {
388
+ url = new URL(raw);
389
+ }
390
+ catch {
391
+ problems.push(`${path}.target-url: must be an absolute URL, got "${raw}"`);
392
+ return undefined;
393
+ }
394
+ const loopback = LOOPBACK_HOSTS.includes(url.hostname);
395
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
396
+ problems.push(`${path}.target-url: must use https (http is allowed only on loopback), got "${url.protocol}"`);
397
+ return undefined;
398
+ }
399
+ if (url.username !== '' || url.password !== '') {
400
+ problems.push(`${path}.target-url: must not embed credentials; name the *-env keys instead`);
401
+ return undefined;
402
+ }
403
+ if (url.search !== '' || url.hash !== '') {
404
+ problems.push(`${path}.target-url: must not include a query string or fragment`);
405
+ return undefined;
406
+ }
407
+ return url.toString();
408
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MINUTE_MS = exports.ROOT_NAMESPACE = void 0;
4
+ exports.defaultMeshNamespace = defaultMeshNamespace;
5
+ exports.floorToMinute = floorToMinute;
6
+ exports.checkIdName = checkIdName;
7
+ exports.computeCheckId = computeCheckId;
8
+ const uuid5_js_1 = require("./uuid5.js");
9
+ /**
10
+ * Root of every default mesh namespace: uuid5(DNS namespace,
11
+ * 'unity-mesh.glydeunity.com'). Pinned so all servers derive the same ids from
12
+ * a `mesh-id` alone.
13
+ */
14
+ exports.ROOT_NAMESPACE = 'b024abd5-11e8-56a6-87c3-4009cb18a821';
15
+ exports.MINUTE_MS = 60_000;
16
+ /**
17
+ * Namespace a mesh hashes in. Servers only agree on ids when they share it, so
18
+ * an explicit `namespace` must be identical in every server's config.
19
+ *
20
+ * @param meshId - Mesh identifier
21
+ * @returns uuid5 of the mesh id under {@link ROOT_NAMESPACE}
22
+ */
23
+ function defaultMeshNamespace(meshId) {
24
+ return (0, uuid5_js_1.uuid5)(exports.ROOT_NAMESPACE, meshId);
25
+ }
26
+ /**
27
+ * Floors a timestamp to the start of its minute.
28
+ * @param epochMs - Milliseconds since the epoch
29
+ * @returns Milliseconds since the epoch at the minute boundary
30
+ */
31
+ function floorToMinute(epochMs) {
32
+ return Math.floor(epochMs / exports.MINUTE_MS) * exports.MINUTE_MS;
33
+ }
34
+ /**
35
+ * The name `check_id` hashes: minute, target and result, joined with `|`. The
36
+ * observer is deliberately absent, so every server that saw the same result in
37
+ * the same minute derives the same id.
38
+ *
39
+ * @param input - Minute (epoch ms) plus target and result
40
+ * @returns Name string in the canonical order
41
+ */
42
+ function checkIdName(input) {
43
+ return [new Date(input.minute).toISOString(), input.server, input.path, input.result].join('|');
44
+ }
45
+ /**
46
+ * Mesh-wide dedup id of one observation.
47
+ * @param namespace - Mesh namespace
48
+ * @param input - Minute (epoch ms) plus target and result
49
+ * @returns uuid5 of {@link checkIdName}
50
+ */
51
+ function computeCheckId(namespace, input) {
52
+ return (0, uuid5_js_1.uuid5)(namespace, checkIdName(input));
53
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PACKAGE_VERSION = exports.PACKAGE_URL = exports.PACKAGE_NAME = exports.uuid5 = exports.isUuid = exports.nextTickDelay = exports.TICK_OFFSET_MS = exports.startMeshProbes = exports.runProbeRound = exports.probe = exports.classifyFailure = exports.buildTargetUrl = exports.floorToMinute = exports.defaultMeshNamespace = exports.computeCheckId = exports.checkIdName = exports.ROOT_NAMESPACE = exports.MINUTE_MS = exports.parseMeshConfig = exports.PAYLOAD_FORMATS = exports.MeshConfigError = exports.DEFAULT_REPORT_TIMEOUT_MS = exports.DEFAULT_PROBE_TIMEOUT_MS = exports.DEFAULT_INTERVAL_SECONDS = exports.DEFAULT_BUGSNAG_URL = void 0;
4
+ var config_js_1 = require("./config.js");
5
+ Object.defineProperty(exports, "DEFAULT_BUGSNAG_URL", { enumerable: true, get: function () { return config_js_1.DEFAULT_BUGSNAG_URL; } });
6
+ Object.defineProperty(exports, "DEFAULT_INTERVAL_SECONDS", { enumerable: true, get: function () { return config_js_1.DEFAULT_INTERVAL_SECONDS; } });
7
+ Object.defineProperty(exports, "DEFAULT_PROBE_TIMEOUT_MS", { enumerable: true, get: function () { return config_js_1.DEFAULT_PROBE_TIMEOUT_MS; } });
8
+ Object.defineProperty(exports, "DEFAULT_REPORT_TIMEOUT_MS", { enumerable: true, get: function () { return config_js_1.DEFAULT_REPORT_TIMEOUT_MS; } });
9
+ Object.defineProperty(exports, "MeshConfigError", { enumerable: true, get: function () { return config_js_1.MeshConfigError; } });
10
+ Object.defineProperty(exports, "PAYLOAD_FORMATS", { enumerable: true, get: function () { return config_js_1.PAYLOAD_FORMATS; } });
11
+ Object.defineProperty(exports, "parseMeshConfig", { enumerable: true, get: function () { return config_js_1.parseMeshConfig; } });
12
+ var ids_js_1 = require("./ids.js");
13
+ Object.defineProperty(exports, "MINUTE_MS", { enumerable: true, get: function () { return ids_js_1.MINUTE_MS; } });
14
+ Object.defineProperty(exports, "ROOT_NAMESPACE", { enumerable: true, get: function () { return ids_js_1.ROOT_NAMESPACE; } });
15
+ Object.defineProperty(exports, "checkIdName", { enumerable: true, get: function () { return ids_js_1.checkIdName; } });
16
+ Object.defineProperty(exports, "computeCheckId", { enumerable: true, get: function () { return ids_js_1.computeCheckId; } });
17
+ Object.defineProperty(exports, "defaultMeshNamespace", { enumerable: true, get: function () { return ids_js_1.defaultMeshNamespace; } });
18
+ Object.defineProperty(exports, "floorToMinute", { enumerable: true, get: function () { return ids_js_1.floorToMinute; } });
19
+ var probe_js_1 = require("./probe.js");
20
+ Object.defineProperty(exports, "buildTargetUrl", { enumerable: true, get: function () { return probe_js_1.buildTargetUrl; } });
21
+ Object.defineProperty(exports, "classifyFailure", { enumerable: true, get: function () { return probe_js_1.classifyFailure; } });
22
+ Object.defineProperty(exports, "probe", { enumerable: true, get: function () { return probe_js_1.probe; } });
23
+ var runner_js_1 = require("./runner.js");
24
+ Object.defineProperty(exports, "runProbeRound", { enumerable: true, get: function () { return runner_js_1.runProbeRound; } });
25
+ Object.defineProperty(exports, "startMeshProbes", { enumerable: true, get: function () { return runner_js_1.startMeshProbes; } });
26
+ var schedule_js_1 = require("./schedule.js");
27
+ Object.defineProperty(exports, "TICK_OFFSET_MS", { enumerable: true, get: function () { return schedule_js_1.TICK_OFFSET_MS; } });
28
+ Object.defineProperty(exports, "nextTickDelay", { enumerable: true, get: function () { return schedule_js_1.nextTickDelay; } });
29
+ var uuid5_js_1 = require("./uuid5.js");
30
+ Object.defineProperty(exports, "isUuid", { enumerable: true, get: function () { return uuid5_js_1.isUuid; } });
31
+ Object.defineProperty(exports, "uuid5", { enumerable: true, get: function () { return uuid5_js_1.uuid5; } });
32
+ var version_js_1 = require("./version.js");
33
+ Object.defineProperty(exports, "PACKAGE_NAME", { enumerable: true, get: function () { return version_js_1.PACKAGE_NAME; } });
34
+ Object.defineProperty(exports, "PACKAGE_URL", { enumerable: true, get: function () { return version_js_1.PACKAGE_URL; } });
35
+ Object.defineProperty(exports, "PACKAGE_VERSION", { enumerable: true, get: function () { return version_js_1.PACKAGE_VERSION; } });
@@ -0,0 +1 @@
1
+ { "type": "commonjs" }
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.classifyFailure = classifyFailure;
4
+ exports.buildTargetUrl = buildTargetUrl;
5
+ exports.probe = probe;
6
+ const node_perf_hooks_1 = require("node:perf_hooks");
7
+ const DNS_CODES = ['ENOTFOUND', 'EAI_AGAIN', 'EAI_NONAME', 'EAI_FAIL', 'EAI_NODATA'];
8
+ const MAX_CAUSE_DEPTH = 5;
9
+ /**
10
+ * Folds a thrown fetch error into the closed failure vocabulary, so the result
11
+ * stays low-cardinality inside `check_id`. Node's fetch wraps the socket error
12
+ * (`TypeError: fetch failed`) and hangs the real cause off `.cause`, so the
13
+ * whole cause chain is read.
14
+ *
15
+ * @param error - Value thrown by `fetch`
16
+ * @returns The failure class
17
+ */
18
+ function classifyFailure(error) {
19
+ for (let link = error, depth = 0; typeof link === 'object' && link !== null && depth < MAX_CAUSE_DEPTH; depth += 1) {
20
+ const name = 'name' in link && typeof link.name === 'string' ? link.name : '';
21
+ const code = 'code' in link && typeof link.code === 'string' ? link.code.toUpperCase() : '';
22
+ if (name === 'AbortError')
23
+ return 'ABORTED';
24
+ if (name === 'TimeoutError' || code.includes('TIMEOUT'))
25
+ return 'TIMEOUT';
26
+ if (DNS_CODES.includes(code))
27
+ return 'DNS';
28
+ if (code === 'ECONNREFUSED')
29
+ return 'REFUSED';
30
+ if (code.startsWith('ERR_TLS') || code.startsWith('ERR_SSL') || code.includes('CERT'))
31
+ return 'TLS';
32
+ if (code === 'ECONNRESET' || code === 'EPIPE')
33
+ return 'RESET';
34
+ link = 'cause' in link ? link.cause : undefined;
35
+ }
36
+ return 'NETWORK';
37
+ }
38
+ /**
39
+ * Builds the URL a host is probed at.
40
+ * @param host - Resolved host
41
+ * @returns Absolute URL
42
+ */
43
+ function buildTargetUrl(host) {
44
+ const authority = host.port === undefined ? host.server : `${host.server}:${host.port}`;
45
+ return `${host.scheme}://${authority}${host.path}`;
46
+ }
47
+ /**
48
+ * GETs a host once. Never throws: a failed attempt is an outcome with a
49
+ * failure class as its result. Redirects are reported, not followed, so a
50
+ * bounce to a login page cannot read as healthy. The body is never read.
51
+ *
52
+ * @param host - Resolved host
53
+ * @param deps - Fetch client, abort signal and user agent
54
+ * @returns What the probe saw
55
+ */
56
+ async function probe(host, deps) {
57
+ const startedAt = node_perf_hooks_1.performance.now();
58
+ const timeout = AbortSignal.timeout(host.timeoutMs);
59
+ try {
60
+ const response = await deps.fetchImpl(buildTargetUrl(host), {
61
+ method: 'GET',
62
+ redirect: 'manual',
63
+ headers: { 'user-agent': deps.userAgent },
64
+ signal: deps.signal ? AbortSignal.any([deps.signal, timeout]) : timeout,
65
+ });
66
+ // Releasing the unread body returns the socket to the pool.
67
+ void response.body?.cancel().catch(() => undefined);
68
+ return {
69
+ result: String(response.status),
70
+ healthy: host.expect.includes(response.status),
71
+ status: response.status,
72
+ latencyMs: elapsedMs(startedAt),
73
+ };
74
+ }
75
+ catch (error) {
76
+ return { result: classifyFailure(error), healthy: false, status: null, latencyMs: elapsedMs(startedAt) };
77
+ }
78
+ }
79
+ function elapsedMs(startedAt) {
80
+ return Math.max(0, Math.round(node_perf_hooks_1.performance.now() - startedAt));
81
+ }