@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,194 @@
1
+ /**
2
+ * Journal-backed durable notification admission and turn-boundary drain.
3
+ *
4
+ * Governing contract: `packages/smithers/notifications/docs/api.md`, published as
5
+ * `/api/notifications`.
6
+ *
7
+ * @since 0.1.0
8
+ */
9
+ import { Journal } from "@smthrs/journal";
10
+ import { Context, Effect, Layer, Schema } from "effect";
11
+ import * as NotificationModel from "./Notification.ts";
12
+ import * as NotificationState from "./NotificationState.ts";
13
+ declare const NotificationError_base: Schema.Class<NotificationError, Schema.TaggedStruct<"/notifications/NotificationError", {
14
+ readonly code: Schema.withConstructorDefault<Schema.Literals<readonly ["notification_unavailable", "notification_closed", "notification_full", "notification_id_reused", "notification_invalid", "notification_refused"]>>;
15
+ readonly message: Schema.String;
16
+ /** The notification the failure is about, when one was readable. */
17
+ readonly notificationId: Schema.optional<Schema.String>;
18
+ /** Dotted path of the offending field, for `notification_invalid`. */
19
+ readonly path: Schema.optional<Schema.String>;
20
+ }>, import("effect/Cause").YieldableError>;
21
+ /**
22
+ * The queue could not be reached, or it refused what a caller handed it.
23
+ *
24
+ * `code` is the stable half and the one to branch on. `notification_unavailable`
25
+ * is the seam reporting that it serves nothing; `notification_id_reused` says a
26
+ * stable id was admitted once already with different content, which is a
27
+ * producer bug rather than a storage failure; `notification_invalid` says the
28
+ * value is not a notification, and `path` names the field inside it that failed.
29
+ * `notification_closed` means the receiver has finished and the caller must
30
+ * start a new request; `notification_full` means nothing was retained and the
31
+ * same notification may be retried after pending work drains. Neither the
32
+ * message nor `path` ever carries the offending value.
33
+ * `notification_refused` rejects reserved outside-change payloads before admission.
34
+ *
35
+ * @category errors
36
+ * @since 0.1.0
37
+ */
38
+ export declare class NotificationError extends NotificationError_base {
39
+ }
40
+ /**
41
+ * What admitting one notification decided.
42
+ *
43
+ * `seq` is the journal sequence the admission committed at, and it is absent
44
+ * exactly when nothing was written, which today means a `rejected-full`
45
+ * refusal. `duplicate` says the id was already admitted, in which case
46
+ * `decision` and `seq` are read back from the committed record rather than
47
+ * recomputed here.
48
+ *
49
+ * A caller MUST inspect `decision`: `rejected-full` means the queue was at
50
+ * capacity and retained nothing, so the notification never reaches the model
51
+ * unless the caller admits it again once a boundary has drained.
52
+ *
53
+ * @category models
54
+ * @since 0.1.0
55
+ */
56
+ export interface AdmissionReceipt {
57
+ readonly notificationId: string;
58
+ readonly decision: NotificationState.AdmissionDecision;
59
+ readonly seq: number | undefined;
60
+ readonly duplicate: boolean;
61
+ readonly consumed?: boolean;
62
+ readonly consumedNotification?: NotificationModel.Notification;
63
+ }
64
+ /**
65
+ * The boundary a drain is attempted at, and whether the run would go idle
66
+ * if nothing were delivered.
67
+ *
68
+ * `(runId, targetLineageId, boundary)` is the unit of drain: two lineages
69
+ * closing a turn under the same boundary name are two drains, and each is
70
+ * recorded separately.
71
+ *
72
+ * @category models
73
+ * @since 0.1.0
74
+ */
75
+ export interface DrainInput {
76
+ readonly runId: string;
77
+ readonly targetLineageId: string;
78
+ readonly boundary: string;
79
+ readonly wouldIdle: boolean;
80
+ /**
81
+ * The journal sequence that opened this turn. A steer admitted after it is
82
+ * held for the next boundary, which is what keeps a message that arrived
83
+ * mid-turn out of the turn already in flight. Omitting it delivers
84
+ * everything pending for the lineage. A value that is not a non-negative
85
+ * integer fails the drain with `notification_invalid` and records nothing.
86
+ */
87
+ readonly cutoffSeq?: number | undefined;
88
+ }
89
+ /**
90
+ * The notifications this boundary delivers, and whether the boundary had
91
+ * already drained.
92
+ *
93
+ * The notifications are the ones the committed promotion record names, so two
94
+ * processes draining one boundary report the same delivery rather than two
95
+ * divergent guesses.
96
+ *
97
+ * @category models
98
+ * @since 0.1.0
99
+ */
100
+ export interface DrainReceipt {
101
+ readonly notifications: ReadonlyArray<NotificationModel.Notification>;
102
+ readonly boundary: string;
103
+ readonly duplicate: boolean;
104
+ }
105
+ /**
106
+ * The durable pending queue: admit a notification exactly once, and drain
107
+ * what a boundary is allowed to deliver.
108
+ *
109
+ * @category services
110
+ * @since 0.1.0
111
+ */
112
+ export interface Service {
113
+ readonly admit: (runId: string, notification: NotificationModel.Notification, version?: number) => Effect.Effect<AdmissionReceipt, Journal.JournalError | NotificationError>;
114
+ readonly drain: (input: DrainInput) => Effect.Effect<DrainReceipt, Journal.JournalError | NotificationError>;
115
+ /**
116
+ * What this run has been told that no boundary has delivered yet, in
117
+ * admission order.
118
+ *
119
+ * The queue is the owner of that fact: pending is admitted minus promoted,
120
+ * and both halves are its own journal records. A supervisor that counted
121
+ * admissions alone would report a steer as waiting forever.
122
+ */
123
+ readonly pending: (runId: string) => Effect.Effect<ReadonlyArray<NotificationModel.Notification>, Journal.JournalError | NotificationError>;
124
+ }
125
+ declare const NotificationQueue_base: Context.ServiceClass<NotificationQueue, "/notifications/NotificationQueue", Service>;
126
+ /**
127
+ * The {@link Service} tag.
128
+ *
129
+ * @category services
130
+ * @since 0.1.0
131
+ */
132
+ export declare class NotificationQueue extends NotificationQueue_base {
133
+ }
134
+ /**
135
+ * Builds a {@link Service} from an implementation of its methods.
136
+ *
137
+ * @param implementation the methods to serve
138
+ * @category constructors
139
+ * @since 0.1.0
140
+ */
141
+ export declare const make: (implementation: Service) => Service;
142
+ /**
143
+ * A {@link Service} that fails every method as unavailable. Overrides
144
+ * replace individual methods.
145
+ *
146
+ * @param overrides methods to serve instead of failing
147
+ * @category constructors
148
+ * @since 0.1.0
149
+ */
150
+ export declare const makeNoop: (overrides?: Partial<Service>) => Service;
151
+ /**
152
+ * Provides {@link makeNoop}.
153
+ *
154
+ * @param overrides methods to serve instead of failing
155
+ * @category layers
156
+ * @since 0.1.0
157
+ */
158
+ export declare const layerNoop: (overrides?: Partial<Service>) => Layer.Layer<NotificationQueue>;
159
+ /**
160
+ * Journal-backed production layer, with the pending capacity a composition
161
+ * chooses.
162
+ *
163
+ * Admission and drain evidence is written through `emitDurableUnfenced`, so
164
+ * both return only after the corresponding entry is durably committed and a
165
+ * dropped lifecycle event is unrepresentable. The channel is the unfenced one
166
+ * on purpose: the notifying process owns no run, so there is no ownership
167
+ * fence to hand over, and both records are first-writer-wins on their own
168
+ * identity instead.
169
+ *
170
+ * The capacity guard is a conditional write at the storage layer, not a check
171
+ * against a fold one process happened to load: the fold, the guard, and the
172
+ * admission record are decided and written inside ONE `journal.transact`
173
+ * write transaction, which the durable writer serializes against every other
174
+ * writer of the database and replays when a concurrent writer commits between
175
+ * the guard's reads and the insert. Two processes admitting to one full queue
176
+ * therefore produce one admission and one `rejected-full`, never two
177
+ * admissions.
178
+ *
179
+ * @param options the pending capacity, defaulting to `NotificationState.defaultCapacity`
180
+ * @category layers
181
+ * @since 1.0.0
182
+ */
183
+ export declare const layerWith: (options?: {
184
+ readonly capacity?: number | undefined;
185
+ }) => Layer.Layer<NotificationQueue, never, Journal.Journal>;
186
+ /**
187
+ * Journal-backed production layer at the default capacity.
188
+ *
189
+ * @category layers
190
+ * @since 0.1.0
191
+ */
192
+ export declare const layer: Layer.Layer<NotificationQueue, never, Journal.Journal>;
193
+ export {};
194
+ //# sourceMappingURL=NotificationQueue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NotificationQueue.d.ts","sourceRoot":"","sources":["../../src/NotificationQueue.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,477 @@
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 NotificationQueue_exports = {};
30
+ __export(NotificationQueue_exports, {
31
+ NotificationError: () => NotificationError,
32
+ NotificationQueue: () => NotificationQueue,
33
+ layer: () => layer,
34
+ layerNoop: () => layerNoop,
35
+ layerWith: () => layerWith,
36
+ make: () => make,
37
+ makeNoop: () => makeNoop
38
+ });
39
+ module.exports = __toCommonJS(NotificationQueue_exports);
40
+ var import_canonical = require("@smthrs/canonical");
41
+ var import_Sha256 = require("@smthrs/crypto/Sha256");
42
+ var import_journal = require("@smthrs/journal");
43
+ var import_effect = require("effect");
44
+ var FoldCache = __toESM(require("./internal/foldCache.js"), 1);
45
+ var Replay = __toESM(require("./internal/replay.js"), 1);
46
+ var NotificationModel = __toESM(require("./Notification.js"), 1);
47
+ var NotificationEvent = __toESM(require("./NotificationEvent.js"), 1);
48
+ var NotificationState = __toESM(require("./NotificationState.js"), 1);
49
+ class NotificationError extends import_effect.Schema.TaggedError()(
50
+ "/notifications/NotificationError",
51
+ {
52
+ code: import_effect.Schema.Literals([
53
+ "notification_unavailable",
54
+ "notification_closed",
55
+ "notification_full",
56
+ "notification_id_reused",
57
+ "notification_invalid",
58
+ "notification_refused"
59
+ ]).pipe(
60
+ import_effect.Schema.withConstructorDefault(import_effect.Effect.succeed("notification_unavailable"))
61
+ ),
62
+ message: import_effect.Schema.String,
63
+ /** The notification the failure is about, when one was readable. */
64
+ notificationId: import_effect.Schema.optional(import_effect.Schema.String),
65
+ /** Dotted path of the offending field, for `notification_invalid`. */
66
+ path: import_effect.Schema.optional(import_effect.Schema.String)
67
+ }
68
+ ) {
69
+ }
70
+ class NotificationQueue extends import_effect.Context.Service()(
71
+ "/notifications/NotificationQueue"
72
+ ) {
73
+ }
74
+ const make = (implementation) => NotificationQueue.of(implementation);
75
+ const unavailable = (operation) => new NotificationError({ code: "notification_unavailable", message: `${operation} is unavailable` });
76
+ const makeNoop = (overrides = {}) => make({
77
+ admit: import_effect.Effect.fn("NotificationQueue.admit")(() => import_effect.Effect.fail(unavailable("admit"))),
78
+ drain: import_effect.Effect.fn("NotificationQueue.drain")(() => import_effect.Effect.fail(unavailable("drain"))),
79
+ pending: import_effect.Effect.fn("NotificationQueue.pending")(() => import_effect.Effect.fail(unavailable("pending"))),
80
+ ...overrides
81
+ });
82
+ const layerNoop = (overrides = {}) => import_effect.Layer.succeed(NotificationQueue)(makeNoop(overrides));
83
+ const maximumPayloadDepth = 256;
84
+ const maximumNotificationCodeUnits = 1048576;
85
+ const maximumIssueCodeUnits = 200;
86
+ const exceededBound = (value) => {
87
+ const pending = [{ value, depth: 0 }];
88
+ let size = 0;
89
+ while (pending.length > 0) {
90
+ const next = pending.pop();
91
+ size += typeof next.value === "string" ? next.value.length : 1;
92
+ if (size > maximumNotificationCodeUnits) return "size";
93
+ if (typeof next.value !== "object" || next.value === null) continue;
94
+ if (next.depth >= maximumPayloadDepth) return "depth";
95
+ if (Array.isArray(next.value)) {
96
+ for (const child of next.value) pending.push({ value: child, depth: next.depth + 1 });
97
+ continue;
98
+ }
99
+ for (const [key, child] of Object.entries(next.value)) {
100
+ size += key.length;
101
+ pending.push({ value: child, depth: next.depth + 1 });
102
+ }
103
+ }
104
+ return void 0;
105
+ };
106
+ const copied = (value) => {
107
+ if (Array.isArray(value)) return value.map(copied);
108
+ if (typeof value === "object" && value !== null) {
109
+ return Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, copied(nested)]));
110
+ }
111
+ return value;
112
+ };
113
+ const formatIssue = import_effect.SchemaIssue.makeFormatterStandardSchemaV1({ leafHook: (issue) => issue._tag });
114
+ const bounded = (text) => text.length <= maximumIssueCodeUnits ? text : `${text.slice(0, maximumIssueCodeUnits - 3)}...`;
115
+ const identifiedBy = (value) => {
116
+ if (typeof value !== "object" || value === null) return void 0;
117
+ const id = value["id"];
118
+ return typeof id === "string" ? id : void 0;
119
+ };
120
+ const decodeNotification = import_effect.Schema.decodeUnknownEffect(NotificationModel.Notification);
121
+ const validated = (notification) => import_effect.Effect.gen(function* () {
122
+ const notificationId = identifiedBy(notification);
123
+ const exceeded = exceededBound(notification);
124
+ if (exceeded !== void 0) {
125
+ return yield* new NotificationError({
126
+ code: "notification_invalid",
127
+ message: exceeded === "depth" ? `A notification nests deeper than the ${maximumPayloadDepth} level bound` : `A notification is larger than the ${maximumNotificationCodeUnits} code unit bound`,
128
+ ...notificationId === void 0 ? {} : { notificationId }
129
+ });
130
+ }
131
+ return yield* decodeNotification(copied(notification)).pipe(
132
+ import_effect.Effect.mapError((error) => {
133
+ const issue = formatIssue(error.issue).issues[0];
134
+ const path = issue.path.map(String).join(".");
135
+ return new NotificationError({
136
+ code: "notification_invalid",
137
+ message: bounded(issue.message),
138
+ ...notificationId === void 0 ? {} : { notificationId },
139
+ ...path === "" ? {} : { path }
140
+ });
141
+ })
142
+ );
143
+ });
144
+ const canonical = (value) => (0, import_canonical.canonicalize)(value, { loneSurrogates: "escape" });
145
+ const fingerprint = (notification) => import_effect.Effect.sync(() => (0, import_Sha256.digestSync)(canonical(notification)));
146
+ const freeze = (value) => {
147
+ if (typeof value !== "object" || value === null) return;
148
+ for (const nested of Object.values(value)) freeze(nested);
149
+ Object.freeze(value);
150
+ };
151
+ const maximumCachedRuns = 64;
152
+ const layerWith = (options = {}) => import_effect.Layer.effect(
153
+ NotificationQueue,
154
+ import_effect.Effect.gen(function* () {
155
+ const journal = yield* import_journal.Journal.Journal;
156
+ const operations = yield* import_effect.Semaphore.make(1);
157
+ const capacity = options.capacity ?? NotificationState.defaultCapacity;
158
+ const folded = FoldCache.make(maximumCachedRuns);
159
+ const entryAt = (runId, seq) => import_effect.Effect.map(
160
+ journal.entries({
161
+ runId,
162
+ ...seq === 0 ? {} : { after: import_journal.JournalEvent.Seq.make(seq - 1) },
163
+ limit: 1
164
+ }),
165
+ (page) => {
166
+ const found = page.entries[0];
167
+ return found !== void 0 && found.seq === seq ? import_effect.Option.some(found) : import_effect.Option.none();
168
+ }
169
+ );
170
+ const admittedAt = (runId, seq) => import_effect.Effect.map(entryAt(runId, seq), (entry) => {
171
+ if (import_effect.Option.isNone(entry)) return import_effect.Option.none();
172
+ const decoded = NotificationEvent.fromEntry(entry.value);
173
+ if (import_effect.Option.isNone(decoded) || !NotificationEvent.isAdmitted(decoded.value)) return import_effect.Option.none();
174
+ freeze(decoded.value.notification);
175
+ return import_effect.Option.some(decoded.value);
176
+ });
177
+ const promotedAt = (runId, seq) => import_effect.Effect.map(entryAt(runId, seq), (entry) => {
178
+ if (import_effect.Option.isNone(entry)) return import_effect.Option.none();
179
+ const decoded = NotificationEvent.fromEntry(entry.value);
180
+ if (import_effect.Option.isNone(decoded) || !NotificationEvent.isPromoted(decoded.value)) return import_effect.Option.none();
181
+ return import_effect.Option.some(decoded.value);
182
+ });
183
+ const load = (runId) => import_effect.Effect.gen(function* () {
184
+ const base = folded.get(runId) ?? {
185
+ state: NotificationState.empty(capacity),
186
+ admissions: import_effect.HashMap.empty(),
187
+ promotions: import_effect.HashMap.empty(),
188
+ cursor: void 0
189
+ };
190
+ const fresh = [];
191
+ let after = base.cursor === void 0 ? void 0 : import_journal.JournalEvent.Seq.make(base.cursor);
192
+ while (true) {
193
+ const page = yield* journal.entries({
194
+ runId,
195
+ eventTypes: [NotificationEvent.AdmittedEventType, NotificationEvent.PromotedEventType],
196
+ ...after === void 0 ? {} : { after },
197
+ limit: 512
198
+ });
199
+ fresh.push(...page.entries);
200
+ if (!page.hasMore || page.entries.length === 0) break;
201
+ after = page.entries.at(-1).seq;
202
+ }
203
+ if (fresh.length === 0) return base;
204
+ let state = base.state;
205
+ let cursor = base.cursor;
206
+ let admissions = base.admissions;
207
+ let promotions = base.promotions;
208
+ for (const entry of fresh) {
209
+ cursor = entry.seq;
210
+ const decoded = NotificationEvent.fromEntry(entry);
211
+ if (import_effect.Option.isNone(decoded)) continue;
212
+ const event = decoded.value;
213
+ if (NotificationEvent.isAdmitted(event)) {
214
+ freeze(event.notification);
215
+ admissions = import_effect.HashMap.set(admissions, event.notification.id, {
216
+ version: event.version,
217
+ fingerprint: event.fingerprint,
218
+ decision: event.decision,
219
+ seq: entry.seq
220
+ });
221
+ state = Replay.applyAdmitted(state, event, entry.seq);
222
+ } else {
223
+ promotions = import_effect.HashMap.set(
224
+ promotions,
225
+ NotificationEvent.drainKey(event.targetLineageId, event.boundary),
226
+ entry.seq
227
+ );
228
+ state = NotificationState.applyPromoted(state, event.ids);
229
+ }
230
+ }
231
+ const loaded = { state, admissions, promotions, cursor };
232
+ yield* journal.whenCommitted(import_effect.Effect.sync(() => folded.put(runId, loaded)));
233
+ return loaded;
234
+ });
235
+ const admitInTransaction = (runId, admitted, admittedFingerprint, version) => import_effect.Effect.gen(function* () {
236
+ const loaded = yield* load(runId);
237
+ const prior = import_effect.Option.getOrUndefined(import_effect.HashMap.get(loaded.admissions, admitted.id));
238
+ const replacing = prior !== void 0 && version !== void 0 && version > (prior.version ?? 0);
239
+ if (replacing) {
240
+ const original = yield* admittedAt(runId, prior.seq);
241
+ if (import_effect.Option.isNone(original)) {
242
+ return yield* new NotificationError({
243
+ code: "notification_unavailable",
244
+ notificationId: admitted.id,
245
+ message: "Original steering input is unreadable"
246
+ });
247
+ }
248
+ const identity = (input) => ({ ...input, payload: null });
249
+ if (canonical(identity(original.value.notification)) !== canonical(identity(admitted))) {
250
+ return yield* new NotificationError({
251
+ code: "notification_id_reused",
252
+ notificationId: admitted.id,
253
+ message: "An edit cannot change the notification owner or delivery binding"
254
+ });
255
+ }
256
+ }
257
+ if (replacing && !loaded.state.items.some((item) => item.notification.id === admitted.id)) {
258
+ const original = yield* admittedAt(runId, prior.seq);
259
+ if (import_effect.Option.isNone(original)) {
260
+ return yield* new NotificationError({
261
+ code: "notification_unavailable",
262
+ message: "Consumed input is unreadable"
263
+ });
264
+ }
265
+ return {
266
+ notificationId: admitted.id,
267
+ decision: prior.decision,
268
+ seq: prior.seq,
269
+ duplicate: true,
270
+ consumed: true,
271
+ consumedNotification: original.value.notification
272
+ };
273
+ }
274
+ if (prior !== void 0 && version !== void 0 && version < (prior.version ?? 0)) {
275
+ return { notificationId: admitted.id, decision: prior.decision, seq: prior.seq, duplicate: true };
276
+ }
277
+ if (prior !== void 0 && !replacing) {
278
+ let same = prior.fingerprint === admittedFingerprint;
279
+ if (prior.fingerprint === void 0) {
280
+ const original = yield* admittedAt(runId, prior.seq);
281
+ if (import_effect.Option.isNone(original)) {
282
+ return yield* new NotificationError({
283
+ code: "notification_unavailable",
284
+ notificationId: admitted.id,
285
+ message: `The admission for notification ${admitted.id} is no longer readable`
286
+ });
287
+ }
288
+ same = canonical(original.value.notification) === canonical(admitted);
289
+ }
290
+ if (!same) {
291
+ return yield* new NotificationError({
292
+ code: "notification_id_reused",
293
+ notificationId: admitted.id,
294
+ message: `Notification id ${admitted.id} was already admitted with different content`
295
+ });
296
+ }
297
+ return {
298
+ notificationId: admitted.id,
299
+ decision: prior.decision,
300
+ seq: prior.seq,
301
+ duplicate: true
302
+ };
303
+ }
304
+ const admission = replacing ? { decision: "coalesced" } : NotificationState.admit(
305
+ loaded.state,
306
+ admitted,
307
+ loaded.cursor === void 0 ? 0 : loaded.cursor + 1
308
+ );
309
+ if (admission.decision === "rejected-full") {
310
+ return {
311
+ notificationId: admitted.id,
312
+ decision: admission.decision,
313
+ seq: void 0,
314
+ duplicate: false
315
+ };
316
+ }
317
+ const receipt = yield* journal.emitDurableUnfenced(
318
+ new import_journal.JournalEvent.Input({
319
+ runId,
320
+ sourceId: NotificationEvent.admissionSourceId(admitted.id),
321
+ sourceSeq: import_journal.JournalEvent.SourceSeq.make(version ?? 0),
322
+ // The sequence is derived from the notification's own id, so
323
+ // a collision IS this admission observed twice. Comparing
324
+ // bytes instead would fail the second writer over `decision`,
325
+ // a field neither caller supplied and each derives from the
326
+ // fill level it happened to load at.
327
+ dedupe: "identity",
328
+ eventType: NotificationEvent.AdmittedEventType,
329
+ payload: {
330
+ notification: admitted,
331
+ decision: admission.decision,
332
+ fingerprint: admittedFingerprint,
333
+ ...version === void 0 ? {} : { version }
334
+ }
335
+ })
336
+ );
337
+ const committed = import_effect.Option.getOrUndefined(import_effect.HashMap.get((yield* load(runId)).admissions, admitted.id));
338
+ if (committed === void 0) {
339
+ return yield* new NotificationError({
340
+ code: "notification_id_reused",
341
+ notificationId: admitted.id,
342
+ message: `The journal identity for notification ${admitted.id} holds an event this queue did not write`
343
+ });
344
+ }
345
+ return {
346
+ notificationId: admitted.id,
347
+ decision: committed.decision,
348
+ seq: committed.seq,
349
+ duplicate: receipt._tag === "Duplicate"
350
+ };
351
+ });
352
+ return make({
353
+ admit: import_effect.Effect.fn("NotificationQueue.admit")(
354
+ (rawRunId, notification, version) => import_effect.Effect.gen(function* () {
355
+ if (version !== void 0 && (!Number.isSafeInteger(version) || version < 1)) {
356
+ return yield* new NotificationError({
357
+ code: "notification_invalid",
358
+ message: "version must be a positive safe integer"
359
+ });
360
+ }
361
+ const admitted = yield* validated(notification);
362
+ const payload = admitted.payload;
363
+ if (typeof payload === "object" && payload !== null && !Array.isArray(payload) && payload["kind"] === "outside_change") {
364
+ return yield* new NotificationError({
365
+ code: "notification_refused",
366
+ notificationId: admitted.id,
367
+ message: "Outside-change delivery requires authenticated watcher facts and stale-write enforcement"
368
+ });
369
+ }
370
+ const admittedFingerprint = yield* fingerprint(admitted);
371
+ return yield* journal.transact(
372
+ operations.withPermits(1)(
373
+ admitInTransaction(import_journal.JournalEvent.RunId.make(rawRunId), admitted, admittedFingerprint, version)
374
+ )
375
+ );
376
+ })
377
+ ),
378
+ drain: import_effect.Effect.fn("NotificationQueue.drain")(
379
+ (input) => journal.transact(
380
+ operations.withPermits(1)(import_effect.Effect.gen(function* () {
381
+ if (input.cutoffSeq !== void 0 && !(Number.isSafeInteger(input.cutoffSeq) && input.cutoffSeq >= 0)) {
382
+ return yield* new NotificationError({
383
+ code: "notification_invalid",
384
+ message: "A drain cutoff must be a non-negative integer journal sequence",
385
+ path: "cutoffSeq"
386
+ });
387
+ }
388
+ const runId = import_journal.JournalEvent.RunId.make(input.runId);
389
+ const key = NotificationEvent.drainKey(input.targetLineageId, input.boundary);
390
+ const loaded = yield* load(runId);
391
+ const delivered = (record, admissions) => import_effect.Effect.forEach(record.ids, (id) => import_effect.Effect.gen(function* () {
392
+ const committed2 = import_effect.HashMap.get(admissions, id);
393
+ const event = import_effect.Option.isNone(committed2) ? import_effect.Option.none() : yield* admittedAt(runId, committed2.value.seq);
394
+ if (import_effect.Option.isNone(event)) {
395
+ return yield* new NotificationError({
396
+ code: "notification_unavailable",
397
+ notificationId: id,
398
+ message: `The delivered notification ${id} is no longer readable`
399
+ });
400
+ }
401
+ return event.value.notification;
402
+ }));
403
+ const replayed = (seq, admissions) => import_effect.Effect.gen(function* () {
404
+ const record = yield* promotedAt(runId, seq);
405
+ if (import_effect.Option.isNone(record)) {
406
+ return yield* new NotificationError({
407
+ code: "notification_unavailable",
408
+ message: `The drain record for boundary ${input.boundary} is no longer readable`
409
+ });
410
+ }
411
+ return {
412
+ notifications: yield* delivered(record.value, admissions),
413
+ boundary: input.boundary,
414
+ duplicate: true
415
+ };
416
+ });
417
+ const prior = import_effect.HashMap.get(loaded.promotions, key);
418
+ if (import_effect.Option.isSome(prior)) return yield* replayed(prior.value, loaded.admissions);
419
+ const cutoff = input.cutoffSeq ?? loaded.cursor ?? 0;
420
+ const promotionState = /^\d+:[a-f0-9]{64}:park:\d+$/.test(input.boundary) ? {
421
+ ...loaded.state,
422
+ items: loaded.state.items.filter((item) => {
423
+ const payload = item.notification.payload;
424
+ return !(typeof payload === "object" && payload !== null && !Array.isArray(payload) && payload.kind === "outside_change");
425
+ })
426
+ } : loaded.state;
427
+ const steers = NotificationState.promoteSteers(promotionState, cutoff, input.targetLineageId);
428
+ const queued = input.wouldIdle && steers.promoted.length === 0 ? NotificationState.promoteQueued(steers.state, input.targetLineageId) : { state: steers.state, promoted: [] };
429
+ const promoted = [...steers.promoted, ...queued.promoted].map((item) => item.notification);
430
+ const receipt = yield* journal.emitDurableUnfenced(
431
+ new import_journal.JournalEvent.Input({
432
+ runId,
433
+ sourceId: NotificationEvent.drainSourceId(input.targetLineageId, input.boundary),
434
+ sourceSeq: import_journal.JournalEvent.SourceSeq.make(0),
435
+ // The identity is the drain: this lineage closing this
436
+ // boundary. Two processes that both reach it have observed one
437
+ // event, and the first record committed is the delivery.
438
+ dedupe: "identity",
439
+ eventType: NotificationEvent.PromotedEventType,
440
+ payload: {
441
+ boundary: input.boundary,
442
+ targetLineageId: input.targetLineageId,
443
+ ids: promoted.map((notification) => notification.id)
444
+ }
445
+ })
446
+ );
447
+ const settled = yield* load(runId);
448
+ const committed = import_effect.HashMap.get(settled.promotions, key);
449
+ if (import_effect.Option.isNone(committed)) {
450
+ return yield* new NotificationError({
451
+ code: "notification_unavailable",
452
+ message: `The journal identity for boundary ${input.boundary} holds an event this queue did not write`
453
+ });
454
+ }
455
+ if (receipt._tag === "Accepted") {
456
+ return { notifications: promoted, boundary: input.boundary, duplicate: false };
457
+ }
458
+ return yield* replayed(committed.value, settled.admissions);
459
+ }))
460
+ )
461
+ ),
462
+ pending: import_effect.Effect.fn("NotificationQueue.pending")(
463
+ (rawRunId) => import_effect.Effect.map(
464
+ load(import_journal.JournalEvent.RunId.make(rawRunId)),
465
+ // The fold `load` already performs: admissions add, promotions
466
+ // remove. Read outside the operations semaphore, because a count
467
+ // taken while a boundary drains is a count taken at some instant
468
+ // either side of it, and blocking a supervisor behind a turn
469
+ // boundary would be the worse answer.
470
+ (loaded) => loaded.state.items.map((item) => item.notification)
471
+ )
472
+ )
473
+ });
474
+ })
475
+ );
476
+ const layer = layerWith();
477
+ //# sourceMappingURL=NotificationQueue.js.map