@smthrs/notifications 0.0.0-stage → 1.0.0-rc.13

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 (146) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/LICENSE +21 -0
  3. package/README.md +93 -2
  4. package/dist/cjs/AlertPolicy.d.ts +284 -0
  5. package/dist/cjs/AlertPolicy.d.ts.map +1 -0
  6. package/dist/cjs/AlertPolicy.js +124 -0
  7. package/dist/cjs/AlertPolicy.js.map +7 -0
  8. package/dist/cjs/AlertRuntime.d.ts +90 -0
  9. package/dist/cjs/AlertRuntime.d.ts.map +1 -0
  10. package/dist/cjs/AlertRuntime.js +166 -0
  11. package/dist/cjs/AlertRuntime.js.map +7 -0
  12. package/dist/cjs/AlertSink.d.ts +101 -0
  13. package/dist/cjs/AlertSink.d.ts.map +1 -0
  14. package/dist/cjs/AlertSink.js +44 -0
  15. package/dist/cjs/AlertSink.js.map +7 -0
  16. package/dist/cjs/Alerts.d.ts +57 -0
  17. package/dist/cjs/Alerts.d.ts.map +1 -0
  18. package/dist/cjs/Alerts.js +46 -0
  19. package/dist/cjs/Alerts.js.map +7 -0
  20. package/dist/cjs/Notification.d.ts +214 -0
  21. package/dist/cjs/Notification.d.ts.map +1 -0
  22. package/dist/cjs/Notification.js +62 -0
  23. package/dist/cjs/Notification.js.map +7 -0
  24. package/dist/cjs/NotificationEvent.d.ts +214 -0
  25. package/dist/cjs/NotificationEvent.d.ts.map +1 -0
  26. package/dist/cjs/NotificationEvent.js +84 -0
  27. package/dist/cjs/NotificationEvent.js.map +7 -0
  28. package/dist/cjs/NotificationQueue.d.ts +194 -0
  29. package/dist/cjs/NotificationQueue.d.ts.map +1 -0
  30. package/dist/cjs/NotificationQueue.js +477 -0
  31. package/dist/cjs/NotificationQueue.js.map +7 -0
  32. package/dist/cjs/NotificationState.d.ts +169 -0
  33. package/dist/cjs/NotificationState.d.ts.map +1 -0
  34. package/dist/cjs/NotificationState.js +110 -0
  35. package/dist/cjs/NotificationState.js.map +7 -0
  36. package/dist/cjs/Projection.d.ts +30 -0
  37. package/dist/cjs/Projection.d.ts.map +1 -0
  38. package/dist/cjs/Projection.js +53 -0
  39. package/dist/cjs/Projection.js.map +7 -0
  40. package/dist/cjs/SteerPayload.d.ts +177 -0
  41. package/dist/cjs/SteerPayload.d.ts.map +1 -0
  42. package/dist/cjs/SteerPayload.js +61 -0
  43. package/dist/cjs/SteerPayload.js.map +7 -0
  44. package/dist/cjs/index.d.ts +41 -0
  45. package/dist/cjs/index.d.ts.map +1 -0
  46. package/dist/cjs/index.js +47 -0
  47. package/dist/cjs/index.js.map +7 -0
  48. package/dist/cjs/internal/foldCache.d.ts +36 -0
  49. package/dist/cjs/internal/foldCache.d.ts.map +1 -0
  50. package/dist/cjs/internal/foldCache.js +54 -0
  51. package/dist/cjs/internal/foldCache.js.map +7 -0
  52. package/dist/cjs/internal/replay.d.ts +22 -0
  53. package/dist/cjs/internal/replay.d.ts.map +1 -0
  54. package/dist/cjs/internal/replay.js +46 -0
  55. package/dist/cjs/internal/replay.js.map +7 -0
  56. package/dist/cjs/layerWebhook.d.ts +60 -0
  57. package/dist/cjs/layerWebhook.d.ts.map +1 -0
  58. package/dist/cjs/layerWebhook.js +145 -0
  59. package/dist/cjs/layerWebhook.js.map +7 -0
  60. package/dist/cjs/package.json +1 -0
  61. package/dist/esm/AlertPolicy.d.ts +284 -0
  62. package/dist/esm/AlertPolicy.d.ts.map +1 -0
  63. package/dist/esm/AlertPolicy.js +284 -0
  64. package/dist/esm/AlertPolicy.js.map +1 -0
  65. package/dist/esm/AlertRuntime.d.ts +90 -0
  66. package/dist/esm/AlertRuntime.d.ts.map +1 -0
  67. package/dist/esm/AlertRuntime.js +191 -0
  68. package/dist/esm/AlertRuntime.js.map +1 -0
  69. package/dist/esm/AlertSink.d.ts +101 -0
  70. package/dist/esm/AlertSink.d.ts.map +1 -0
  71. package/dist/esm/AlertSink.js +63 -0
  72. package/dist/esm/AlertSink.js.map +1 -0
  73. package/dist/esm/Alerts.d.ts +57 -0
  74. package/dist/esm/Alerts.d.ts.map +1 -0
  75. package/dist/esm/Alerts.js +57 -0
  76. package/dist/esm/Alerts.js.map +1 -0
  77. package/dist/esm/Notification.d.ts +214 -0
  78. package/dist/esm/Notification.d.ts.map +1 -0
  79. package/dist/esm/Notification.js +121 -0
  80. package/dist/esm/Notification.js.map +1 -0
  81. package/dist/esm/NotificationEvent.d.ts +214 -0
  82. package/dist/esm/NotificationEvent.d.ts.map +1 -0
  83. package/dist/esm/NotificationEvent.js +158 -0
  84. package/dist/esm/NotificationEvent.js.map +1 -0
  85. package/dist/esm/NotificationQueue.d.ts +194 -0
  86. package/dist/esm/NotificationQueue.d.ts.map +1 -0
  87. package/dist/esm/NotificationQueue.js +625 -0
  88. package/dist/esm/NotificationQueue.js.map +1 -0
  89. package/dist/esm/NotificationState.d.ts +169 -0
  90. package/dist/esm/NotificationState.d.ts.map +1 -0
  91. package/dist/esm/NotificationState.js +191 -0
  92. package/dist/esm/NotificationState.js.map +1 -0
  93. package/dist/esm/Projection.d.ts +30 -0
  94. package/dist/esm/Projection.d.ts.map +1 -0
  95. package/dist/esm/Projection.js +47 -0
  96. package/dist/esm/Projection.js.map +1 -0
  97. package/dist/esm/SteerPayload.d.ts +177 -0
  98. package/dist/esm/SteerPayload.d.ts.map +1 -0
  99. package/dist/esm/SteerPayload.js +139 -0
  100. package/dist/esm/SteerPayload.js.map +1 -0
  101. package/dist/esm/index.d.ts +41 -0
  102. package/dist/esm/index.d.ts.map +1 -0
  103. package/dist/esm/index.js +41 -0
  104. package/dist/esm/index.js.map +1 -0
  105. package/dist/esm/internal/foldCache.d.ts +36 -0
  106. package/dist/esm/internal/foldCache.d.ts.map +1 -0
  107. package/dist/esm/internal/foldCache.js +58 -0
  108. package/dist/esm/internal/foldCache.js.map +1 -0
  109. package/dist/esm/internal/replay.d.ts +22 -0
  110. package/dist/esm/internal/replay.d.ts.map +1 -0
  111. package/dist/esm/internal/replay.js +31 -0
  112. package/dist/esm/internal/replay.js.map +1 -0
  113. package/dist/esm/layerWebhook.d.ts +60 -0
  114. package/dist/esm/layerWebhook.d.ts.map +1 -0
  115. package/dist/esm/layerWebhook.js +186 -0
  116. package/dist/esm/layerWebhook.js.map +1 -0
  117. package/docs/README.md +146 -0
  118. package/docs/api.md +443 -0
  119. package/docs/concepts/admission-and-promotion.md +144 -0
  120. package/docs/concepts/alerting.md +138 -0
  121. package/docs/concepts/journal-records.md +132 -0
  122. package/docs/guides/alert-on-a-stuck-run.md +140 -0
  123. package/docs/guides/drain-at-a-turn-boundary.md +95 -0
  124. package/docs/guides/handle-a-full-queue.md +102 -0
  125. package/docs/guides/report-pending-notifications.md +92 -0
  126. package/docs/guides/send-alerts-to-a-webhook.md +155 -0
  127. package/docs/guides/steer-a-run.md +127 -0
  128. package/docs/guides/testing.md +161 -0
  129. package/docs/installation.md +123 -0
  130. package/docs/quickstart.md +159 -0
  131. package/docs/troubleshooting.md +254 -0
  132. package/package.json +182 -3
  133. package/src/AlertPolicy.ts +377 -0
  134. package/src/AlertRuntime.ts +280 -0
  135. package/src/AlertSink.ts +105 -0
  136. package/src/Alerts.ts +71 -0
  137. package/src/Notification.ts +171 -0
  138. package/src/NotificationEvent.ts +213 -0
  139. package/src/NotificationQueue.ts +856 -0
  140. package/src/NotificationState.ts +295 -0
  141. package/src/Projection.ts +48 -0
  142. package/src/SteerPayload.ts +198 -0
  143. package/src/index.ts +47 -0
  144. package/src/internal/foldCache.ts +72 -0
  145. package/src/internal/replay.ts +39 -0
  146. package/src/layerWebhook.ts +239 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/AlertPolicy.ts"],
