homebridge-pagerduty 2.1.1 → 2.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +1 -0
  3. package/SECURITY.md +2 -2
  4. package/config.schema.json +7 -4
  5. package/dist/controller.d.ts +29 -0
  6. package/dist/controller.js +102 -7
  7. package/dist/delivery/events.d.ts +7 -4
  8. package/dist/delivery/events.js +16 -4
  9. package/dist/delivery/health.d.ts +0 -6
  10. package/dist/delivery/health.js +0 -4
  11. package/dist/delivery/sender.d.ts +12 -1
  12. package/dist/delivery/sender.js +32 -9
  13. package/dist/devices/base-accessory.js +1 -1
  14. package/dist/diagnostics/collector.d.ts +5 -3
  15. package/dist/diagnostics/collector.js +25 -18
  16. package/dist/diagnostics/format.js +3 -0
  17. package/dist/dynamic-schema.d.ts +14 -1
  18. package/dist/dynamic-schema.js +23 -4
  19. package/dist/platform.d.ts +40 -5
  20. package/dist/platform.js +140 -17
  21. package/dist/settings.d.ts +49 -0
  22. package/dist/settings.js +51 -2
  23. package/dist/signals/config.d.ts +14 -1
  24. package/dist/signals/config.js +27 -0
  25. package/dist/signals/reader.d.ts +8 -0
  26. package/dist/signals/reader.js +18 -3
  27. package/dist/signals/schema.d.ts +8 -1
  28. package/dist/signals/schema.js +9 -2
  29. package/dist/state/desired.js +34 -5
  30. package/dist/state/instance-lock.d.ts +94 -0
  31. package/dist/state/instance-lock.js +214 -0
  32. package/dist/state/model.d.ts +2 -0
  33. package/dist/state/model.js +4 -2
  34. package/dist/state/mutations.d.ts +9 -1
  35. package/dist/state/mutations.js +29 -7
  36. package/dist/state/reconcile.d.ts +13 -1
  37. package/dist/state/reconcile.js +29 -5
  38. package/dist/state/store.d.ts +10 -2
  39. package/dist/state/store.js +20 -3
  40. package/dist/types/index.d.ts +29 -0
  41. package/dist/utils/startup-report.js +17 -2
  42. package/dist/utils/timing.d.ts +5 -27
  43. package/dist/utils/timing.js +5 -43
  44. package/dist/utils/validators.d.ts +21 -1
  45. package/dist/utils/validators.js +162 -30
  46. package/docs/EVENTS-API.md +8 -1
  47. package/docs/FEATURES.md +8 -4
  48. package/docs/README-DETAILED.md +52 -17
  49. package/docs/REVIEW.md +9 -7
  50. package/docs/SIGNALS-AGENT.md +1 -1
  51. package/docs/SIGNALS.md +6 -3
  52. package/package.json +10 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.2.0](https://github.com/tbaur/homebridge-pagerduty/compare/v2.1.1...v2.2.0) (2026-11-28)
4
+
5
+
6
+ ### Features
7
+
8
+ * damp flapping alerts and harden signal store and delivery ([#35](https://github.com/tbaur/homebridge-pagerduty/issues/35)) ([0de1561](https://github.com/tbaur/homebridge-pagerduty/commit/0de156109b8026817325940c38fcde5f93de6d80))
9
+
3
10
  ## [2.1.1](https://github.com/tbaur/homebridge-pagerduty/compare/v2.1.0...v2.1.1) (2026-10-26)
4
11
 
5
12
 
package/README.md CHANGED
@@ -32,6 +32,7 @@ These plugins write to the [signal store](docs/SIGNALS.md). Each one pages only
32
32
  - [homebridge-mynest](https://github.com/tbaur/homebridge-mynest)
33
33
  - [homebridge-myresideo](https://github.com/tbaur/homebridge-myresideo)
34
34
  - [homebridge-concert](https://github.com/tbaur/homebridge-concert)
35
+ - [homebridge-myairthings](https://github.com/tbaur/homebridge-myairthings)
35
36
 
36
37
  If you have integrated another plugin, [let me know](https://github.com/tbaur/homebridge-pagerduty/issues) and I will add it to this list.
37
38
 
package/SECURITY.md CHANGED
@@ -31,7 +31,7 @@ If a key leaks, delete the integration in PagerDuty, create a new one, and put t
31
31
  - **Escaped log values.** Alert names, summaries and anything written by another plugin pass through `forLog`, which escapes control characters and caps length. A value cannot inject a fake log line or terminal escape codes.
32
32
  - **Input validation.** Config is checked at startup. A missing key starts nothing. An unusable config disables the platform without unregistering accessories. A bad alert entry is held until it is fixed.
33
33
  - **Bounded I/O.** Separate connect and total timeouts on every request, a 64 KiB response cap, and no redirects followed.
34
- - **Owner-only files.** The plugin writes to one `homebridge-pagerduty` directory inside the Homebridge storage directory. That directory and the signal store's interface directory inside it are created with mode `0700`. The plugin also writes the settings screen file `.homebridge-pagerduty-v1.schema.json` next to it, where the Homebridge UI looks for it. The state file, the settings screen file and the signal store, including its `-wal` and `-shm` files, are created with mode `0600`. Store files found with a looser mode are tightened, and the plugin logs that.
34
+ - **Owner-only files.** The plugin writes to one `homebridge-pagerduty` directory inside the Homebridge storage directory. That directory and the signal store's interface directory inside it are created with mode `0700`. The plugin also writes the settings screen file `.homebridge-pagerduty-v1.schema.json` next to it, where the Homebridge UI looks for it. The state file, the instance lock, the settings screen file and the signal store, including its `-wal` and `-shm` files, are created with mode `0600`. Store files found with a looser mode are tightened, and the plugin logs that.
35
35
  - **No runtime dependencies.** HTTPS and SQLite come from Node.
36
36
  - **Dependencies audited.** CI runs `npm audit` on the runtime tree and OSV-Scanner on the full tree.
37
37
  - **A CI step rejects key-shaped strings** in the docs, source, tests, scripts, schema and workflows, so a key cannot be committed by accident. Tests build their fake keys at runtime, and the suite refuses to run if `PAGERDUTY_ROUTING_KEY` is set.
@@ -46,7 +46,7 @@ Other plugins can raise alerts by writing rows to `homebridge-pagerduty/signals-
46
46
  What the plugin does to keep the store safe to read:
47
47
 
48
48
  - The list of allowed plugins is part of the SQL query, so rows from other plugins cannot push allowed rows out of the read.
49
- - Names and text that other plugins write are validated and length-capped. On the settings screen, that text is only ever a field's starting value, never a title or description, which the Homebridge UI renders as markup.
49
+ - Names and text that other plugins write are validated and length-capped. On the settings screen, a plugin's free text is only ever a field's starting value, never a title or description, which the Homebridge UI renders as markup. Package and signal names do appear as section titles, and they are limited to lowercase letters, digits and `@/._-`, so they cannot carry markup.
50
50
  - The schema's `CHECK` constraints limit `plugin` to package-name characters and cap every text column. Rows are validated again when read, in case another plugin created the table differently.
51
51
  - A read error never clears an alert, so a damaged or locked store cannot silently resolve a page.
52
52
 
@@ -77,10 +77,11 @@
77
77
  "type": "string",
78
78
  "minLength": 1,
79
79
  "maxLength": 64,
80
+ "pattern": "^[A-Za-z0-9\\u00AA-\\uFFFF][A-Za-z0-9\\u00AA-\\uFFFF '&!._:;()/,-]*$",
80
81
  "examples": [
81
82
  "Leak"
82
83
  ],
83
- "description": "Each severity below adds a HomeKit switch named with this prefix and the severity, such as Leak Critical. It also labels this alert in the Homebridge log. Safe to rename."
84
+ "description": "Each severity below adds a HomeKit switch named with this prefix and the severity, such as Leak Critical. Start it with a letter or digit, and use only letters, digits, spaces and common punctuation. It also labels this alert in the Homebridge log. Safe to rename."
84
85
  },
85
86
  "summary": {
86
87
  "title": "PagerDuty Message",
@@ -149,7 +150,8 @@
149
150
  "type": "string",
150
151
  "default": "PagerDuty Maintenance",
151
152
  "maxLength": 64,
152
- "description": "The name that HomeKit shows. You can rename it at any time, and it keeps its room and automations."
153
+ "pattern": "^[A-Za-z0-9\\u00AA-\\uFFFF](?:[A-Za-z0-9\\u00AA-\\uFFFF '&!._:;()/,-]*[A-Za-z0-9\\u00AA-\\uFFFF])?$",
154
+ "description": "The name that HomeKit shows. Start and end it with a letter or digit. You can rename it at any time, and it keeps its room and automations."
153
155
  },
154
156
  "maxMinutes": {
155
157
  "title": "Turn Off After (minutes)",
@@ -174,14 +176,15 @@
174
176
  "title": "Delivery Fault Sensor",
175
177
  "type": "boolean",
176
178
  "default": true,
177
- "description": "Adds a contact sensor to HomeKit. It opens when an alert could not be delivered for two minutes, so HomeKit can tell you that nobody may have been paged."
179
+ "description": "Adds a contact sensor to HomeKit that opens when a page is not going out, so HomeKit can tell you that nobody may have been paged. It opens at once when PagerDuty rejects an event, when an alert could not be delivered for two minutes, and when the signal store has been unreadable for five minutes."
178
180
  },
179
181
  "deliveryFaultSensorName": {
180
182
  "title": "Sensor Name",
181
183
  "type": "string",
182
184
  "default": "PagerDuty Delivery",
183
185
  "maxLength": 64,
184
- "description": "The name that HomeKit shows. You can rename it at any time, and it keeps its room and automations."
186
+ "pattern": "^[A-Za-z0-9\\u00AA-\\uFFFF](?:[A-Za-z0-9\\u00AA-\\uFFFF '&!._:;()/,-]*[A-Za-z0-9\\u00AA-\\uFFFF])?$",
187
+ "description": "The name that HomeKit shows. Start and end it with a letter or digit. You can rename it at any time, and it keeps its room and automations."
185
188
  },
186
189
  "dryRun": {
187
190
  "title": "Dry Run",
@@ -55,6 +55,12 @@ export declare class AlertController {
55
55
  private readonly catalogListeners;
56
56
  private readonly abort;
57
57
  private readonly knownForeignWriters;
58
+ /** Plugins already named for writing an `updated_at` that is not Unix milliseconds. */
59
+ private readonly knownBadClocks;
60
+ /** When each target's recent triggers were accepted, oldest first. In memory only. */
61
+ private readonly recentTriggers;
62
+ /** Damped targets already named in the log. */
63
+ private readonly dampedWarned;
58
64
  private readonly outageGapKeys;
59
65
  private state;
60
66
  private plan;
@@ -106,6 +112,17 @@ export declare class AlertController {
106
112
  private recordRejected;
107
113
  /** Alerts that had an unsent trigger during the outage and are now closed with nothing delivered. */
108
114
  private countSuperseded;
115
+ /** Targets that sent {@link FLAP_MAX_TRIGGERS} triggers within the window. Forgets older triggers. */
116
+ private dampedKeys;
117
+ /** When a damped target's count falls below the limit: its oldest counted trigger leaves the window. */
118
+ private dampingEndsAt;
119
+ /**
120
+ * Warn once per spell of damping, and wake the sender when the first one
121
+ * ends. A spell lasts until the target's window clears, not until its held
122
+ * trigger goes away: a flapping alert closes and reopens within one spell,
123
+ * and must not warn each time.
124
+ */
125
+ private noteDamping;
109
126
  private handleDeadlines;
110
127
  private scheduleDeadline;
111
128
  private updateFault;
@@ -128,6 +145,18 @@ export declare class AlertController {
128
145
  private pollSignals;
129
146
  private updateCatalog;
130
147
  private applySignalRows;
148
+ /**
149
+ * Switches a row change sets: every configured switch, plus a held switch
150
+ * that still has saved state, which keeps following its row as before.
151
+ */
152
+ private drivenSwitches;
153
+ /** Name each plugin once whose `updated_at` had to be replaced by the clock. */
154
+ private reportBadClocks;
155
+ /**
156
+ * A busy store is routine and logs at debug, until it has been busy long
157
+ * enough to open the delivery sensor. Then it warns like any other cause, so
158
+ * the sensor never opens without a line that says why.
159
+ */
131
160
  private noteStoreUnavailable;
132
161
  private noteStoreAvailable;
133
162
  private warnAboutKeyChange;
@@ -31,7 +31,7 @@ const reconcile_1 = require("./state/reconcile");
31
31
  const store_1 = require("./state/store");
32
32
  const errors_1 = require("./utils/errors");
33
33
  const redact_1 = require("./utils/redact");
34
- const EMPTY_PLAN = { sendable: [], heldByMaintenance: [], rejected: [] };
34
+ const EMPTY_PLAN = { sendable: [], heldByMaintenance: [], damped: [], rejected: [] };
35
35
  /** Owns desired and delivered state and keeps PagerDuty in line with it. */
36
36
  class AlertController {
37
37
  options;
@@ -49,6 +49,12 @@ class AlertController {
49
49
  catalogListeners = [];
50
50
  abort = new AbortController();
51
51
  knownForeignWriters = new Set();
52
+ /** Plugins already named for writing an `updated_at` that is not Unix milliseconds. */
53
+ knownBadClocks = new Set();
54
+ /** When each target's recent triggers were accepted, oldest first. In memory only. */
55
+ recentTriggers = new Map();
56
+ /** Damped targets already named in the log. */
57
+ dampedWarned = new Set();
52
58
  outageGapKeys = new Set();
53
59
  state;
54
60
  plan = EMPTY_PLAN;
@@ -113,7 +119,11 @@ class AlertController {
113
119
  this.pendingRowSweep = this.allowed.length > 0;
114
120
  this.retainSweep();
115
121
  }
116
- (0, mutations_1.pruneSignals)(state, { allowed: this.allowed, switches: new Set(this.switches.keys()) });
122
+ (0, mutations_1.pruneSignals)(state, {
123
+ allowed: this.allowed,
124
+ switches: new Set(this.switches.keys()),
125
+ held: (refKey) => (0, config_1.isSwitchHeld)(this.config, refKey),
126
+ });
117
127
  this.forgetRemovedAlerts();
118
128
  if (state.maintenance.on && !this.config.maintenance.switch) {
119
129
  (0, mutations_1.applyMaintenance)(state, { on: false, at: this.now(), maxMinutes: this.config.maintenance.maxMinutes });
@@ -133,6 +143,7 @@ class AlertController {
133
143
  clearTimeout(this.timers.deadline);
134
144
  clearInterval(this.timers.poll);
135
145
  clearInterval(this.timers.health);
146
+ clearTimeout(this.timers.damping);
136
147
  this.abort.abort();
137
148
  await this.sender.stop();
138
149
  this.reader?.close();
@@ -212,6 +223,7 @@ class AlertController {
212
223
  openAlerts: Object.keys(this.requireState().delivered).length,
213
224
  pending: this.plan.sendable.length,
214
225
  heldByMaintenance: this.plan.heldByMaintenance.length,
226
+ damped: this.plan.damped.length,
215
227
  rejected: this.plan.rejected.length,
216
228
  deliveryFault: this.fault,
217
229
  storeOk: this.allowed.length === 0 ? null : this.storeUnreadableSince === null,
@@ -226,11 +238,14 @@ class AlertController {
226
238
  }
227
239
  reconcileNow() {
228
240
  const state = this.requireState();
241
+ const now = this.now();
242
+ const damped = this.dampedKeys(now);
229
243
  const plan = (0, reconcile_1.reconcile)({
230
244
  desired: (0, desired_1.computeDesired)(this.config, state),
231
245
  delivered: state.delivered,
232
246
  rejected: state.rejected,
233
247
  maintenanceOn: state.maintenance.on,
248
+ damped,
234
249
  hashContext: {
235
250
  routingKeyFingerprint: state.routingKeyFingerprint ?? '',
236
251
  region: this.config.region,
@@ -238,7 +253,8 @@ class AlertController {
238
253
  },
239
254
  });
240
255
  this.pruneRejections(plan);
241
- this.health.observe(plan, this.now());
256
+ this.noteDamping(plan, damped, now);
257
+ this.health.observe(plan, now);
242
258
  if (this.sender.inOutage) {
243
259
  for (const action of plan.sendable) {
244
260
  if (action.kind === 'trigger') {
@@ -283,6 +299,7 @@ class AlertController {
283
299
  recordDelivered(action) {
284
300
  const state = this.requireState();
285
301
  if (action.kind === 'trigger') {
302
+ this.recentTriggers.set(action.key, [...(this.recentTriggers.get(action.key) ?? []), this.now()]);
286
303
  const existing = state.delivered[action.key];
287
304
  state.delivered[action.key] = {
288
305
  dedupKey: action.dedupKey,
@@ -318,6 +335,58 @@ class AlertController {
318
335
  this.outageGapKeys.clear();
319
336
  return count;
320
337
  }
338
+ // --- Flap damping ----------------------------------------------------------------
339
+ /** Targets that sent {@link FLAP_MAX_TRIGGERS} triggers within the window. Forgets older triggers. */
340
+ dampedKeys(now) {
341
+ const damped = new Set();
342
+ for (const [key, times] of this.recentTriggers) {
343
+ const recent = times.filter((time) => now - time < settings_1.FLAP_WINDOW_MS);
344
+ if (recent.length === 0) {
345
+ this.recentTriggers.delete(key);
346
+ continue;
347
+ }
348
+ this.recentTriggers.set(key, recent);
349
+ if (recent.length >= settings_1.FLAP_MAX_TRIGGERS) {
350
+ damped.add(key);
351
+ }
352
+ }
353
+ return damped;
354
+ }
355
+ /** When a damped target's count falls below the limit: its oldest counted trigger leaves the window. */
356
+ dampingEndsAt(key) {
357
+ const times = this.recentTriggers.get(key) ?? [];
358
+ return (times[times.length - settings_1.FLAP_MAX_TRIGGERS] ?? 0) + settings_1.FLAP_WINDOW_MS;
359
+ }
360
+ /**
361
+ * Warn once per spell of damping, and wake the sender when the first one
362
+ * ends. A spell lasts until the target's window clears, not until its held
363
+ * trigger goes away: a flapping alert closes and reopens within one spell,
364
+ * and must not warn each time.
365
+ */
366
+ noteDamping(plan, damped, now) {
367
+ for (const key of this.dampedWarned) {
368
+ if (!damped.has(key)) {
369
+ this.dampedWarned.delete(key);
370
+ }
371
+ }
372
+ let soonest;
373
+ for (const key of plan.damped) {
374
+ const endsAt = this.dampingEndsAt(key);
375
+ soonest = Math.min(soonest ?? endsAt, endsAt);
376
+ if (!this.dampedWarned.has(key)) {
377
+ this.dampedWarned.add(key);
378
+ const minutes = Math.max(1, Math.ceil((endsAt - now) / 60_000));
379
+ this.log.warn(`${(0, redact_1.forLog)(this.labelFor(key))}: ${settings_1.FLAP_MAX_TRIGGERS} triggers in ${settings_1.FLAP_WINDOW_MS / 60_000} min; `
380
+ + `holding new triggers for up to ${minutes} min, then sending the current state. Resolves still go out`);
381
+ }
382
+ }
383
+ clearTimeout(this.timers.damping);
384
+ this.timers.damping = undefined;
385
+ if (soonest !== undefined && !this.stopped) {
386
+ this.timers.damping = setTimeout(() => this.kick(), Math.max(0, soonest - now));
387
+ this.timers.damping.unref();
388
+ }
389
+ }
321
390
  // --- Timers --------------------------------------------------------------------
322
391
  handleDeadlines() {
323
392
  const state = this.requireState();
@@ -458,7 +527,8 @@ class AlertController {
458
527
  }
459
528
  applySignalRows(result) {
460
529
  for (const entry of result.catalog) {
461
- if (!this.allowed.includes(entry.plugin) && !this.knownForeignWriters.has(entry.plugin)) {
530
+ const named = this.knownForeignWriters.has(entry.plugin) || (0, config_1.isSignalHeld)(this.config, (0, schema_1.signalRefKey)(entry));
531
+ if (!this.allowed.includes(entry.plugin) && !named) {
462
532
  this.knownForeignWriters.add(entry.plugin);
463
533
  this.log.info(`signal store: ${(0, redact_1.forLog)(entry.plugin)} writes signals; allow it under Plugin Signals to page for it`);
464
534
  }
@@ -474,9 +544,10 @@ class AlertController {
474
544
  rows: result.rows,
475
545
  complete: result.complete,
476
546
  allowed: this.allowed,
477
- switches: new Set(this.switches.keys()),
547
+ switches: this.drivenSwitches(state),
478
548
  now: this.now(),
479
549
  });
550
+ this.reportBadClocks(applied.timeOutOfRange);
480
551
  const swept = this.pendingRowSweep && this.sweepClosedRows();
481
552
  this.pendingRowSweep = false;
482
553
  if (swept) {
@@ -490,11 +561,35 @@ class AlertController {
490
561
  this.kick();
491
562
  }
492
563
  }
564
+ /**
565
+ * Switches a row change sets: every configured switch, plus a held switch
566
+ * that still has saved state, which keeps following its row as before.
567
+ */
568
+ drivenSwitches(state) {
569
+ const held = Object.keys(state.switches).filter((refKey) => (0, config_1.isSwitchHeld)(this.config, refKey));
570
+ return new Set([...this.switches.keys(), ...held]);
571
+ }
572
+ /** Name each plugin once whose `updated_at` had to be replaced by the clock. */
573
+ reportBadClocks(refKeys) {
574
+ for (const key of refKeys) {
575
+ const plugin = key.slice(0, key.lastIndexOf('/'));
576
+ if (!this.knownBadClocks.has(plugin)) {
577
+ this.knownBadClocks.add(plugin);
578
+ this.log.info(`signal store: ${(0, redact_1.forLog)(plugin)} wrote an updated_at that is not a time in Unix milliseconds; using the time it was read`);
579
+ }
580
+ }
581
+ }
582
+ /**
583
+ * A busy store is routine and logs at debug, until it has been busy long
584
+ * enough to open the delivery sensor. Then it warns like any other cause, so
585
+ * the sensor never opens without a line that says why.
586
+ */
493
587
  noteStoreUnavailable(reason) {
494
588
  const now = this.now();
495
589
  this.storeUnreadableSince ??= now;
496
590
  const line = `signal store unavailable (${reason}); keeping the last rows read`;
497
- if (reason !== 'busy' && now - this.lastStoreWarnAt >= settings_1.OUTAGE_REWARN_MS) {
591
+ const quietBusy = reason === 'busy' && now - this.storeUnreadableSince < settings_1.SIGNAL_STORE_FAULT_AFTER_MS;
592
+ if (!quietBusy && now - this.lastStoreWarnAt >= settings_1.OUTAGE_REWARN_MS) {
498
593
  this.lastStoreWarnAt = now;
499
594
  this.log.warn(line);
500
595
  }
@@ -550,7 +645,7 @@ class AlertController {
550
645
  const desired = (0, desired_1.computeDesired)(this.config, state);
551
646
  let swept = false;
552
647
  for (const target of desired.values()) {
553
- if (target.key.startsWith('signal:') && !target.open && state.delivered[target.key] === undefined) {
648
+ if (target.key.startsWith(model_1.SIGNAL_TARGET_PREFIX) && !target.open && !target.held && state.delivered[target.key] === undefined) {
554
649
  state.delivered[target.key] = { dedupKey: target.dedupKey, severity: 'info', openedAt: this.now() };
555
650
  swept = true;
556
651
  }
@@ -39,13 +39,16 @@ export declare function buildEvent(action: Action, input: {
39
39
  source: string;
40
40
  }): TriggerEvent | ResolveEvent;
41
41
  /** How the sender treats a response status. */
42
- export type StatusClass = 'delivered' | 'rejected' | 'rateLimited' | 'retry';
42
+ export type StatusClass = 'delivered' | 'rejected' | 'rateLimited' | 'refused' | 'retry';
43
43
  /**
44
44
  * Classify a status.
45
45
  *
46
- * `2xx` is delivered (anything but `202` also warns). `408` and `429` wait
47
- * minutes. Any other `4xx` is PagerDuty refusing the event, which no retry
48
- * will change. `3xx` (never followed), `5xx` and anything odd are retried.
46
+ * `2xx` is delivered (anything but `202` also warns). `400`, `413` and `422`
47
+ * reject the event, and no retry will change that. `408` and `429` wait
48
+ * minutes. Any other `4xx` is not something PagerDuty documents. It more
49
+ * likely comes from a proxy or an edge in front of PagerDuty than from the
50
+ * event, so it is retried on the same slow backoff as a rate limit rather than
51
+ * dropped. `3xx` (never followed), `5xx` and anything odd are retried.
49
52
  */
50
53
  export declare function classifyStatus(status: number): StatusClass;
51
54
  /**
@@ -39,22 +39,34 @@ function buildEvent(action, input) {
39
39
  },
40
40
  };
41
41
  }
42
+ /**
43
+ * Statuses that say the event itself is wrong, so sending the same body again
44
+ * cannot help. PagerDuty documents only `400`; `413` and `422` say the same
45
+ * thing about the body.
46
+ */
47
+ const EVENT_REJECTED = new Set([400, 413, 422]);
42
48
  /**
43
49
  * Classify a status.
44
50
  *
45
- * `2xx` is delivered (anything but `202` also warns). `408` and `429` wait
46
- * minutes. Any other `4xx` is PagerDuty refusing the event, which no retry
47
- * will change. `3xx` (never followed), `5xx` and anything odd are retried.
51
+ * `2xx` is delivered (anything but `202` also warns). `400`, `413` and `422`
52
+ * reject the event, and no retry will change that. `408` and `429` wait
53
+ * minutes. Any other `4xx` is not something PagerDuty documents. It more
54
+ * likely comes from a proxy or an edge in front of PagerDuty than from the
55
+ * event, so it is retried on the same slow backoff as a rate limit rather than
56
+ * dropped. `3xx` (never followed), `5xx` and anything odd are retried.
48
57
  */
49
58
  function classifyStatus(status) {
50
59
  if (status >= 200 && status < 300) {
51
60
  return 'delivered';
52
61
  }
62
+ if (EVENT_REJECTED.has(status)) {
63
+ return 'rejected';
64
+ }
53
65
  if (status === 408 || status === 429) {
54
66
  return 'rateLimited';
55
67
  }
56
68
  if (status >= 400 && status < 500) {
57
- return 'rejected';
69
+ return 'refused';
58
70
  }
59
71
  return 'retry';
60
72
  }
@@ -34,10 +34,4 @@ export declare class DeliveryHealth {
34
34
  now: number;
35
35
  storeUnreadableSince: number | null;
36
36
  }): DeliveryFaultCause[];
37
- /** True when {@link causes} is not empty. */
38
- isFault(input: {
39
- plan: Plan;
40
- now: number;
41
- storeUnreadableSince: number | null;
42
- }): boolean;
43
37
  }
@@ -58,9 +58,5 @@ class DeliveryHealth {
58
58
  }
59
59
  return causes;
60
60
  }
61
- /** True when {@link causes} is not empty. */
62
- isFault(input) {
63
- return this.causes(input).length > 0;
64
- }
65
61
  }
66
62
  exports.DeliveryHealth = DeliveryHealth;
@@ -65,12 +65,23 @@ export declare class Sender {
65
65
  get inOutage(): boolean;
66
66
  /** Something may have changed. Never cuts a backoff short. */
67
67
  wake(): void;
68
- /** Stop sending. An in-flight request is left to finish; nothing new starts. */
68
+ /**
69
+ * Stop sending. Nothing new starts, and a backoff is cut short. This does
70
+ * not cancel a request in flight: the controller aborts it, and an answer
71
+ * that still arrives is recorded as usual.
72
+ */
69
73
  stop(): Promise<void>;
70
74
  private run;
71
75
  /** Send one action and return how long to wait before the next. */
72
76
  private attempt;
73
77
  private logDelivered;
78
+ /**
79
+ * Record a failed attempt and return the wait before the next one.
80
+ *
81
+ * `fast` is a network or server failure: full jitter from 5 seconds. A rate
82
+ * limit, and a `4xx` that PagerDuty does not document, wait minutes, with
83
+ * equal jitter and any `Retry-After` honoured.
84
+ */
74
85
  private failed;
75
86
  private recovered;
76
87
  }
@@ -25,6 +25,12 @@ const redact_1 = require("../utils/redact");
25
25
  const retry_after_1 = require("../utils/retry-after");
26
26
  const timing_1 = require("../utils/timing");
27
27
  const events_1 = require("./events");
28
+ /** How each kind of failure reads in the outage line. */
29
+ const FAILURE_WORDS = {
30
+ fast: 'is not reachable',
31
+ rateLimited: 'is rate limiting events',
32
+ refused: 'refused the request',
33
+ };
28
34
  /** Equal jitter: at least half the window, so a `429` never retries at once. */
29
35
  function equalJitterDelayMs(input) {
30
36
  const exponent = Math.min(Math.max(input.attempt - 1, 0), 16);
@@ -67,7 +73,11 @@ class Sender {
67
73
  this.loop = this.run();
68
74
  }
69
75
  }
70
- /** Stop sending. An in-flight request is left to finish; nothing new starts. */
76
+ /**
77
+ * Stop sending. Nothing new starts, and a backoff is cut short. This does
78
+ * not cancel a request in flight: the controller aborts it, and an answer
79
+ * that still arrives is recorded as usual.
80
+ */
71
81
  async stop() {
72
82
  this.stopped = true;
73
83
  this.backoff?.interrupt();
@@ -107,8 +117,13 @@ class Sender {
107
117
  response = await this.deps.post(action);
108
118
  }
109
119
  catch (error) {
120
+ if (this.stopped) {
121
+ // Aborted by shutdown. PagerDuty was not unreachable, so say nothing
122
+ // and count nothing; the next start sends whatever is still due.
123
+ return 0;
124
+ }
110
125
  this.deps.onRequest?.(this.now() - started, false);
111
- return this.failed(action, { detail: (0, errors_1.describeError)(error), rateLimited: false });
126
+ return this.failed(action, { detail: (0, errors_1.describeError)(error), backoff: 'fast' });
112
127
  }
113
128
  const outcome = (0, events_1.classifyStatus)(response.status);
114
129
  this.deps.onRequest?.(this.now() - started, outcome === 'delivered');
@@ -123,13 +138,14 @@ class Sender {
123
138
  this.deps.onRejected(action, (0, events_1.rejectionReason)(response.status, response.body));
124
139
  return 0;
125
140
  case 'rateLimited':
141
+ case 'refused':
126
142
  return this.failed(action, {
127
143
  detail: `HTTP ${response.status}`,
128
- rateLimited: true,
144
+ backoff: outcome,
129
145
  retryAfterMs: (0, retry_after_1.parseRetryAfterMs)(response.headers['retry-after'], settings_1.MAX_RETRY_AFTER_MS, this.now),
130
146
  });
131
147
  default:
132
- return this.failed(action, { detail: `HTTP ${response.status}`, rateLimited: false });
148
+ return this.failed(action, { detail: `HTTP ${response.status}`, backoff: 'fast' });
133
149
  }
134
150
  }
135
151
  logDelivered(action, status) {
@@ -139,21 +155,28 @@ class Sender {
139
155
  this.deps.log.warn(`PagerDuty answered ${status} rather than 202; treated as accepted`);
140
156
  }
141
157
  }
158
+ /**
159
+ * Record a failed attempt and return the wait before the next one.
160
+ *
161
+ * `fast` is a network or server failure: full jitter from 5 seconds. A rate
162
+ * limit, and a `4xx` that PagerDuty does not document, wait minutes, with
163
+ * equal jitter and any `Retry-After` honoured.
164
+ */
142
165
  failed(action, failure) {
143
166
  this.failures += 1;
144
167
  if (action.kind === 'trigger') {
145
168
  this.attemptedDuringOutage.add(action.key);
146
169
  }
147
- const delayMs = failure.rateLimited
148
- ? Math.max(failure.retryAfterMs ?? 0, equalJitterDelayMs({
170
+ const delayMs = failure.backoff === 'fast'
171
+ ? (0, timing_1.backoffDelayMs)({ attempt: this.failures, baseMs: settings_1.BACKOFF_BASE_MS, maxMs: settings_1.BACKOFF_MAX_MS, random: this.random })
172
+ : Math.max(failure.retryAfterMs ?? 0, equalJitterDelayMs({
149
173
  attempt: this.failures,
150
174
  baseMs: settings_1.RATE_LIMIT_BACKOFF_BASE_MS,
151
175
  maxMs: settings_1.BACKOFF_MAX_MS,
152
176
  random: this.random,
153
- }))
154
- : (0, timing_1.backoffDelayMs)({ attempt: this.failures, baseMs: settings_1.BACKOFF_BASE_MS, maxMs: settings_1.BACKOFF_MAX_MS, random: this.random });
177
+ }));
155
178
  const now = this.now();
156
- const what = failure.rateLimited ? 'is rate limiting events' : 'is not reachable';
179
+ const what = FAILURE_WORDS[failure.backoff];
157
180
  const line = `PagerDuty ${what} (${failure.detail}); retrying in ${Math.round(delayMs / 1_000)}s`;
158
181
  if (this.outageSince === null || now - this.lastOutageWarnAt >= settings_1.OUTAGE_REWARN_MS) {
159
182
  this.outageSince ??= now;
@@ -53,7 +53,7 @@ class BaseAccessory {
53
53
  /** Throw the HAP error that shows No Response when unavailable. */
54
54
  requireAvailable() {
55
55
  if (this.unavailable) {
56
- throw new this.host.api.hap.HapStatusError(-70402 /* this.host.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE */);
56
+ throw new this.host.api.hap.HapStatusError(this.host.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE);
57
57
  }
58
58
  }
59
59
  /**
@@ -7,9 +7,11 @@
7
7
  * @fileoverview Opt-in diagnostics collector.
8
8
  *
9
9
  * It reads only in-memory state through `readGauges`; it never touches the
10
- * network and never sees the routing key.
10
+ * network. The config it echoes is the validated one, so the echo shows what
11
+ * is running rather than what was typed, and the routing key appears only as
12
+ * present.
11
13
  */
12
- import type { DeliveryGauges, DiagnosticsSnapshot, PagerDutyPlatformConfig } from '../types';
14
+ import type { DeliveryGauges, DiagnosticsSnapshot, ResolvedConfig } from '../types';
13
15
  /** Health classification result. */
14
16
  export interface HealthRollup {
15
17
  health: 'healthy' | 'degraded';
@@ -17,7 +19,7 @@ export interface HealthRollup {
17
19
  }
18
20
  interface CollectorOptions {
19
21
  pluginVersion: string;
20
- config: PagerDutyPlatformConfig;
22
+ config: ResolvedConfig;
21
23
  now?: () => number;
22
24
  }
23
25
  /** Accumulates diagnostics counters and renders heartbeat and snapshot reports. */
@@ -8,10 +8,13 @@
8
8
  * @fileoverview Opt-in diagnostics collector.
9
9
  *
10
10
  * It reads only in-memory state through `readGauges`; it never touches the
11
- * network and never sees the routing key.
11
+ * network. The config it echoes is the validated one, so the echo shows what
12
+ * is running rather than what was typed, and the routing key appears only as
13
+ * present.
12
14
  */
13
15
  Object.defineProperty(exports, "__esModule", { value: true });
14
16
  exports.DiagnosticsCollector = void 0;
17
+ const config_1 = require("../signals/config");
15
18
  /** Maximum number of recent request latencies retained for percentile math. */
16
19
  const LATENCY_WINDOW = 200;
17
20
  /** Accumulates diagnostics counters and renders heartbeat and snapshot reports. */
@@ -100,24 +103,28 @@ class DiagnosticsCollector {
100
103
  }
101
104
  }
102
105
  exports.DiagnosticsCollector = DiagnosticsCollector;
103
- /** The routing key and every alert name and summary stay out of the echo. */
106
+ function isAnythingHeld(config) {
107
+ const { all, plugins, switches } = config.heldSignals;
108
+ return all || plugins.length > 0 || switches.plugins.length > 0 || switches.signals.length > 0;
109
+ }
110
+ /**
111
+ * The settings in effect, with the routing key and every alert name and
112
+ * summary left out. Values are the validated ones: a `diagnosticsInterval` of
113
+ * 5 echoes the 30 that runs.
114
+ */
104
115
  function redactConfig(config) {
105
- const options = config.options;
106
116
  return {
107
- routingKey: typeof config.routingKey === 'string' && config.routingKey.length > 0,
108
- region: config.region ?? 'us',
109
- alerts: Array.isArray(config.alerts) ? config.alerts.length : 0,
110
- maintenanceSwitch: config.maintenance?.switch === true,
111
- signalPluginsAllowed: countAllowedPlugins(config.signals),
112
- deliveryFaultSensor: options?.deliveryFaultSensor !== false,
113
- dryRun: options?.dryRun === true,
114
- diagnosticsInterval: options?.diagnosticsInterval ?? 0,
115
- structuredLogs: options?.structuredLogs === true,
117
+ routingKey: config.routingKey.length > 0,
118
+ region: config.region,
119
+ source: config.source,
120
+ alerts: config.alerts.length,
121
+ heldAlerts: config.heldAlertIds.length,
122
+ maintenanceSwitch: config.maintenance.switch,
123
+ signalPluginsAllowed: (0, config_1.allowedPlugins)(config).length,
124
+ signalsHeld: isAnythingHeld(config),
125
+ deliveryFaultSensor: config.options.deliveryFaultSensor,
126
+ dryRun: config.options.dryRun,
127
+ diagnosticsInterval: config.options.diagnosticsInterval,
128
+ structuredLogs: config.options.structuredLogs,
116
129
  };
117
130
  }
118
- function countAllowedPlugins(signals) {
119
- if (typeof signals !== 'object' || signals === null) {
120
- return 0;
121
- }
122
- return Object.values(signals).filter((entry) => entry?.allow === true).length;
123
- }
@@ -45,6 +45,9 @@ function formatDiagnosticLine(report) {
45
45
  `pending ${delivery.pending}`,
46
46
  `held ${delivery.heldByMaintenance}`,
47
47
  ];
48
+ if (delivery.damped > 0) {
49
+ parts.push(`damped ${delivery.damped}`);
50
+ }
48
51
  if (delivery.storeOk !== null) {
49
52
  parts.push(`store ${delivery.storeOk ? 'ok' : 'unreadable'}`);
50
53
  }