4
+ "sourcesContent": ["/**\n * Alert policy: what a condition is, when a journal leaves one open, and\n * which open conditions have outlived their delay.\n *\n * Everything here is pure and a function of journal time, so the same entries\n * decide the same alerts in any process at any instant past the delay. The\n * transport that pages about them is `./layerWebhook.ts` and the journal-backed\n * tick that drives them is `./AlertRuntime.ts`; `./Alerts.ts` is the module a\n * consumer imports.\n *\n * @since 1.0.0\n */\n\nimport type { JournalEvent } from \"@smthrs/journal\"\nimport { Schema } from \"effect\"\n\n/**\n * The journal event type one delivered alert is recorded under.\n *\n * @category constants\n * @since 0.1.0\n */\nexport const deliveredEventType = \"flows.alerts.delivered\"\n\n/**\n * The journal event type one failed delivery attempt is recorded under.\n *\n * One entry is written per alert per failure code, never one per tick: a\n * webhook that stays down for an hour leaves one record, not a hundred and\n * twenty that every later tick has to read past.\n *\n * @category constants\n * @since 0.1.0\n */\nexport const failedEventType = \"flows.alerts.failed\"\n\n/**\n * How loud an alert is.\n *\n * @category models\n * @since 0.1.0\n */\nexport const Severity = Schema.Literals([\"info\", \"warning\", \"critical\"])\n\n/**\n * How loud an alert is.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Severity = typeof Severity.Type\n\n/**\n * How a condition is recognized in the journal.\n *\n * `field` names a payload key, `value` the value that means the condition\n * holds, and `eventTypes` narrows which entries are consulted at all. An\n * `eventTypes` item ending in `.*` names a family: `control.*` consults\n * `control.run.parked` and `control.monitor.beat` alike. An entry that carries\n * the field with a different value CLOSES the condition, which is what makes a\n * resume clear an approval alert without a second vocabulary for \"cleared\".\n *\n * @category models\n * @since 0.1.0\n */\nexport const Detector = Schema.Struct({\n field: Schema.NonEmptyString,\n value: Schema.NonEmptyString,\n eventTypes: Schema.optional(Schema.Array(Schema.NonEmptyString))\n})\n\n/**\n * How a condition is recognized in the journal.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Detector = typeof Detector.Type\n\n/**\n * What to do about one condition, and after how long.\n *\n * `afterMs` is a whole, non-negative number of milliseconds. The bound is the\n * schema's job because the delay is also arithmetic on journal time: a `NaN`\n * delay fires on the first tick and stamps a `firedAt` that JSON writes as\n * `null`, and a negative one fires with a `firedAt` earlier than the condition\n * it describes.\n *\n * @category models\n * @since 0.1.0\n */\nexport const Rule = Schema.Struct({\n afterMs: Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(0))),\n severity: Schema.optional(Severity),\n owner: Schema.optional(Schema.String),\n runbook: Schema.optional(Schema.String)\n})\n\n/**\n * What to do about one condition, and after how long.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Rule = typeof Rule.Type\n\n/**\n * The conditions a policy alerts on and the delays it alerts after.\n *\n * `defaults` fills in what a rule leaves out, so a policy states the delay per\n * condition and the ownership once.\n *\n * @category models\n * @since 0.1.0\n */\nexport const Policy = Schema.Struct({\n defaults: Schema.optional(Schema.Struct({\n severity: Schema.optional(Severity),\n owner: Schema.optional(Schema.String),\n runbook: Schema.optional(Schema.String)\n })),\n rules: Schema.Record(Schema.String, Rule),\n /** Detectors for conditions this deployment names itself. */\n detectors: Schema.optional(Schema.Record(Schema.String, Detector))\n})\n\n/**\n * The conditions a policy alerts on and the delays it alerts after.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Policy = typeof Policy.Type\n\n/**\n * The four conditions a control plane journals out of the box.\n *\n * `status` rides on every `control.run.*` entry, and `health` on every\n * `control.monitor.beat`. A deployment whose supervisor journals a park reason\n * gets `quota-parked` from the same field the run summary reports it under.\n *\n * Each consults the `control.*` family only. A run's journal is shared with\n * flow steps, agent traces, and anything else that writes to the run, and a\n * `status` or `health` field on one of those entries would otherwise open or\n * close a condition the control plane never reported.\n *\n * @category constants\n * @since 0.1.0\n */\nexport const defaultDetectors: Readonly<Record<string, Detector>> = {\n \"waiting-approval\": { field: \"status\", value: \"waiting-approval\", eventTypes: [\"control.*\"] },\n failed: { field: \"status\", value: \"failed\", eventTypes: [\"control.*\"] },\n stalled: { field: \"health\", value: \"stalled\", eventTypes: [\"control.*\"] },\n \"quota-parked\": { field: \"waitingReason\", value: \"quota\", eventTypes: [\"control.*\"] }\n}\n\n/**\n * Whether a detector's `eventTypes` names an entry's event type, exactly or\n * through a `.*` family.\n */\nconst names = (eventTypes: ReadonlyArray<string>, eventType: string): boolean =>\n eventTypes.some((named) => named.endsWith(\".*\") ? eventType.startsWith(named.slice(0, -1)) : named === eventType)\n\n/**\n * A condition that is open on a run, and when it opened.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Open {\n readonly runId: string\n readonly condition: string\n /** The journal time of the entry that opened the condition. */\n readonly since: number\n}\n\n/**\n * One alert a policy decided to raise.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Alert {\n readonly runId: string\n readonly condition: string\n readonly since: number\n /**\n * The journal instant the condition outlived its delay: `since` plus the\n * rule's `afterMs`, never the wall clock of whichever tick noticed.\n */\n readonly firedAt: number\n readonly severity: Severity\n readonly coalescingKey: string\n readonly owner?: string | undefined\n readonly runbook?: string | undefined\n}\n\n/**\n * The journal source the alerter writes one outcome of one alert under.\n *\n * A delivery record counts as evidence that an alert went out only under this\n * source, so another producer's `flows.alerts.delivered` record with a\n * matching `alertId` does not suppress a page. This scopes records; it does\n * not authenticate the writer, because the journal does not bind a source to\n * a writer.\n *\n * @param id the alert's {@link alertId}\n * @param outcome `delivered`, `refused`, or `failed/<code>`\n * @private\n * @since 1.0.0\n */\nexport const recordSourceId = (id: string, outcome: string): string => `/notifications/alerts/${id}/${outcome}`\n\n/**\n * The key an alert coalesces on: one open condition on one run.\n *\n * Each component is percent-encoded before it is joined, so a run id or a\n * condition name containing the separator cannot forge another pair's key and\n * suppress a page that belongs to somebody else. Both components are values a\n * deployment chooses, which is why the encoding is not optional.\n *\n * @param runId the run the condition is open on\n * @param condition the condition name the policy uses\n * @category getters\n * @since 1.0.0\n */\nexport const coalescingKey = (runId: string, condition: string): string =>\n `${encodeURIComponent(runId)}:${encodeURIComponent(condition)}`\n\n/**\n * The identity a delivery is recorded under.\n *\n * The opening time is part of it on purpose. A condition that clears and\n * re-opens is a NEW alert, because the second approval wait is not the first\n * one, and a key without the time would suppress it forever.\n *\n * @param alert the alert\n * @category getters\n * @since 0.1.0\n */\nexport const alertId = (alert: Pick<Alert, \"coalescingKey\" | \"since\">): string =>\n `alert:${alert.coalescingKey}:${alert.since}`\n\n/**\n * The detectors one policy decides with: the four this package ships, with\n * the deployment's own overriding them by name.\n *\n * @private\n * @since 1.0.0\n */\nexport const detectorsOf = (policy: Policy): Readonly<Record<string, Detector>> => ({\n ...defaultDetectors,\n ...policy.detectors\n})\n\n/**\n * One entry's payload when it is a record a detector can read a field off,\n * and `undefined` for the arrays and primitives that carry no fields at all.\n *\n * @private\n * @since 1.0.0\n */\nexport const payloadRecord = (payload: unknown): Readonly<Record<string, unknown>> | undefined =>\n typeof payload === \"object\" && payload !== null && !Array.isArray(payload)\n ? payload as Readonly<Record<string, unknown>>\n : undefined\n\n/**\n * Folds one entry into the open-condition map. Shared by {@link conditions}\n * and the runtime's incremental read, so both decide a condition the same\n * way.\n *\n * The alerter's own records are never evidence about a condition. They are\n * written into the same journal they are read from, and they carry the alert's\n * own vocabulary: a refusal reports the answering HTTP `status`, which a\n * detector watching the run's `status` would read as the condition clearing.\n * A page would then close the condition it paged about and the next tick would\n * re-open it, so a webhook that answered 503 once would alert forever.\n *\n * @private\n * @since 1.0.0\n */\nexport const observe = (\n policy: Policy,\n detectors: Readonly<Record<string, Detector>>,\n entry: JournalEvent.Entry,\n payload: Readonly<Record<string, unknown>>,\n open: Map<string, number>\n): void => {\n if (entry.eventType === deliveredEventType || entry.eventType === failedEventType) return\n for (const condition of Object.keys(policy.rules)) {\n const detector = detectors[condition]\n if (detector === undefined) continue\n if (detector.eventTypes !== undefined && !names(detector.eventTypes, entry.eventType)) continue\n // Own properties only. `in` walks `Object.prototype`, so a detector named\n // `toString` or `constructor` would read every record-shaped entry in the\n // run as evidence and close the condition on all of them.\n if (!Object.hasOwn(payload, detector.field)) continue\n if (payload[detector.field] === detector.value) {\n if (!open.has(condition)) open.set(condition, entry.emittedAtMs)\n } else {\n open.delete(condition)\n }\n }\n}\n\n/**\n * Every condition a run's journal leaves open, with the time each opened.\n *\n * An entry that carries a detector's field opens the condition when the value\n * matches and closes it when it does not. Entries the detector does not name\n * are ignored entirely, so a monitor beat cannot close an approval wait and an\n * approval cannot close a stall.\n *\n * @param policy the policy whose detectors decide what counts\n * @param runId the run the entries belong to\n * @param entries the run's journal, oldest first\n * @category projections\n * @since 0.1.0\n */\nexport const conditions = (\n policy: Policy,\n runId: string,\n entries: ReadonlyArray<JournalEvent.Entry>\n): ReadonlyArray<Open> => {\n const detectors = detectorsOf(policy)\n const open = new Map<string, number>()\n for (const entry of entries) {\n const payload = payloadRecord(entry.payload)\n if (payload === undefined) continue\n observe(policy, detectors, entry, payload, open)\n }\n return Array.from(open, ([condition, since]) => ({ runId, condition, since }))\n}\n\n/**\n * The alerts a policy raises for the conditions open at `now`.\n *\n * Pure, and a function of journal time: the same journal raises the same\n * alerts in any process, at any instant past the delay. `now` decides WHETHER\n * an alert is raised; it never appears in one. A condition that has been open\n * for less than its rule's delay raises nothing, which is the whole point of\n * the delay, because most stalls clear themselves.\n *\n * @param policy the policy\n * @param open the conditions the journal left open\n * @param now the instant to judge them at\n * @category projections\n * @since 0.1.0\n */\nexport const decide = (\n policy: Policy,\n open: ReadonlyArray<Open>,\n now: number\n): ReadonlyArray<Alert> =>\n open.flatMap((condition) => {\n const rule = policy.rules[condition.condition]\n if (rule === undefined) return []\n if (now - condition.since < rule.afterMs) return []\n const severity = rule.severity ?? policy.defaults?.severity ?? \"warning\"\n const owner = rule.owner ?? policy.defaults?.owner\n const runbook = rule.runbook ?? policy.defaults?.runbook\n return [{\n runId: condition.runId,\n condition: condition.condition,\n since: condition.since,\n // Derived from the journal, not read off the clock. The alert id is\n // stable across ticks, and the queue refuses a reused id whose content\n // changed, so an alert stamped with the reading time would become\n // permanently undeliverable the moment a tick refused and time moved on.\n firedAt: condition.since + rule.afterMs,\n severity,\n coalescingKey: coalescingKey(condition.runId, condition.condition),\n ...(owner === undefined ? {} : { owner }),\n ...(runbook === undefined ? {} : { runbook })\n }]\n })\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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,QAAM,OAAO,oBAAI,IAAoB;AACrC,aAAW,SAAS,SAAS;AAC3B,UAAM,UAAU,cAAc,MAAM,OAAO;AAC3C,QAAI,YAAY,OAAW;AAC3B,YAAQ,QAAQ,WAAW,OAAO,SAAS,IAAI;AAAA,EACjD;AACA,SAAO,MAAM,KAAK,MAAM,CAAC,CAAC,WAAW,KAAK,OAAO,EAAE,OAAO,WAAW,MAAM,EAAE;AAC/E;AAiBO,MAAM,SAAS,CACpB,QACA,MACA,QAEA,KAAK,QAAQ,CAAC,cAAc;AAC1B,QAAM,OAAO,OAAO,MAAM,UAAU,SAAS;AAC7C,MAAI,SAAS,OAAW,QAAO,CAAC;AAChC,MAAI,MAAM,UAAU,QAAQ,KAAK,QAAS,QAAO,CAAC;AAClD,QAAM,WAAW,KAAK,YAAY,OAAO,UAAU,YAAY;AAC/D,QAAM,QAAQ,KAAK,SAAS,OAAO,UAAU;AAC7C,QAAM,UAAU,KAAK,WAAW,OAAO,UAAU;AACjD,SAAO,CAAC;AAAA,IACN,OAAO,UAAU;AAAA,IACjB,WAAW,UAAU;AAAA,IACrB,OAAO,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA,IAKjB,SAAS,UAAU,QAAQ,KAAK;AAAA,IAChC;AAAA,IACA,eAAe,cAAc,UAAU,OAAO,UAAU,SAAS;AAAA,IACjE,GAAI,UAAU,SAAY,CAAC,IAAI,EAAE,MAAM;AAAA,IACvC,GAAI,YAAY,SAAY,CAAC,IAAI,EAAE,QAAQ;AAAA,EAC7C,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The journal-backed alert runtime: one tick per run.
3
+ *
4
+ * A tick folds the run's journal into the conditions it leaves open, decides
5
+ * which have outlived their delay, admits each one as a coalesced system
6
+ * event, pages the sink, and journals what the sink did with it. The fold is
7
+ * retained per run, so a tick costs the entries committed since the previous
8
+ * one rather than the run's whole journal.
9
+ *
10
+ * The rules it enforces are `./AlertPolicy.ts` and the channel it pages over
11
+ * is `./AlertSink.ts`; neither knows this module exists.
12
+ *
13
+ * @since 1.0.0
14
+ */
15
+ import { Journal } from "@smthrs/journal";
16
+ import { Context, Effect, Layer } from "effect";
17
+ import { type Alert, Policy } from "./AlertPolicy.ts";
18
+ import { Sink } from "./AlertSink.ts";
19
+ import { type NotificationError, NotificationQueue } from "./NotificationQueue.ts";
20
+ /**
21
+ * What one tick decided.
22
+ *
23
+ * @category models
24
+ * @since 0.1.0
25
+ */
26
+ export interface Tick {
27
+ /** Alerts raised and delivered on this tick. */
28
+ readonly delivered: ReadonlyArray<Alert>;
29
+ /** Alerts the sink refused on this tick. They are retried on the next one. */
30
+ readonly failed: ReadonlyArray<Alert>;
31
+ /**
32
+ * Alerts the notification queue refused because the run is at capacity. The
33
+ * sink was not called for them, and they are retried on the next tick.
34
+ */
35
+ readonly refused: ReadonlyArray<Alert>;
36
+ /** Alerts that had already been delivered, and were not delivered again. */
37
+ readonly suppressed: ReadonlyArray<Alert>;
38
+ }
39
+ /**
40
+ * The alert runtime: one tick per run.
41
+ *
42
+ * @category services
43
+ * @since 0.1.0
44
+ */
45
+ export interface RuntimeService {
46
+ /**
47
+ * Reads one run's journal and pages about whatever has waited too long.
48
+ *
49
+ * The two failures stay apart because they mean different things to an
50
+ * operator. A `JournalError` is the alerter's own record channel failing: it
51
+ * read no entries, or it could not write the delivery record. A
52
+ * `NotificationError` is the notification queue rejecting the alert outright,
53
+ * which is a producer or storage fault rather than a full queue. Neither is
54
+ * a sink failure: a refused page is journaled as `flows.alerts.failed` and
55
+ * retried on the next tick, and it comes back in {@link Tick.failed}. A queue
56
+ * at capacity is not a failure either; it comes back in {@link Tick.refused}.
57
+ */
58
+ readonly tick: (runId: string) => Effect.Effect<Tick, Journal.JournalError | NotificationError>;
59
+ }
60
+ declare const AlertRuntime_base: Context.ServiceClass<AlertRuntime, "/notifications/AlertRuntime", RuntimeService>;
61
+ /**
62
+ * The {@link RuntimeService} tag.
63
+ *
64
+ * @category services
65
+ * @since 0.1.0
66
+ */
67
+ export declare class AlertRuntime extends AlertRuntime_base {
68
+ }
69
+ /**
70
+ * The alert runtime over one policy.
71
+ *
72
+ * A tick reads the run's journal, derives the open conditions, decides which
73
+ * have outlived their delay, and for each one that has not already been
74
+ * delivered: admits a coalesced system event, sends it to the sink, and
75
+ * journals the delivery. The admission comes first because it is idempotent
76
+ * and the send is not: a crash between them costs a duplicate admission, which
77
+ * the queue drops, while a crash between an accepted send and the delivery
78
+ * record costs a duplicate PAGE, which is why {@link SinkService.deliver} is
79
+ * required to dedupe on {@link alertId}.
80
+ *
81
+ * The policy is decoded when the layer is built, so a rule with an impossible
82
+ * delay fails the composition by name instead of mis-paging at 3am.
83
+ *
84
+ * @param policy the rules to enforce
85
+ * @category layers
86
+ * @since 0.1.0
87
+ */
88
+ export declare const layer: (policy: Policy) => Layer.Layer<AlertRuntime, never, Journal.Journal | NotificationQueue | Sink>;
89
+ export {};
90
+ //# sourceMappingURL=AlertRuntime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AlertRuntime.d.ts","sourceRoot":"","sources":["../../src/AlertRuntime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,OAAO,EAAgB,MAAM,iBAAiB,CAAA;AACvD,OAAO,EAAS,OAAO,EAAE,MAAM,EAAW,KAAK,EAAkB,MAAM,QAAQ,CAAA;AAC/E,OAAO,EACL,KAAK,KAAK,EAQV,MAAM,EAEP,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAA;AAGrC,OAAO,EAAE,KAAK,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAElF;;;;;GAKG;AACH,MAAM,WAAW,IAAI;IACnB,gDAAgD;IAChD,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC,KAAK,CAAC,CAAA;IACxC,8EAA8E;IAC9E,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC,KAAK,CAAC,CAAA;IACrC;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,CAAA;IACtC,4EAA4E;IAC5E,QAAQ,CAAC,UAAU,EAAE,aAAa,CAAC,KAAK,CAAC,CAAA;CAC1C;AAED;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,YAAY,GAAG,iBAAiB,CAAC,CAAA;CAChG;;AAED;;;;;GAKG;AACH,qBAAa,YAAa,SAAQ,iBAEjC;CAAG;AA8CJ;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,KAAK,GAChB,QAAQ,MAAM,KACb,KAAK,CAAC,KAAK,CAAC,YAAY,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,GAAG,iBAAiB,GAAG,IAAI,CAgI3E,CAAA"}
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var AlertRuntime_exports = {};
30
+ __export(AlertRuntime_exports, {
31
+ AlertRuntime: () => AlertRuntime,
32
+ layer: () => layer
33
+ });
34
+ module.exports = __toCommonJS(AlertRuntime_exports);
35
+ var import_journal = require("@smthrs/journal");
36
+ var import_effect = require("effect");
37
+ var import_AlertPolicy = require("./AlertPolicy.js");
38
+ var import_AlertSink = require("./AlertSink.js");
39
+ var FoldCache = __toESM(require("./internal/foldCache.js"), 1);
40
+ var import_NotificationQueue = require("./NotificationQueue.js");
41
+ class AlertRuntime extends import_effect.Context.Service()(
42
+ "/notifications/AlertRuntime"
43
+ ) {
44
+ }
45
+ const maximumWatchedRuns = 64;
46
+ const alertNotification = (alert) => ({
47
+ _tag: "system-event",
48
+ id: (0, import_AlertPolicy.alertId)(alert),
49
+ targetLineageId: alert.runId,
50
+ delivery: "queue",
51
+ coalescingKey: alert.coalescingKey,
52
+ provenance: {
53
+ sourceRunId: alert.runId,
54
+ sourceLineageId: alert.runId,
55
+ sourceTurn: 0,
56
+ sourceActor: "alerts"
57
+ },
58
+ payload: {
59
+ condition: alert.condition,
60
+ severity: alert.severity,
61
+ since: alert.since,
62
+ firedAt: alert.firedAt,
63
+ ...alert.owner === void 0 ? {} : { owner: alert.owner },
64
+ ...alert.runbook === void 0 ? {} : { runbook: alert.runbook }
65
+ }
66
+ });
67
+ const layer = (policy) => import_effect.Layer.effect(
68
+ AlertRuntime,
69
+ import_effect.Effect.gen(function* () {
70
+ const checked = yield* import_effect.Effect.orDie(import_effect.Schema.decodeUnknownEffect(import_AlertPolicy.Policy)(policy));
71
+ const detectors = (0, import_AlertPolicy.detectorsOf)(checked);
72
+ const journal = yield* import_journal.Journal.Journal;
73
+ const queue = yield* import_NotificationQueue.NotificationQueue;
74
+ const sink = yield* import_AlertSink.Sink;
75
+ const watched = FoldCache.make(maximumWatchedRuns);
76
+ const observed = (runId) => import_effect.Effect.gen(function* () {
77
+ const base = watched.get(runId) ?? { open: /* @__PURE__ */ new Map(), delivered: import_effect.HashSet.empty(), cursor: void 0 };
78
+ const fresh = [];
79
+ let after = base.cursor === void 0 ? void 0 : import_journal.JournalEvent.Seq.make(base.cursor);
80
+ while (true) {
81
+ const page = yield* journal.entries({ runId, ...after === void 0 ? {} : { after }, limit: 512 });
82
+ fresh.push(...page.entries);
83
+ if (!page.hasMore || page.entries.length === 0) break;
84
+ after = page.entries.at(-1).seq;
85
+ }
86
+ if (fresh.length === 0) return base;
87
+ const open = new Map(base.open);
88
+ let delivered = base.delivered;
89
+ let cursor = base.cursor;
90
+ for (const entry of fresh) {
91
+ cursor = entry.seq;
92
+ const payload = (0, import_AlertPolicy.payloadRecord)(entry.payload);
93
+ if (payload === void 0) continue;
94
+ if (entry.eventType === import_AlertPolicy.deliveredEventType) {
95
+ const id = payload["alertId"];
96
+ if (typeof id === "string" && entry.sourceId === (0, import_AlertPolicy.recordSourceId)(id, "delivered")) {
97
+ delivered = import_effect.HashSet.add(delivered, id);
98
+ }
99
+ }
100
+ (0, import_AlertPolicy.observe)(checked, detectors, entry, payload, open);
101
+ }
102
+ const next = { open, delivered, cursor };
103
+ yield* journal.whenCommitted(import_effect.Effect.sync(() => watched.put(runId, next)));
104
+ return next;
105
+ });
106
+ const record = (eventType, alert, source, outcome) => journal.emitDurableUnfenced(
107
+ new import_journal.JournalEvent.Input({
108
+ runId: import_journal.JournalEvent.RunId.make(alert.runId),
109
+ sourceId: import_journal.JournalEvent.SourceId.make((0, import_AlertPolicy.recordSourceId)((0, import_AlertPolicy.alertId)(alert), source)),
110
+ sourceSeq: import_journal.JournalEvent.SourceSeq.make(0),
111
+ // One record per alert per outcome. Without an explicit identity
112
+ // the journal allocates a new sequence on every attempt, and a
113
+ // webhook that stays down appends a row per tick forever.
114
+ dedupe: "identity",
115
+ eventType,
116
+ payload: {
117
+ runId: alert.runId,
118
+ condition: alert.condition,
119
+ since: alert.since,
120
+ severity: alert.severity,
121
+ alertId: (0, import_AlertPolicy.alertId)(alert),
122
+ ...outcome.code === void 0 ? {} : { code: outcome.code },
123
+ ...outcome.status === void 0 ? {} : { status: outcome.status }
124
+ }
125
+ })
126
+ ).pipe(import_effect.Effect.asVoid);
127
+ return AlertRuntime.of({
128
+ tick: import_effect.Effect.fn("AlertRuntime.tick")(function* (runId) {
129
+ const journalRunId = import_journal.JournalEvent.RunId.make(runId);
130
+ const history = yield* observed(journalRunId);
131
+ const now = yield* import_effect.Clock.currentTimeMillis;
132
+ const open = Array.from(history.open, ([condition, since]) => ({ runId, condition, since }));
133
+ const raised = (0, import_AlertPolicy.decide)(checked, open, now);
134
+ const delivered = [];
135
+ const failed = [];
136
+ const refused = [];
137
+ const suppressed = [];
138
+ for (const alert of raised) {
139
+ if (import_effect.HashSet.has(history.delivered, (0, import_AlertPolicy.alertId)(alert))) {
140
+ suppressed.push(alert);
141
+ continue;
142
+ }
143
+ const receipt = yield* queue.admit(runId, alertNotification(alert));
144
+ if (receipt.decision === "rejected-full") {
145
+ yield* record(import_AlertPolicy.failedEventType, alert, "refused", { code: "notification_full" });
146
+ refused.push(alert);
147
+ continue;
148
+ }
149
+ const outcome = yield* import_effect.Effect.result(sink.deliver(alert));
150
+ if (import_effect.Result.isFailure(outcome)) {
151
+ yield* record(import_AlertPolicy.failedEventType, alert, `failed/${outcome.failure.code}`, {
152
+ code: outcome.failure.code,
153
+ status: outcome.failure.status
154
+ });
155
+ failed.push(alert);
156
+ } else {
157
+ yield* record(import_AlertPolicy.deliveredEventType, alert, "delivered", {});
158
+ delivered.push(alert);
159
+ }
160
+ }
161
+ return { delivered, failed, refused, suppressed };
162
+ })
163
+ });
164
+ })
165
+ );
166
+ //# sourceMappingURL=AlertRuntime.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/AlertRuntime.ts"],
4
+ "sourcesContent": ["/**\n * The journal-backed alert runtime: one tick per run.\n *\n * A tick folds the run's journal into the conditions it leaves open, decides\n * which have outlived their delay, admits each one as a coalesced system\n * event, pages the sink, and journals what the sink did with it. The fold is\n * retained per run, so a tick costs the entries committed since the previous\n * one rather than the run's whole journal.\n *\n * The rules it enforces are `./AlertPolicy.ts` and the channel it pages over\n * is `./AlertSink.ts`; neither knows this module exists.\n *\n * @since 1.0.0\n */\n\nimport { Journal, JournalEvent } from \"@smthrs/journal\"\nimport { Clock, Context, Effect, HashSet, Layer, Result, Schema } from \"effect\"\nimport {\n type Alert,\n alertId,\n decide,\n deliveredEventType,\n detectorsOf,\n failedEventType,\n observe,\n payloadRecord,\n Policy,\n recordSourceId\n} from \"./AlertPolicy.ts\"\nimport { Sink } from \"./AlertSink.ts\"\nimport * as FoldCache from \"./internal/foldCache.ts\"\nimport type * as NotificationModel from \"./Notification.ts\"\nimport { type NotificationError, NotificationQueue } from \"./NotificationQueue.ts\"\n\n/**\n * What one tick decided.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Tick {\n /** Alerts raised and delivered on this tick. */\n readonly delivered: ReadonlyArray<Alert>\n /** Alerts the sink refused on this tick. They are retried on the next one. */\n readonly failed: ReadonlyArray<Alert>\n /**\n * Alerts the notification queue refused because the run is at capacity. The\n * sink was not called for them, and they are retried on the next tick.\n */\n readonly refused: ReadonlyArray<Alert>\n /** Alerts that had already been delivered, and were not delivered again. */\n readonly suppressed: ReadonlyArray<Alert>\n}\n\n/**\n * The alert runtime: one tick per run.\n *\n * @category services\n * @since 0.1.0\n */\nexport interface RuntimeService {\n /**\n * Reads one run's journal and pages about whatever has waited too long.\n *\n * The two failures stay apart because they mean different things to an\n * operator. A `JournalError` is the alerter's own record channel failing: it\n * read no entries, or it could not write the delivery record. A\n * `NotificationError` is the notification queue rejecting the alert outright,\n * which is a producer or storage fault rather than a full queue. Neither is\n * a sink failure: a refused page is journaled as `flows.alerts.failed` and\n * retried on the next tick, and it comes back in {@link Tick.failed}. A queue\n * at capacity is not a failure either; it comes back in {@link Tick.refused}.\n */\n readonly tick: (runId: string) => Effect.Effect<Tick, Journal.JournalError | NotificationError>\n}\n\n/**\n * The {@link RuntimeService} tag.\n *\n * @category services\n * @since 0.1.0\n */\nexport class AlertRuntime extends Context.Service<AlertRuntime, RuntimeService>()(\n \"/notifications/AlertRuntime\"\n) {}\n\n/**\n * One run's folded alert history: the conditions still open, the alerts\n * already paged, and the sequence the fold stopped at.\n */\ninterface Watched {\n readonly open: ReadonlyMap<string, number>\n /**\n * The alerts already paged, as a persistent set: a tick adds a node and\n * leaves the fold the previous tick published untouched, where copying the\n * set would cost the run's whole delivery history on every tick.\n */\n readonly delivered: HashSet.HashSet<string>\n readonly cursor: number | undefined\n}\n\n/**\n * How many runs one alert runtime keeps folded at a time. The retention policy\n * is scan-resistant, so a sweep of more runs than this reads journal tails for\n * all but a fixed handful of them.\n */\nconst maximumWatchedRuns = 64\n\nconst alertNotification = (alert: Alert): NotificationModel.Notification => ({\n _tag: \"system-event\",\n id: alertId(alert),\n targetLineageId: alert.runId,\n delivery: \"queue\",\n coalescingKey: alert.coalescingKey,\n provenance: {\n sourceRunId: alert.runId,\n sourceLineageId: alert.runId,\n sourceTurn: 0,\n sourceActor: \"alerts\"\n },\n payload: {\n condition: alert.condition,\n severity: alert.severity,\n since: alert.since,\n firedAt: alert.firedAt,\n ...(alert.owner === undefined ? {} : { owner: alert.owner }),\n ...(alert.runbook === undefined ? {} : { runbook: alert.runbook })\n }\n})\n\n/**\n * The alert runtime over one policy.\n *\n * A tick reads the run's journal, derives the open conditions, decides which\n * have outlived their delay, and for each one that has not already been\n * delivered: admits a coalesced system event, sends it to the sink, and\n * journals the delivery. The admission comes first because it is idempotent\n * and the send is not: a crash between them costs a duplicate admission, which\n * the queue drops, while a crash between an accepted send and the delivery\n * record costs a duplicate PAGE, which is why {@link SinkService.deliver} is\n * required to dedupe on {@link alertId}.\n *\n * The policy is decoded when the layer is built, so a rule with an impossible\n * delay fails the composition by name instead of mis-paging at 3am.\n *\n * @param policy the rules to enforce\n * @category layers\n * @since 0.1.0\n */\nexport const layer = (\n policy: Policy\n): Layer.Layer<AlertRuntime, never, Journal.Journal | NotificationQueue | Sink> =>\n Layer.effect(\n AlertRuntime,\n Effect.gen(function*() {\n const checked = yield* Effect.orDie(Schema.decodeUnknownEffect(Policy)(policy))\n const detectors = detectorsOf(checked)\n const journal = yield* Journal.Journal\n const queue = yield* NotificationQueue\n const sink = yield* Sink\n // Folded history per run, so a tick costs the entries committed since\n // the previous one rather than the run's whole journal.\n const watched = FoldCache.make<Watched>(maximumWatchedRuns)\n\n const observed = (runId: JournalEvent.RunId): Effect.Effect<Watched, Journal.JournalError> =>\n Effect.gen(function*() {\n const base: Watched = watched.get(runId) ??\n { open: new Map(), delivered: HashSet.empty(), cursor: undefined }\n const fresh: Array<JournalEvent.Entry> = []\n let after = base.cursor === undefined ? undefined : JournalEvent.Seq.make(base.cursor)\n while (true) {\n const page = yield* journal.entries({ runId, ...(after === undefined ? {} : { after }), limit: 512 })\n fresh.push(...page.entries)\n if (!page.hasMore || page.entries.length === 0) break\n after = page.entries.at(-1)!.seq\n }\n if (fresh.length === 0) return base\n\n // `open` is bounded by the policy's rules, so it is copied; the\n // delivery history is not, so it grows by one persistent node.\n const open = new Map(base.open)\n let delivered = base.delivered\n let cursor = base.cursor\n for (const entry of fresh) {\n cursor = entry.seq\n const payload = payloadRecord(entry.payload)\n if (payload === undefined) continue\n if (entry.eventType === deliveredEventType) {\n const id = payload[\"alertId\"]\n // Only a record under the source the alerter writes counts, so\n // another producer's delivered record cannot suppress a page.\n // The journal does not bind a source to a writer.\n if (typeof id === \"string\" && entry.sourceId === recordSourceId(id, \"delivered\")) {\n delivered = HashSet.add(delivered, id)\n }\n }\n observe(checked, detectors, entry, payload, open)\n }\n const next: Watched = { open, delivered, cursor }\n // Published at commit, exactly as `NotificationQueue.load` publishes\n // its fold. A tick inside an enclosing transaction reads that\n // transaction's uncommitted rows, and caching them would outlive the\n // rollback that erased them: the run would page about a condition\n // durable history never held.\n yield* journal.whenCommitted(Effect.sync(() => watched.put(runId, next)))\n return next\n })\n\n const record = (\n eventType: string,\n alert: Alert,\n source: string,\n outcome: { readonly code?: string | undefined; readonly status?: number | undefined }\n ): Effect.Effect<void, Journal.JournalError> =>\n journal.emitDurableUnfenced(\n new JournalEvent.Input({\n runId: JournalEvent.RunId.make(alert.runId),\n sourceId: JournalEvent.SourceId.make(recordSourceId(alertId(alert), source)),\n sourceSeq: JournalEvent.SourceSeq.make(0),\n // One record per alert per outcome. Without an explicit identity\n // the journal allocates a new sequence on every attempt, and a\n // webhook that stays down appends a row per tick forever.\n dedupe: \"identity\",\n eventType,\n payload: {\n runId: alert.runId,\n condition: alert.condition,\n since: alert.since,\n severity: alert.severity,\n alertId: alertId(alert),\n ...(outcome.code === undefined ? {} : { code: outcome.code }),\n ...(outcome.status === undefined ? {} : { status: outcome.status })\n }\n })\n ).pipe(Effect.asVoid)\n\n return AlertRuntime.of({\n tick: Effect.fn(\"AlertRuntime.tick\")(function*(runId: string) {\n const journalRunId = JournalEvent.RunId.make(runId)\n const history = yield* observed(journalRunId)\n const now = yield* Clock.currentTimeMillis\n const open = Array.from(history.open, ([condition, since]) => ({ runId, condition, since }))\n const raised = decide(checked, open, now)\n const delivered: Array<Alert> = []\n const failed: Array<Alert> = []\n const refused: Array<Alert> = []\n const suppressed: Array<Alert> = []\n for (const alert of raised) {\n if (HashSet.has(history.delivered, alertId(alert))) {\n suppressed.push(alert)\n continue\n }\n // Raised unchanged: a queue that rejects the admission outright is\n // not the journal failing, and calling it `sink_failed` would send\n // an operator looking at the webhook.\n const receipt = yield* queue.admit(runId, alertNotification(alert))\n if (receipt.decision === \"rejected-full\") {\n // The alert has nowhere durable to sit, so paging about it would\n // tell an operator about something the run will never read.\n yield* record(failedEventType, alert, \"refused\", { code: \"notification_full\" })\n refused.push(alert)\n continue\n }\n const outcome = yield* Effect.result(sink.deliver(alert))\n if (Result.isFailure(outcome)) {\n yield* record(failedEventType, alert, `failed/${outcome.failure.code}`, {\n code: outcome.failure.code,\n status: outcome.failure.status\n })\n failed.push(alert)\n } else {\n yield* record(deliveredEventType, alert, \"delivered\", {})\n delivered.push(alert)\n }\n }\n return { delivered, failed, refused, suppressed }\n })\n })\n })\n )\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,qBAAsC;AACtC,oBAAuE;AACvE,yBAWO;AACP,uBAAqB;AACrB,gBAA2B;AAE3B,+BAA0D;AAkDnD,MAAM,qBAAqB,sBAAQ,QAAsC;AAAA,EAC9E;AACF,EAAE;AAAC;AAsBH,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB,CAAC,WAAkD;AAAA,EAC3E,MAAM;AAAA,EACN,QAAI,4BAAQ,KAAK;AAAA,EACjB,iBAAiB,MAAM;AAAA,EACvB,UAAU;AAAA,EACV,eAAe,MAAM;AAAA,EACrB,YAAY;AAAA,IACV,aAAa,MAAM;AAAA,IACnB,iBAAiB,MAAM;AAAA,IACvB,YAAY;AAAA,IACZ,aAAa;AAAA,EACf;AAAA,EACA,SAAS;AAAA,IACP,WAAW,MAAM;AAAA,IACjB,UAAU,MAAM;AAAA,IAChB,OAAO,MAAM;AAAA,IACb,SAAS,MAAM;AAAA,IACf,GAAI,MAAM,UAAU,SAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;AAAA,IAC1D,GAAI,MAAM,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;AAAA,EAClE;AACF;AAqBO,MAAM,QAAQ,CACnB,WAEA,oBAAM;AAAA,EACJ;AAAA,EACA,qBAAO,IAAI,aAAY;AACrB,UAAM,U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,CAAC;AAC9B,cAAM,UAAwB,CAAC;AAC/B,cAAM,aAA2B,CAAC;AAClC,mBAAW,SAAS,QAAQ;AAC1B,cAAI,sBAAQ,IAAI,QAAQ,eAAW,4BAAQ,KAAK,CAAC,GAAG;AAClD,uBAAW,KAAK,KAAK;AACrB;AAAA,UACF;AAIA,gBAAM,UAAU,OAAO,MAAM,MAAM,OAAO,kBAAkB,KAAK,CAAC;AAClE,cAAI,QAAQ,aAAa,iBAAiB;AAGxC,mBAAO,OAAO,oCAAiB,OAAO,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC9E,oBAAQ,KAAK,KAAK;AAClB;AAAA,UACF;AACA,gBAAM,UAAU,OAAO,qBAAO,OAAO,KAAK,QAAQ,KAAK,CAAC;AACxD,cAAI,qBAAO,UAAU,OAAO,GAAG;AAC7B,mBAAO,OAAO,oCAAiB,OAAO,UAAU,QAAQ,QAAQ,IAAI,IAAI;AAAA,cACtE,MAAM,QAAQ,QAAQ;AAAA,cACtB,QAAQ,QAAQ,QAAQ;AAAA,YAC1B,CAAC;AACD,mBAAO,KAAK,KAAK;AAAA,UACnB,OAAO;AACL,mBAAO,OAAO,uCAAoB,OAAO,aAAa,CAAC,CAAC;AACxD,sBAAU,KAAK,KAAK;AAAA,UACtB;AAAA,QACF;AACA,eAAO,EAAE,WAAW,QAAQ,SAAS,WAAW;AAAA,MAClD,CAAC;AAAA,IACH,CAAC;AAAA,EACH,CAAC;AACH;",
6
+ "names": []
7
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The alert sink port: where a raised alert is sent, and why a send failed.
3
+ *
4
+ * The port is a tag and an error so a deployment supplies the transport and
5
+ * the policy needs none. `./layerWebhook.ts` is the transport this package
6
+ * ships, and {@link layerNoop} is the one a test composes.
7
+ *
8
+ * @since 1.0.0
9
+ */
10
+ import { Context, Effect, Layer, Schema } from "effect";
11
+ import type { Alert } from "./AlertPolicy.ts";
12
+ /**
13
+ * Why a sink did not take an alert.
14
+ *
15
+ * `sink_rejected` is an answer that refused the page, `sink_unreachable` a
16
+ * request that never got one, and `sink_timeout` one that got no answer inside
17
+ * the sink's bound. `sink_misconfigured` is an endpoint the sink may not POST
18
+ * to at all; it is raised when the layer is built, before any alert exists,
19
+ * so it never reaches a journal.
20
+ *
21
+ * @category models
22
+ * @since 1.0.0
23
+ */
24
+ export declare const FailureCode: Schema.Literals<readonly ["sink_rejected", "sink_unreachable", "sink_timeout", "sink_misconfigured"]>;
25
+ /**
26
+ * Why a sink did not take an alert.
27
+ *
28
+ * @category models
29
+ * @since 1.0.0
30
+ */
31
+ export type FailureCode = typeof FailureCode.Type;
32
+ declare const AlertError_base: Schema.Class<AlertError, Schema.TaggedStruct<"/notifications/AlertError", {
33
+ readonly code: Schema.withConstructorDefault<Schema.Literals<readonly ["sink_rejected", "sink_unreachable", "sink_timeout", "sink_misconfigured"]>>;
34
+ readonly message: Schema.String;
35
+ /** The HTTP status that refused the page, when the sink speaks HTTP. */
36
+ readonly status: Schema.optional<Schema.Int>;
37
+ /** A short, credential-free description of the transport failure. */
38
+ readonly reason: Schema.optional<Schema.String>;
39
+ }>, import("effect/Cause").YieldableError>;
40
+ /**
41
+ * A sink refused or could not take an alert.
42
+ *
43
+ * The error carries a code, the answering status when there was one, and a
44
+ * short reason. It deliberately holds no request: a webhook request carries
45
+ * the credential the deployment handed {@link layerWebhook}, and an error is
46
+ * logged, encoded, and journaled in places a credential must never reach.
47
+ *
48
+ * @category errors
49
+ * @since 0.1.0
50
+ */
51
+ export declare class AlertError extends AlertError_base {
52
+ }
53
+ /**
54
+ * Where a raised alert is sent.
55
+ *
56
+ * Injected rather than fixed, because who gets paged is a deployment's
57
+ * decision and the policy is not: the same rules feed a webhook in production
58
+ * and nothing at all in a test.
59
+ *
60
+ * @category services
61
+ * @since 0.1.0
62
+ */
63
+ export interface SinkService {
64
+ /**
65
+ * Sends one alert, and does so idempotently on {@link alertId}.
66
+ *
67
+ * Delivery is at-least-once: the `flows.alerts.delivered` record is written
68
+ * after this effect succeeds, so a process that dies in between pages again
69
+ * on the next tick. Every field of the alert, {@link Alert.firedAt}
70
+ * included, is derived from the journal, so the same alert is byte-identical
71
+ * on every attempt and `alertId(alert)` is the deduplication key a receiving
72
+ * system should key on. A sink that cannot dedupe is a sink that will
73
+ * occasionally page twice about one condition.
74
+ *
75
+ * A failure means the page did not go out. Succeeding on a page that was
76
+ * dropped is the one thing this port must never do.
77
+ */
78
+ readonly deliver: (alert: Alert) => Effect.Effect<void, AlertError>;
79
+ }
80
+ declare const Sink_base: Context.ServiceClass<Sink, "/notifications/AlertSink", SinkService>;
81
+ /**
82
+ * The {@link SinkService} tag.
83
+ *
84
+ * @category services
85
+ * @since 0.1.0
86
+ */
87
+ export declare class Sink extends Sink_base {
88
+ }
89
+ /**
90
+ * A sink that accepts every alert and sends it nowhere.
91
+ *
92
+ * The admission and the delivery record still happen, so a composition without
93
+ * an outbound channel still has the durable evidence of what it would have
94
+ * paged about.
95
+ *
96
+ * @category layers
97
+ * @since 0.1.0
98
+ */
99
+ export declare const layerNoop: Layer.Layer<Sink>;
100
+ export {};
101
+ //# sourceMappingURL=AlertSink.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AlertSink.d.ts","sourceRoot":"","sources":["../../src/AlertSink.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AACvD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AAE7C;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,WAAW,uGAA+F,CAAA;AAEvH;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GAAG,OAAO,WAAW,CAAC,IAAI,CAAA;;;;IAkB7C,wEAAwE;;IAExE,qEAAqE;;;AAlBzE;;;;;;;;;;GAUG;AACH,qBAAa,UAAW,SAAQ,eAU/B;CAAG;AAEJ;;;;;;;;;GASG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;CACpE;;AAED;;;;;GAKG;AACH,qBAAa,IAAK,SAAQ,SAAgE;CAAG;AAE7F;;;;;;;;;GASG;AACH,eAAO,MAAM,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,IAAI,CAAuD,CAAA"}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var AlertSink_exports = {};
20
+ __export(AlertSink_exports, {
21
+ AlertError: () => AlertError,
22
+ FailureCode: () => FailureCode,
23
+ Sink: () => Sink,
24
+ layerNoop: () => layerNoop
25
+ });
26
+ module.exports = __toCommonJS(AlertSink_exports);
27
+ var import_effect = require("effect");
28
+ const FailureCode = import_effect.Schema.Literals(["sink_rejected", "sink_unreachable", "sink_timeout", "sink_misconfigured"]);
29
+ class AlertError extends import_effect.Schema.TaggedError()(
30
+ "/notifications/AlertError",
31
+ {
32
+ code: FailureCode.pipe(import_effect.Schema.withConstructorDefault(import_effect.Effect.succeed("sink_rejected"))),
33
+ message: import_effect.Schema.String,
34
+ /** The HTTP status that refused the page, when the sink speaks HTTP. */
35
+ status: import_effect.Schema.optional(import_effect.Schema.Int),
36
+ /** A short, credential-free description of the transport failure. */
37
+ reason: import_effect.Schema.optional(import_effect.Schema.String)
38
+ }
39
+ ) {
40
+ }
41
+ class Sink extends import_effect.Context.Service()("/notifications/AlertSink") {
42
+ }
43
+ const layerNoop = import_effect.Layer.succeed(Sink)({ deliver: () => import_effect.Effect.void });
44
+ //# sourceMappingURL=AlertSink.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/AlertSink.ts"],
4
+ "sourcesContent": ["/**\n * The alert sink port: where a raised alert is sent, and why a send failed.\n *\n * The port is a tag and an error so a deployment supplies the transport and\n * the policy needs none. `./layerWebhook.ts` is the transport this package\n * ships, and {@link layerNoop} is the one a test composes.\n *\n * @since 1.0.0\n */\n\nimport { Context, Effect, Layer, Schema } from \"effect\"\nimport type { Alert } from \"./AlertPolicy.ts\"\n\n/**\n * Why a sink did not take an alert.\n *\n * `sink_rejected` is an answer that refused the page, `sink_unreachable` a\n * request that never got one, and `sink_timeout` one that got no answer inside\n * the sink's bound. `sink_misconfigured` is an endpoint the sink may not POST\n * to at all; it is raised when the layer is built, before any alert exists,\n * so it never reaches a journal.\n *\n * @category models\n * @since 1.0.0\n */\nexport const FailureCode = Schema.Literals([\"sink_rejected\", \"sink_unreachable\", \"sink_timeout\", \"sink_misconfigured\"])\n\n/**\n * Why a sink did not take an alert.\n *\n * @category models\n * @since 1.0.0\n */\nexport type FailureCode = typeof FailureCode.Type\n\n/**\n * A sink refused or could not take an alert.\n *\n * The error carries a code, the answering status when there was one, and a\n * short reason. It deliberately holds no request: a webhook request carries\n * the credential the deployment handed {@link layerWebhook}, and an error is\n * logged, encoded, and journaled in places a credential must never reach.\n *\n * @category errors\n * @since 0.1.0\n */\nexport class AlertError extends Schema.TaggedError<AlertError>()(\n \"/notifications/AlertError\",\n {\n code: FailureCode.pipe(Schema.withConstructorDefault(Effect.succeed(\"sink_rejected\" as const))),\n message: Schema.String,\n /** The HTTP status that refused the page, when the sink speaks HTTP. */\n status: Schema.optional(Schema.Int),\n /** A short, credential-free description of the transport failure. */\n reason: Schema.optional(Schema.String)\n }\n) {}\n\n/**\n * Where a raised alert is sent.\n *\n * Injected rather than fixed, because who gets paged is a deployment's\n * decision and the policy is not: the same rules feed a webhook in production\n * and nothing at all in a test.\n *\n * @category services\n * @since 0.1.0\n */\nexport interface SinkService {\n /**\n * Sends one alert, and does so idempotently on {@link alertId}.\n *\n * Delivery is at-least-once: the `flows.alerts.delivered` record is written\n * after this effect succeeds, so a process that dies in between pages again\n * on the next tick. Every field of the alert, {@link Alert.firedAt}\n * included, is derived from the journal, so the same alert is byte-identical\n * on every attempt and `alertId(alert)` is the deduplication key a receiving\n * system should key on. A sink that cannot dedupe is a sink that will\n * occasionally page twice about one condition.\n *\n * A failure means the page did not go out. Succeeding on a page that was\n * dropped is the one thing this port must never do.\n */\n readonly deliver: (alert: Alert) => Effect.Effect<void, AlertError>\n}\n\n/**\n * The {@link SinkService} tag.\n *\n * @category services\n * @since 0.1.0\n */\nexport class Sink extends Context.Service<Sink, SinkService>()(\"/notifications/AlertSink\") {}\n\n/**\n * A sink that accepts every alert and sends it nowhere.\n *\n * The admission and the delivery record still happen, so a composition without\n * an outbound channel still has the durable evidence of what it would have\n * paged about.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerNoop: Layer.Layer<Sink> = Layer.succeed(Sink)({ deliver: () => Effect.void })\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,oBAA+C;AAexC,MAAM,cAAc,qBAAO,SAAS,CAAC,iBAAiB,oBAAoB,gBAAgB,oBAAoB,CAAC;AAqB/G,MAAM,mBAAmB,qBAAO,YAAwB;AAAA,EAC7D;AAAA,EACA;AAAA,IACE,MAAM,YAAY,KAAK,qBAAO,uBAAuB,qBAAO,QAAQ,eAAwB,CAAC,CAAC;AAAA,IAC9F,SAAS,qBAAO;AAAA;AAAA,IAEhB,QAAQ,qBAAO,SAAS,qBAAO,GAAG;AAAA;AAAA,IAElC,QAAQ,qBAAO,SAAS,qBAAO,MAAM;AAAA,EACvC;AACF,EAAE;AAAC;AAoCI,MAAM,aAAa,sBAAQ,QAA2B,EAAE,0BAA0B,EAAE;AAAC;AAYrF,MAAM,YAA+B,oBAAM,QAAQ,IAAI,EAAE,EAAE,SAAS,MAAM,qBAAO,KAAK,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Alert policy: run conditions that have lasted too long, turned into durable,
3
+ * coalesced, delivered-once notifications.
4
+ *
5
+ * A notification queue answers "tell this run something". An alert answers the
6
+ * question nobody is around to ask: a run has been waiting for an approval for
7
+ * an hour, and the person who could grant it does not know. The two are the
8
+ * same machinery, since an alert is admitted as a coalesced system event, and
9
+ * they differ only in who decides to write one.
10
+ *
11
+ * ## Journal time, not wall time
12
+ *
13
+ * A condition's clock starts at the journal entry that opened it, which makes
14
+ * the decision replayable: the same journal produces the same alerts, whatever
15
+ * process reads it and whenever. A restart re-derives every open condition
16
+ * from the entries rather than from a timer it lost.
17
+ *
18
+ * ## Delivered at least once
19
+ *
20
+ * The admission is idempotent on the notification id, so re-admitting the same
21
+ * alert writes nothing new, and `flows.alerts.delivered` is journaled AFTER
22
+ * the sink accepted the page and is checked before the sink is called again.
23
+ * That ordering is deliberate and it is the reason the guarantee is
24
+ * at-least-once rather than exactly-once: a process that dies between the
25
+ * accepted send and the delivery record has paged, left no evidence of it, and
26
+ * will page again on the next tick. Recording the delivery first turns the
27
+ * same crash into a page nobody ever receives, which for an alert is the worse
28
+ * failure.
29
+ *
30
+ * So the sink owns the last mile: {@link SinkService.deliver} MUST be
31
+ * idempotent on {@link alertId}, which is stable for the life of one condition
32
+ * and reaches the sink on every alert it is handed. A sink that fails journals
33
+ * `flows.alerts.failed` once per failure code and the alert is retried on the
34
+ * next tick, because a refused page is not a delivered page.
35
+ *
36
+ * ## What a refusal costs
37
+ *
38
+ * The queue can refuse the admission when a run already holds its capacity of
39
+ * pending notifications. A tick that is refused pages nobody: the alert comes
40
+ * back in {@link Tick.refused}, the refusal is journaled, and the next tick
41
+ * tries again once a boundary has drained. Calling the sink anyway would page
42
+ * about an alert the run will never see.
43
+ *
44
+ * ## Conditions are data
45
+ *
46
+ * A condition is a payload field with a value: `status` is `waiting-approval`,
47
+ * `health` is `stalled`. Those are the fields control-plane entries and monitor
48
+ * beats already carry, so a deployment that journals a different vocabulary
49
+ * supplies its own detectors instead of a fork of this module.
50
+ *
51
+ * @since 0.1.0
52
+ */
53
+ export { type Alert, alertId, coalescingKey, conditions, decide, defaultDetectors, deliveredEventType, Detector, failedEventType, type Open, Policy, Rule, Severity } from "./AlertPolicy.ts";
54
+ export { AlertRuntime, layer, type RuntimeService, type Tick } from "./AlertRuntime.ts";
55
+ export { AlertError, FailureCode, layerNoop, Sink, type SinkService } from "./AlertSink.ts";
56
+ export { defaultWebhookTimeout, layerWebhook } from "./layerWebhook.ts";
57
+ //# sourceMappingURL=Alerts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Alerts.d.ts","sourceRoot":"","sources":["../../src/Alerts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH,OAAO,EACL,KAAK,KAAK,EACV,OAAO,EACP,aAAa,EACb,UAAU,EACV,MAAM,EACN,gBAAgB,EAChB,kBAAkB,EAClB,QAAQ,EACR,eAAe,EACf,KAAK,IAAI,EACT,MAAM,EACN,IAAI,EACJ,QAAQ,EACT,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,cAAc,EAAE,KAAK,IAAI,EAAE,MAAM,mBAAmB,CAAA;AACvF,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC3F,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA"}
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var Alerts_exports = {};
20
+ __export(Alerts_exports, {
21
+ AlertError: () => import_AlertSink.AlertError,
22
+ AlertRuntime: () => import_AlertRuntime.AlertRuntime,
23
+ Detector: () => import_AlertPolicy.Detector,
24
+ FailureCode: () => import_AlertSink.FailureCode,
25
+ Policy: () => import_AlertPolicy.Policy,
26
+ Rule: () => import_AlertPolicy.Rule,
27
+ Severity: () => import_AlertPolicy.Severity,
28
+ Sink: () => import_AlertSink.Sink,
29
+ alertId: () => import_AlertPolicy.alertId,
30
+ coalescingKey: () => import_AlertPolicy.coalescingKey,
31
+ conditions: () => import_AlertPolicy.conditions,
32
+ decide: () => import_AlertPolicy.decide,
33
+ defaultDetectors: () => import_AlertPolicy.defaultDetectors,
34
+ defaultWebhookTimeout: () => import_layerWebhook.defaultWebhookTimeout,
35
+ deliveredEventType: () => import_AlertPolicy.deliveredEventType,
36
+ failedEventType: () => import_AlertPolicy.failedEventType,
37
+ layer: () => import_AlertRuntime.layer,
38
+ layerNoop: () => import_AlertSink.layerNoop,
39
+ layerWebhook: () => import_layerWebhook.layerWebhook
40
+ });
41
+ module.exports = __toCommonJS(Alerts_exports);
42
+ var import_AlertPolicy = require("./AlertPolicy.js");
43
+ var import_AlertRuntime = require("./AlertRuntime.js");
44
+ var import_AlertSink = require("./AlertSink.js");
45
+ var import_layerWebhook = require("./layerWebhook.js");
46
+ //# sourceMappingURL=Alerts.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/Alerts.ts"],
4
+ "sourcesContent": ["/**\n * Alert policy: run conditions that have lasted too long, turned into durable,\n * coalesced, delivered-once notifications.\n *\n * A notification queue answers \"tell this run something\". An alert answers the\n * question nobody is around to ask: a run has been waiting for an approval for\n * an hour, and the person who could grant it does not know. The two are the\n * same machinery, since an alert is admitted as a coalesced system event, and\n * they differ only in who decides to write one.\n *\n * ## Journal time, not wall time\n *\n * A condition's clock starts at the journal entry that opened it, which makes\n * the decision replayable: the same journal produces the same alerts, whatever\n * process reads it and whenever. A restart re-derives every open condition\n * from the entries rather than from a timer it lost.\n *\n * ## Delivered at least once\n *\n * The admission is idempotent on the notification id, so re-admitting the same\n * alert writes nothing new, and `flows.alerts.delivered` is journaled AFTER\n * the sink accepted the page and is checked before the sink is called again.\n * That ordering is deliberate and it is the reason the guarantee is\n * at-least-once rather than exactly-once: a process that dies between the\n * accepted send and the delivery record has paged, left no evidence of it, and\n * will page again on the next tick. Recording the delivery first turns the\n * same crash into a page nobody ever receives, which for an alert is the worse\n * failure.\n *\n * So the sink owns the last mile: {@link SinkService.deliver} MUST be\n * idempotent on {@link alertId}, which is stable for the life of one condition\n * and reaches the sink on every alert it is handed. A sink that fails journals\n * `flows.alerts.failed` once per failure code and the alert is retried on the\n * next tick, because a refused page is not a delivered page.\n *\n * ## What a refusal costs\n *\n * The queue can refuse the admission when a run already holds its capacity of\n * pending notifications. A tick that is refused pages nobody: the alert comes\n * back in {@link Tick.refused}, the refusal is journaled, and the next tick\n * tries again once a boundary has drained. Calling the sink anyway would page\n * about an alert the run will never see.\n *\n * ## Conditions are data\n *\n * A condition is a payload field with a value: `status` is `waiting-approval`,\n * `health` is `stalled`. Those are the fields control-plane entries and monitor\n * beats already carry, so a deployment that journals a different vocabulary\n * supplies its own detectors instead of a fork of this module.\n *\n * @since 0.1.0\n */\n\nexport {\n type Alert,\n alertId,\n coalescingKey,\n conditions,\n decide,\n defaultDetectors,\n deliveredEventType,\n Detector,\n failedEventType,\n type Open,\n Policy,\n Rule,\n Severity\n} from \"./AlertPolicy.ts\"\nexport { AlertRuntime, layer, type RuntimeService, type Tick } from \"./AlertRuntime.ts\"\nexport { AlertError, FailureCode, layerNoop, Sink, type SinkService } from \"./AlertSink.ts\"\nexport { defaultWebhookTimeout, layerWebhook } from \"./layerWebhook.ts\"\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqDA,yBAcO;AACP,0BAAoE;AACpE,uBAA2E;AAC3E,0BAAoD;",
6
+ "names": []
7
+ }