@smthrs/notifications 1.0.0-rc.7 → 1.0.0-rc.8

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.
package/README.md CHANGED
@@ -10,7 +10,9 @@ runtime.
10
10
 
11
11
  Durable notification queue, admission policy, and journal projection for flows. It models human and system notifications, derives queue state from journal events, and drains eligible work at harness boundaries.
12
12
 
13
- Not on npm yet; see [Installation](https://github.com/smithersai/smithers/blob/main/packages/smithers/flows/flow/docs/installation.md#use-the-libraries).
13
+ ```bash
14
+ npm install @smthrs/notifications@next effect
15
+ ```
14
16
 
15
17
  Node.js 26.4.0 or later. `@smthrs/journal` holds the durable records, and the
16
18
  example below imports it directly, so declare it in your own package too.
@@ -81,7 +81,8 @@ export interface DrainInput {
81
81
  * The journal sequence that opened this turn. A steer admitted after it is
82
82
  * held for the next boundary, which is what keeps a message that arrived
83
83
  * mid-turn out of the turn already in flight. Omitting it delivers
84
- * everything pending for the lineage.
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.
85
86
  */
86
87
  readonly cutoffSeq?: number | undefined;
87
88
  }
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationQueue.d.ts","sourceRoot":"","sources":["../../src/NotificationQueue.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAAE,OAAO,EAAgB,MAAM,iBAAiB,CAAA;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAW,KAAK,EAAU,MAAM,EAA0B,MAAM,QAAQ,CAAA;AAEhG,OAAO,KAAK,iBAAiB,MAAM,mBAAmB,CAAA;AAEtD,OAAO,KAAK,iBAAiB,MAAM,wBAAwB,CAAA;;;;IAiCvD,oEAAoE;;IAEpE,sEAAsE;;;AAjC1E;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,iBAAkB,SAAQ,sBAmBtC;CAAG;AAEJ;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAA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journal = require("@smthrs/journal");
43
43
  var import_effect = require("effect");
44
44
  var FoldCache = __toESM(require("./internal/foldCache.js"), 1);
45
+ var Replay = __toESM(require("./internal/replay.js"), 1);
45
46
  var NotificationModel = __toESM(require("./Notification.js"), 1);
46
47
  var NotificationEvent = __toESM(require("./NotificationEvent.js"), 1);
47
48
  var NotificationState = __toESM(require("./NotificationState.js"), 1);
@@ -217,16 +218,7 @@ const layerWith = (options = {}) => import_effect.Layer.effect(
217
218
  decision: event.decision,
218
219
  seq: entry.seq
219
220
  });
220
- if (event.version !== void 0 && state.items.some((item) => item.notification.id === event.notification.id)) {
221
- state = Object.freeze({
222
- ...state,
223
- items: Object.freeze(state.items.map(
224
- (item) => item.notification.id === event.notification.id ? Object.freeze({ notification: event.notification, seq: item.seq }) : item
225
- ))
226
- });
227
- } else {
228
- state = NotificationState.applyAdmission(state, event.notification, entry.seq, event.decision);
229
- }
221
+ state = Replay.applyAdmitted(state, event, entry.seq);
230
222
  } else {
231
223
  promotions = import_effect.HashMap.set(
232
224
  promotions,
@@ -386,6 +378,13 @@ const layerWith = (options = {}) => import_effect.Layer.effect(
386
378
  drain: import_effect.Effect.fn("NotificationQueue.drain")(
387
379
  (input) => journal.transact(
388
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
+ }
389
388
  const runId = import_journal.JournalEvent.RunId.make(input.runId);
390
389
  const key = NotificationEvent.drainKey(input.targetLineageId, input.boundary);
391
390
  const loaded = yield* load(runId);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/NotificationQueue.ts"],
4
- "sourcesContent": ["/**\n * Journal-backed durable notification admission and turn-boundary drain.\n *\n * Governing contract: `packages/smithers/notifications/docs/api.md`, published as\n * `/api/notifications`.\n *\n * @since 0.1.0\n */\n\nimport { canonicalize } from \"@smthrs/canonical\"\nimport { digestSync } from \"@smthrs/crypto/Sha256\"\nimport { Journal, JournalEvent } from \"@smthrs/journal\"\nimport { Context, Effect, HashMap, Layer, Option, Schema, SchemaIssue, Semaphore } from \"effect\"\nimport * as FoldCache from \"./internal/foldCache.ts\"\nimport * as NotificationModel from \"./Notification.ts\"\nimport * as NotificationEvent from \"./NotificationEvent.ts\"\nimport * as NotificationState from \"./NotificationState.ts\"\n\n/**\n * The queue could not be reached, or it refused what a caller handed it.\n *\n * `code` is the stable half and the one to branch on. `notification_unavailable`\n * is the seam reporting that it serves nothing; `notification_id_reused` says a\n * stable id was admitted once already with different content, which is a\n * producer bug rather than a storage failure; `notification_invalid` says the\n * value is not a notification, and `path` names the field inside it that failed.\n * `notification_closed` means the receiver has finished and the caller must\n * start a new request; `notification_full` means nothing was retained and the\n * same notification may be retried after pending work drains. Neither the\n * message nor `path` ever carries the offending value.\n * `notification_refused` rejects reserved outside-change payloads before admission.\n *\n * @category errors\n * @since 0.1.0\n */\nexport class NotificationError extends Schema.TaggedError<NotificationError>()(\n \"/notifications/NotificationError\",\n {\n code: Schema.Literals([\n \"notification_unavailable\",\n \"notification_closed\",\n \"notification_full\",\n \"notification_id_reused\",\n \"notification_invalid\",\n \"notification_refused\"\n ]).pipe(\n Schema.withConstructorDefault(Effect.succeed(\"notification_unavailable\" as const))\n ),\n message: Schema.String,\n /** The notification the failure is about, when one was readable. */\n notificationId: Schema.optional(Schema.String),\n /** Dotted path of the offending field, for `notification_invalid`. */\n path: Schema.optional(Schema.String)\n }\n) {}\n\n/**\n * What admitting one notification decided.\n *\n * `seq` is the journal sequence the admission committed at, and it is absent\n * exactly when nothing was written, which today means a `rejected-full`\n * refusal. `duplicate` says the id was already admitted, in which case\n * `decision` and `seq` are read back from the committed record rather than\n * recomputed here.\n *\n * A caller MUST inspect `decision`: `rejected-full` means the queue was at\n * capacity and retained nothing, so the notification never reaches the model\n * unless the caller admits it again once a boundary has drained.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface AdmissionReceipt {\n readonly notificationId: string\n readonly decision: NotificationState.AdmissionDecision\n readonly seq: number | undefined\n readonly duplicate: boolean\n readonly consumed?: boolean\n readonly consumedNotification?: NotificationModel.Notification\n}\n\n/**\n * The boundary a drain is attempted at, and whether the run would go idle\n * if nothing were delivered.\n *\n * `(runId, targetLineageId, boundary)` is the unit of drain: two lineages\n * closing a turn under the same boundary name are two drains, and each is\n * recorded separately.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DrainInput {\n readonly runId: string\n readonly targetLineageId: string\n readonly boundary: string\n readonly wouldIdle: boolean\n /**\n * The journal sequence that opened this turn. A steer admitted after it is\n * held for the next boundary, which is what keeps a message that arrived\n * mid-turn out of the turn already in flight. Omitting it delivers\n * everything pending for the lineage.\n */\n readonly cutoffSeq?: number | undefined\n}\n\n/**\n * The notifications this boundary delivers, and whether the boundary had\n * already drained.\n *\n * The notifications are the ones the committed promotion record names, so two\n * processes draining one boundary report the same delivery rather than two\n * divergent guesses.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DrainReceipt {\n readonly notifications: ReadonlyArray<NotificationModel.Notification>\n readonly boundary: string\n readonly duplicate: boolean\n}\n\n/**\n * The durable pending queue: admit a notification exactly once, and drain\n * what a boundary is allowed to deliver.\n *\n * @category services\n * @since 0.1.0\n */\nexport interface Service {\n readonly admit: (\n runId: string,\n notification: NotificationModel.Notification,\n version?: number\n ) => Effect.Effect<AdmissionReceipt, Journal.JournalError | NotificationError>\n readonly drain: (\n input: DrainInput\n ) => Effect.Effect<DrainReceipt, Journal.JournalError | NotificationError>\n /**\n * What this run has been told that no boundary has delivered yet, in\n * admission order.\n *\n * The queue is the owner of that fact: pending is admitted minus promoted,\n * and both halves are its own journal records. A supervisor that counted\n * admissions alone would report a steer as waiting forever.\n */\n readonly pending: (\n runId: string\n ) => Effect.Effect<ReadonlyArray<NotificationModel.Notification>, Journal.JournalError | NotificationError>\n}\n\n/**\n * The {@link Service} tag.\n *\n * @category services\n * @since 0.1.0\n */\nexport class NotificationQueue extends Context.Service<NotificationQueue, Service>()(\n \"/notifications/NotificationQueue\"\n) {}\n\n/**\n * Builds a {@link Service} from an implementation of its methods.\n *\n * @param implementation the methods to serve\n * @category constructors\n * @since 0.1.0\n */\nexport const make = (implementation: Service): Service => NotificationQueue.of(implementation)\n\nconst unavailable = (operation: string): NotificationError =>\n new NotificationError({ code: \"notification_unavailable\", message: `${operation} is unavailable` })\n\n/**\n * A {@link Service} that fails every method as unavailable. Overrides\n * replace individual methods.\n *\n * @param overrides methods to serve instead of failing\n * @category constructors\n * @since 0.1.0\n */\nexport const makeNoop = (overrides: Partial<Service> = {}): Service =>\n make({\n admit: Effect.fn(\"NotificationQueue.admit\")(() => Effect.fail(unavailable(\"admit\"))),\n drain: Effect.fn(\"NotificationQueue.drain\")(() => Effect.fail(unavailable(\"drain\"))),\n pending: Effect.fn(\"NotificationQueue.pending\")(() => Effect.fail(unavailable(\"pending\"))),\n ...overrides\n })\n\n/**\n * Provides {@link makeNoop}.\n *\n * @param overrides methods to serve instead of failing\n * @category layers\n * @since 0.1.0\n */\nexport const layerNoop = (overrides: Partial<Service> = {}): Layer.Layer<NotificationQueue> =>\n Layer.succeed(NotificationQueue)(makeNoop(overrides))\n\n/**\n * The deepest a notification's JSON may nest.\n *\n * The bound exists because the value is walked and serialized on the way to\n * the journal, and an unbounded walk turns a hostile payload into an untyped\n * `RangeError` instead of a refusal a caller can read.\n */\nconst maximumPayloadDepth = 256\n\n/**\n * The largest a notification may be, in UTF-16 code units: every string and\n * object key counted at its length, and every other value as one.\n *\n * The bound exists because an admission copies, decodes, canonicalizes,\n * fingerprints, and journals the whole value, so a producer admitting a huge\n * array or string spends the notifying process's CPU and memory and bloats\n * every replay of the run. It is checked before any of that work starts.\n */\nconst maximumNotificationCodeUnits = 1_048_576\n\n/** Bounds an issue message so a refusal cannot journal or log an essay. */\nconst maximumIssueCodeUnits = 200\n\n/**\n * The bound a value breaks, if any, walked iteratively so the walk itself\n * cannot exhaust the stack. A cycle is caught by the depth bound: it has no\n * finite depth, so it trips the limit rather than looping forever. The size\n * count stops the walk as soon as it passes the bound, so an oversized value\n * costs the walk no more than the bound does.\n */\nconst exceededBound = (value: unknown): \"depth\" | \"size\" | undefined => {\n const pending: Array<{ readonly value: unknown; readonly depth: number }> = [{ value, depth: 0 }]\n let size = 0\n while (pending.length > 0) {\n const next = pending.pop()!\n size += typeof next.value === \"string\" ? next.value.length : 1\n if (size > maximumNotificationCodeUnits) return \"size\"\n if (typeof next.value !== \"object\" || next.value === null) continue\n if (next.depth >= maximumPayloadDepth) return \"depth\"\n if (Array.isArray(next.value)) {\n for (const child of next.value) pending.push({ value: child, depth: next.depth + 1 })\n continue\n }\n for (const [key, child] of Object.entries(next.value)) {\n size += key.length\n pending.push({ value: child, depth: next.depth + 1 })\n }\n }\n return undefined\n}\n\n/**\n * A structural copy of the caller's value, so nothing the queue journals or\n * retains can be edited afterwards through a reference the caller kept. Values\n * that are not arrays or objects pass through, which is what leaves a function\n * or a symbol in place for the schema to reject.\n */\nconst copied = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(copied)\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, copied(nested)]))\n }\n return value\n}\n\nconst formatIssue = SchemaIssue.makeFormatterStandardSchemaV1({ leafHook: (issue) => issue._tag })\n\nconst bounded = (text: string): string =>\n text.length <= maximumIssueCodeUnits ? text : `${text.slice(0, maximumIssueCodeUnits - 3)}...`\n\nconst identifiedBy = (value: unknown): string | undefined => {\n if (typeof value !== \"object\" || value === null) return undefined\n const id = (value as Readonly<Record<string, unknown>>)[\"id\"]\n return typeof id === \"string\" ? id : undefined\n}\n\nconst decodeNotification = Schema.decodeUnknownEffect(NotificationModel.Notification)\n\n/**\n * Decodes the caller's argument at the durability boundary and returns a value\n * the caller cannot reach.\n *\n * Nothing downstream re-checks the shape: a structurally invalid notification\n * that reached the journal would be acknowledged at a real sequence and then\n * skipped by every replay, which is acknowledged data loss. The depth and size\n * bounds run first so a hostile payload can neither exhaust the stack nor make\n * the copy, the decode, and the fingerprint walk it in full.\n */\nconst validated = (\n notification: NotificationModel.Notification\n): Effect.Effect<NotificationModel.Notification, NotificationError> =>\n Effect.gen(function*() {\n const notificationId = identifiedBy(notification)\n const exceeded = exceededBound(notification)\n if (exceeded !== undefined) {\n return yield* new NotificationError({\n code: \"notification_invalid\",\n message: exceeded === \"depth\"\n ? `A notification nests deeper than the ${maximumPayloadDepth} level bound`\n : `A notification is larger than the ${maximumNotificationCodeUnits} code unit bound`,\n ...(notificationId === undefined ? {} : { notificationId })\n })\n }\n return yield* decodeNotification(copied(notification)).pipe(\n Effect.mapError((error) => {\n // The formatter reports at least one issue for a failure and gives\n // every issue a concrete path. Standard Schema's result type widens\n // both, so a fallback for either would be code no input can reach.\n const issue = formatIssue(error.issue).issues[0] as {\n readonly message: string\n readonly path: ReadonlyArray<PropertyKey>\n }\n const path = issue.path.map(String).join(\".\")\n return new NotificationError({\n code: \"notification_invalid\",\n message: bounded(issue.message),\n ...(notificationId === undefined ? {} : { notificationId }),\n ...(path === \"\" ? {} : { path })\n })\n })\n )\n })\n\n// Persisted notification JSON predates RFC 8785's rejection of lone surrogates.\nconst canonical = (value: unknown): string => canonicalize(value, { loneSurrogates: \"escape\" })\n\n/** Fingerprint the validated input before the journal redacts its payload. */\nconst fingerprint = (notification: NotificationModel.Notification): Effect.Effect<string> =>\n Effect.sync(() => digestSync(canonical(notification)))\n\n/** Freeze the decoded JSON graph before any queue output can expose it. */\nconst freeze = (value: unknown): void => {\n if (typeof value !== \"object\" || value === null) return\n for (const nested of Object.values(value)) freeze(nested)\n Object.freeze(value)\n}\n\n/**\n * One committed admission, as the journal recorded it.\n *\n * This is an identity, not a payload: the fold keeps the fingerprint that\n * settles a duplicate and the sequence the record lives at, and reads the\n * notification itself back from the journal on the rare path that needs it.\n * Retaining every admitted payload for a run's lifetime is what made a\n * capacity-one queue grow without bound.\n */\ninterface Committed {\n readonly version: number | undefined\n readonly fingerprint: string | undefined\n readonly decision: NotificationState.AdmissionDecision\n readonly seq: number\n}\n\n/**\n * One run's folded notification history.\n *\n * `cursor` is the sequence of the last entry folded, absent when the run has\n * no entries at all. It is what the next read pages from, so a fold costs the\n * entries added since the previous call rather than the run's whole journal.\n */\ninterface Loaded {\n readonly state: NotificationState.State\n readonly admissions: HashMap.HashMap<string, Committed>\n /** Drain identity to the sequence its record committed at. */\n readonly promotions: HashMap.HashMap<string, number>\n readonly cursor: number | undefined\n}\n\n/**\n * How many runs one layer keeps folded at a time. Evicting is safe: the next\n * call for an evicted run folds it again from the beginning, and the retention\n * policy is scan-resistant, so a supervisor sweeping more runs than this reads\n * journal tails for all but a fixed handful of them.\n */\nconst maximumCachedRuns = 64\n\n/**\n * Journal-backed production layer, with the pending capacity a composition\n * chooses.\n *\n * Admission and drain evidence is written through `emitDurableUnfenced`, so\n * both return only after the corresponding entry is durably committed and a\n * dropped lifecycle event is unrepresentable. The channel is the unfenced one\n * on purpose: the notifying process owns no run, so there is no ownership\n * fence to hand over, and both records are first-writer-wins on their own\n * identity instead.\n *\n * The capacity guard is a conditional write at the storage layer, not a check\n * against a fold one process happened to load: the fold, the guard, and the\n * admission record are decided and written inside ONE `journal.transact`\n * write transaction, which the durable writer serializes against every other\n * writer of the database and replays when a concurrent writer commits between\n * the guard's reads and the insert. Two processes admitting to one full queue\n * therefore produce one admission and one `rejected-full`, never two\n * admissions.\n *\n * @param options the pending capacity, defaulting to `NotificationState.defaultCapacity`\n * @category layers\n * @since 1.0.0\n */\nexport const layerWith = (\n options: { readonly capacity?: number | undefined } = {}\n): Layer.Layer<NotificationQueue, never, Journal.Journal> =>\n Layer.effect(\n NotificationQueue,\n Effect.gen(function*() {\n const journal = yield* Journal.Journal\n // Orders this layer's own fibers so one process never runs two of its\n // admissions or drains against the fold cache at once. It is\n // process-local by construction and is NOT what enforces capacity or\n // drain identity across processes: those are the conditional writes\n // inside `journal.transact`, decided and committed in one serialized\n // write transaction. Always enter the journal transaction before taking\n // this permit, matching callers already inside an enclosing transaction.\n const operations = yield* Semaphore.make(1)\n const capacity = options.capacity ?? NotificationState.defaultCapacity\n // Only committed folds may be shared. A transaction reads its own\n // inserts, but its read-back is still provisional until the OUTERMOST\n // commit; neither a retry nor a later caller may dedupe against it.\n const folded = FoldCache.make<Loaded>(maximumCachedRuns)\n\n /**\n * One entry by the sequence it committed at.\n *\n * The fold keeps identities and sequences rather than payloads, so the\n * paths that must report an admitted notification read it back here.\n */\n const entryAt = (\n runId: JournalEvent.RunId,\n seq: number\n ): Effect.Effect<Option.Option<JournalEvent.Entry>, Journal.JournalError> =>\n Effect.map(\n journal.entries({\n runId,\n ...(seq === 0 ? {} : { after: JournalEvent.Seq.make(seq - 1) }),\n limit: 1\n }),\n (page) => {\n const found = page.entries[0]\n return found !== undefined && found.seq === seq ? Option.some(found) : Option.none()\n }\n )\n\n const admittedAt = (\n runId: JournalEvent.RunId,\n seq: number\n ): Effect.Effect<Option.Option<NotificationEvent.Admitted>, Journal.JournalError> =>\n Effect.map(entryAt(runId, seq), (entry) => {\n if (Option.isNone(entry)) return Option.none()\n const decoded = NotificationEvent.fromEntry(entry.value)\n if (Option.isNone(decoded) || !NotificationEvent.isAdmitted(decoded.value)) return Option.none()\n freeze(decoded.value.notification)\n return Option.some(decoded.value)\n })\n\n const promotedAt = (\n runId: JournalEvent.RunId,\n seq: number\n ): Effect.Effect<Option.Option<NotificationEvent.Promoted>, Journal.JournalError> =>\n Effect.map(entryAt(runId, seq), (entry) => {\n if (Option.isNone(entry)) return Option.none()\n const decoded = NotificationEvent.fromEntry(entry.value)\n if (Option.isNone(decoded) || !NotificationEvent.isPromoted(decoded.value)) return Option.none()\n return Option.some(decoded.value)\n })\n\n const load = (runId: JournalEvent.RunId): Effect.Effect<Loaded, Journal.JournalError> =>\n Effect.gen(function*() {\n const base: Loaded = folded.get(runId) ?? {\n state: NotificationState.empty(capacity),\n admissions: HashMap.empty(),\n promotions: HashMap.empty(),\n cursor: undefined\n }\n const fresh: Array<JournalEvent.Entry> = []\n let after = base.cursor === undefined ? undefined : JournalEvent.Seq.make(base.cursor)\n while (true) {\n // `after` is an exact-optional property upstream, so an explicit\n // `undefined` is not the same as an absent key.\n const page = yield* journal.entries({\n runId,\n eventTypes: [NotificationEvent.AdmittedEventType, NotificationEvent.PromotedEventType],\n ...(after === undefined ? {} : { after }),\n limit: 512\n })\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 let state = base.state\n let cursor = base.cursor\n // Persistent maps: one event adds a node and leaves the fold the\n // previous load published untouched, where copying both maps would\n // cost the run's whole history on every event and make a long run's\n // folding quadratic in its own admissions.\n let admissions = base.admissions\n let promotions = base.promotions\n for (const entry of fresh) {\n cursor = entry.seq\n const decoded = NotificationEvent.fromEntry(entry)\n if (Option.isNone(decoded)) continue\n const event = decoded.value\n if (NotificationEvent.isAdmitted(event)) {\n freeze(event.notification)\n admissions = HashMap.set(admissions, event.notification.id, {\n version: event.version,\n fingerprint: event.fingerprint,\n decision: event.decision,\n seq: entry.seq\n })\n if (\n event.version !== undefined &&\n state.items.some((item) => item.notification.id === event.notification.id)\n ) {\n state = Object.freeze({\n ...state,\n items: Object.freeze(state.items.map((item) =>\n item.notification.id === event.notification.id\n ? Object.freeze({ notification: event.notification, seq: item.seq })\n : item\n ))\n })\n } else {\n state = NotificationState.applyAdmission(state, event.notification, entry.seq, event.decision)\n }\n } else {\n promotions = HashMap.set(\n promotions,\n NotificationEvent.drainKey(event.targetLineageId, event.boundary),\n entry.seq\n )\n state = NotificationState.applyPromoted(state, event.ids)\n }\n }\n\n const loaded: Loaded = { state, admissions, promotions, cursor }\n yield* journal.whenCommitted(Effect.sync(() => folded.put(runId, loaded)))\n return loaded\n })\n\n /**\n * One conditional admission: the duplicate check, the capacity guard,\n * and the admission record, decided and written inside ONE journal\n * write transaction.\n *\n * This is the queue's conditional insert, the same read-guarded write\n * the journal itself uses for its dedupe and fence conditions: the\n * guard's reads and the insert share one serialized write transaction,\n * and the durable writer replays the whole body when a concurrent\n * writer commits between them. A decision a stale fold produced can\n * therefore never commit \u2014 the replay re-folds against the committed\n * state and a queue that filled meanwhile refuses \u2014 however many\n * processes share the database. The process-local `operations`\n * semaphore orders this layer's own fibers only; it is not what\n * enforces capacity across processes.\n */\n const admitInTransaction = (\n runId: JournalEvent.RunId,\n admitted: NotificationModel.Notification,\n admittedFingerprint: string,\n version?: number\n ): Effect.Effect<AdmissionReceipt, Journal.JournalError | NotificationError> =>\n Effect.gen(function*() {\n const loaded = yield* load(runId)\n const prior = Option.getOrUndefined(HashMap.get(loaded.admissions, admitted.id))\n const replacing = prior !== undefined && version !== undefined && version > (prior.version ?? 0)\n if (replacing) {\n const original = yield* admittedAt(runId, prior.seq)\n if (Option.isNone(original)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n notificationId: admitted.id,\n message: \"Original steering input is unreadable\"\n })\n }\n const identity = (input: NotificationModel.Notification) => ({ ...input, payload: null })\n if (canonical(identity(original.value.notification)) !== canonical(identity(admitted))) {\n return yield* new NotificationError({\n code: \"notification_id_reused\",\n notificationId: admitted.id,\n message: \"An edit cannot change the notification owner or delivery binding\"\n })\n }\n }\n if (replacing && !loaded.state.items.some((item) => item.notification.id === admitted.id)) {\n const original = yield* admittedAt(runId, prior.seq)\n if (Option.isNone(original)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n message: \"Consumed input is unreadable\"\n })\n }\n return {\n notificationId: admitted.id,\n decision: prior.decision,\n seq: prior.seq,\n duplicate: true,\n consumed: true,\n consumedNotification: original.value.notification\n }\n }\n if (prior !== undefined && version !== undefined && version < (prior.version ?? 0)) {\n return { notificationId: admitted.id, decision: prior.decision, seq: prior.seq, duplicate: true }\n }\n if (prior !== undefined && !replacing) {\n // Legacy rows have no fingerprint; only their persisted content is\n // available for comparison, and the fold keeps identities rather\n // than payloads, so the original is read back at its sequence.\n // New rows settle on the fingerprint alone and read nothing.\n let same = prior.fingerprint === admittedFingerprint\n if (prior.fingerprint === undefined) {\n const original = yield* admittedAt(runId, prior.seq)\n if (Option.isNone(original)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n notificationId: admitted.id,\n message: `The admission for notification ${admitted.id} is no longer readable`\n })\n }\n same = canonical(original.value.notification) === canonical(admitted)\n }\n if (!same) {\n return yield* new NotificationError({\n code: \"notification_id_reused\",\n notificationId: admitted.id,\n message: `Notification id ${admitted.id} was already admitted with different content`\n })\n }\n return {\n notificationId: admitted.id,\n decision: prior.decision,\n seq: prior.seq,\n duplicate: true\n }\n }\n\n const admission = replacing ? { decision: \"coalesced\" as const } : NotificationState.admit(\n loaded.state,\n admitted,\n loaded.cursor === undefined ? 0 : loaded.cursor + 1\n )\n if (admission.decision === \"rejected-full\") {\n // Nothing is journaled. A rejection recorded as an admission\n // would match on every later attempt and burn the id forever,\n // so the queue refuses in the receipt alone and the caller may\n // admit again once a boundary has drained.\n return {\n notificationId: admitted.id,\n decision: admission.decision,\n seq: undefined,\n duplicate: false\n }\n }\n\n const receipt = yield* journal.emitDurableUnfenced(\n new JournalEvent.Input({\n runId,\n sourceId: NotificationEvent.admissionSourceId(admitted.id),\n sourceSeq: JournalEvent.SourceSeq.make(version ?? 0),\n // The sequence is derived from the notification's own id, so\n // a collision IS this admission observed twice. Comparing\n // bytes instead would fail the second writer over `decision`,\n // a field neither caller supplied and each derives from the\n // fill level it happened to load at.\n dedupe: \"identity\",\n eventType: NotificationEvent.AdmittedEventType,\n payload: {\n notification: admitted,\n decision: admission.decision,\n fingerprint: admittedFingerprint,\n ...(version === undefined ? {} : { version })\n }\n })\n )\n const committed = Option.getOrUndefined(HashMap.get((yield* load(runId)).admissions, admitted.id))\n if (committed === undefined) {\n // Only reachable when the emit deduped against an entry this\n // queue did not write, so nothing was committed and there is\n // no admission to report.\n return yield* new NotificationError({\n code: \"notification_id_reused\",\n notificationId: admitted.id,\n message: `The journal identity for notification ${admitted.id} holds an event this queue did not write`\n })\n }\n return {\n notificationId: admitted.id,\n decision: committed.decision,\n seq: committed.seq,\n duplicate: receipt._tag === \"Duplicate\"\n }\n })\n\n return make({\n admit: Effect.fn(\"NotificationQueue.admit\")((rawRunId, notification, version) =>\n Effect.gen(function*() {\n if (version !== undefined && (!Number.isSafeInteger(version) || version < 1)) {\n return yield* new NotificationError({\n code: \"notification_invalid\",\n message: \"version must be a positive safe integer\"\n })\n }\n const admitted = yield* validated(notification)\n // T-COL-12 stays dark: nothing yet authenticates a watcher burst, pins\n // its coding run or enforces fresh machine reads. Refusing here, before\n // the journal, keeps co-admitted steers deliverable on every replay.\n const payload = admitted.payload\n if (\n typeof payload === \"object\" && payload !== null && !Array.isArray(payload) &&\n (payload as Readonly<Record<string, unknown>>)[\"kind\"] === \"outside_change\"\n ) {\n return yield* new NotificationError({\n code: \"notification_refused\",\n notificationId: admitted.id,\n message: \"Outside-change delivery requires authenticated watcher facts and stale-write enforcement\"\n })\n }\n const admittedFingerprint = yield* fingerprint(admitted)\n return yield* journal.transact(\n operations.withPermits(1)(\n admitInTransaction(JournalEvent.RunId.make(rawRunId), admitted, admittedFingerprint, version)\n )\n )\n })\n ),\n drain: Effect.fn(\"NotificationQueue.drain\")((input) =>\n journal.transact(\n operations.withPermits(1)(Effect.gen(function*() {\n const runId = JournalEvent.RunId.make(input.runId)\n const key = NotificationEvent.drainKey(input.targetLineageId, input.boundary)\n const loaded = yield* load(runId)\n // A replay reports what the committed record delivered, read\n // back from the journal: the fold holds the identities, not the\n // notifications, so a run's drained payloads are not retained.\n const delivered = (\n record: NotificationEvent.Promoted,\n admissions: HashMap.HashMap<string, Committed>\n ): Effect.Effect<\n ReadonlyArray<NotificationModel.Notification>,\n Journal.JournalError | NotificationError\n > =>\n Effect.forEach(record.ids, (id) =>\n Effect.gen(function*() {\n const committed = HashMap.get(admissions, id)\n const event = Option.isNone(committed)\n ? Option.none<NotificationEvent.Admitted>()\n : yield* admittedAt(runId, committed.value.seq)\n // A committed drain promises this exact delivery. Missing or\n // corrupt payloads cannot become a successful partial replay.\n if (Option.isNone(event)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n notificationId: id,\n message: `The delivered notification ${id} is no longer readable`\n })\n }\n return event.value.notification\n }))\n\n const replayed = (seq: number, admissions: HashMap.HashMap<string, Committed>) =>\n Effect.gen(function*() {\n const record = yield* promotedAt(runId, seq)\n if (Option.isNone(record)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n message: `The drain record for boundary ${input.boundary} is no longer readable`\n })\n }\n return {\n notifications: yield* delivered(record.value, admissions),\n boundary: input.boundary,\n duplicate: true\n }\n })\n\n const prior = HashMap.get(loaded.promotions, key)\n if (Option.isSome(prior)) return yield* replayed(prior.value, loaded.admissions)\n\n const cutoff = input.cutoffSeq ?? loaded.cursor ?? 0\n // The existing coding park ladder waits for a person's answer.\n // System facts must remain pending there: promoting them would\n // make the harness treat an outside edit as an answered question.\n // Filtering this projection changes only promoted IDs; the journal\n // fold retains every held admission and its original sequence.\n const promotionState = /^\\d+:[a-f0-9]{64}:park:\\d+$/.test(input.boundary)\n ? {\n ...loaded.state,\n items: loaded.state.items.filter((item) => {\n const payload = item.notification.payload\n return !(typeof payload === \"object\" && payload !== null && !Array.isArray(payload) &&\n (payload as Readonly<Record<string, unknown>>).kind === \"outside_change\")\n })\n }\n : loaded.state\n const steers = NotificationState.promoteSteers(promotionState, cutoff, input.targetLineageId)\n const queued = input.wouldIdle && steers.promoted.length === 0\n ? NotificationState.promoteQueued(steers.state, input.targetLineageId)\n : { state: steers.state, promoted: [] }\n const promoted = [...steers.promoted, ...queued.promoted].map((item) => item.notification)\n const receipt = yield* journal.emitDurableUnfenced(\n new JournalEvent.Input({\n runId,\n sourceId: NotificationEvent.drainSourceId(input.targetLineageId, input.boundary),\n sourceSeq: JournalEvent.SourceSeq.make(0),\n // The identity is the drain: this lineage closing this\n // boundary. Two processes that both reach it have observed one\n // event, and the first record committed is the delivery.\n dedupe: \"identity\",\n eventType: NotificationEvent.PromotedEventType,\n payload: {\n boundary: input.boundary,\n targetLineageId: input.targetLineageId,\n ids: promoted.map((notification) => notification.id)\n }\n })\n )\n const settled = yield* load(runId)\n const committed = HashMap.get(settled.promotions, key)\n if (Option.isNone(committed)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n message: `The journal identity for boundary ${input.boundary} holds an event this queue did not write`\n })\n }\n // An accepted emit wrote THIS drain, so the promoted set is the\n // one already in hand and no read-back is owed.\n if (receipt._tag === \"Accepted\") {\n return { notifications: promoted, boundary: input.boundary, duplicate: false }\n }\n return yield* replayed(committed.value, settled.admissions)\n }))\n )\n ),\n pending: Effect.fn(\"NotificationQueue.pending\")((rawRunId) =>\n Effect.map(\n load(JournalEvent.RunId.make(rawRunId)),\n // The fold `load` already performs: admissions add, promotions\n // remove. Read outside the operations semaphore, because a count\n // taken while a boundary drains is a count taken at some instant\n // either side of it, and blocking a supervisor behind a turn\n // boundary would be the worse answer.\n (loaded) => loaded.state.items.map((item) => item.notification)\n )\n )\n })\n })\n )\n\n/**\n * Journal-backed production layer at the default capacity.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer: Layer.Layer<NotificationQueue, never, Journal.Journal> = layerWith()\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,uBAA6B;AAC7B,oBAA2B;AAC3B,qBAAsC;AACtC,oBAAwF;AACxF,gBAA2B;AAC3B,wBAAmC;AACnC,wBAAmC;AACnC,wBAAmC;AAmB5B,MAAM,0BAA0B,qBAAO,YAA+B;AAAA,EAC3E;AAAA,EACA;AAAA,IACE,MAAM,qBAAO,SAAS;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA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,UAAU;AAAA,UAC5D,CAAC,CAAC;AAAA,QACJ;AAAA,MACF;AAAA,MACA,SAAS,qBAAO,GAAG,2BAA2B;AAAA,QAAE,CAAC,aAC/C,qBAAO;AAAA,UACL,KAAK,4BAAa,MAAM,KAAK,QAAQ,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAMtC,CAAC,WAAW,OAAO,MAAM,MAAM,IAAI,CAAC,SAAS,KAAK,YAAY;AAAA,QAChE;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH;AAQK,MAAM,QAAgE,UAAU;",
4
+ "sourcesContent": ["/**\n * Journal-backed durable notification admission and turn-boundary drain.\n *\n * Governing contract: `packages/smithers/notifications/docs/api.md`, published as\n * `/api/notifications`.\n *\n * @since 0.1.0\n */\n\nimport { canonicalize } from \"@smthrs/canonical\"\nimport { digestSync } from \"@smthrs/crypto/Sha256\"\nimport { Journal, JournalEvent } from \"@smthrs/journal\"\nimport { Context, Effect, HashMap, Layer, Option, Schema, SchemaIssue, Semaphore } from \"effect\"\nimport * as FoldCache from \"./internal/foldCache.ts\"\nimport * as Replay from \"./internal/replay.ts\"\nimport * as NotificationModel from \"./Notification.ts\"\nimport * as NotificationEvent from \"./NotificationEvent.ts\"\nimport * as NotificationState from \"./NotificationState.ts\"\n\n/**\n * The queue could not be reached, or it refused what a caller handed it.\n *\n * `code` is the stable half and the one to branch on. `notification_unavailable`\n * is the seam reporting that it serves nothing; `notification_id_reused` says a\n * stable id was admitted once already with different content, which is a\n * producer bug rather than a storage failure; `notification_invalid` says the\n * value is not a notification, and `path` names the field inside it that failed.\n * `notification_closed` means the receiver has finished and the caller must\n * start a new request; `notification_full` means nothing was retained and the\n * same notification may be retried after pending work drains. Neither the\n * message nor `path` ever carries the offending value.\n * `notification_refused` rejects reserved outside-change payloads before admission.\n *\n * @category errors\n * @since 0.1.0\n */\nexport class NotificationError extends Schema.TaggedError<NotificationError>()(\n \"/notifications/NotificationError\",\n {\n code: Schema.Literals([\n \"notification_unavailable\",\n \"notification_closed\",\n \"notification_full\",\n \"notification_id_reused\",\n \"notification_invalid\",\n \"notification_refused\"\n ]).pipe(\n Schema.withConstructorDefault(Effect.succeed(\"notification_unavailable\" as const))\n ),\n message: Schema.String,\n /** The notification the failure is about, when one was readable. */\n notificationId: Schema.optional(Schema.String),\n /** Dotted path of the offending field, for `notification_invalid`. */\n path: Schema.optional(Schema.String)\n }\n) {}\n\n/**\n * What admitting one notification decided.\n *\n * `seq` is the journal sequence the admission committed at, and it is absent\n * exactly when nothing was written, which today means a `rejected-full`\n * refusal. `duplicate` says the id was already admitted, in which case\n * `decision` and `seq` are read back from the committed record rather than\n * recomputed here.\n *\n * A caller MUST inspect `decision`: `rejected-full` means the queue was at\n * capacity and retained nothing, so the notification never reaches the model\n * unless the caller admits it again once a boundary has drained.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface AdmissionReceipt {\n readonly notificationId: string\n readonly decision: NotificationState.AdmissionDecision\n readonly seq: number | undefined\n readonly duplicate: boolean\n readonly consumed?: boolean\n readonly consumedNotification?: NotificationModel.Notification\n}\n\n/**\n * The boundary a drain is attempted at, and whether the run would go idle\n * if nothing were delivered.\n *\n * `(runId, targetLineageId, boundary)` is the unit of drain: two lineages\n * closing a turn under the same boundary name are two drains, and each is\n * recorded separately.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DrainInput {\n readonly runId: string\n readonly targetLineageId: string\n readonly boundary: string\n readonly wouldIdle: boolean\n /**\n * The journal sequence that opened this turn. A steer admitted after it is\n * held for the next boundary, which is what keeps a message that arrived\n * mid-turn out of the turn already in flight. Omitting it delivers\n * everything pending for the lineage. A value that is not a non-negative\n * integer fails the drain with `notification_invalid` and records nothing.\n */\n readonly cutoffSeq?: number | undefined\n}\n\n/**\n * The notifications this boundary delivers, and whether the boundary had\n * already drained.\n *\n * The notifications are the ones the committed promotion record names, so two\n * processes draining one boundary report the same delivery rather than two\n * divergent guesses.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DrainReceipt {\n readonly notifications: ReadonlyArray<NotificationModel.Notification>\n readonly boundary: string\n readonly duplicate: boolean\n}\n\n/**\n * The durable pending queue: admit a notification exactly once, and drain\n * what a boundary is allowed to deliver.\n *\n * @category services\n * @since 0.1.0\n */\nexport interface Service {\n readonly admit: (\n runId: string,\n notification: NotificationModel.Notification,\n version?: number\n ) => Effect.Effect<AdmissionReceipt, Journal.JournalError | NotificationError>\n readonly drain: (\n input: DrainInput\n ) => Effect.Effect<DrainReceipt, Journal.JournalError | NotificationError>\n /**\n * What this run has been told that no boundary has delivered yet, in\n * admission order.\n *\n * The queue is the owner of that fact: pending is admitted minus promoted,\n * and both halves are its own journal records. A supervisor that counted\n * admissions alone would report a steer as waiting forever.\n */\n readonly pending: (\n runId: string\n ) => Effect.Effect<ReadonlyArray<NotificationModel.Notification>, Journal.JournalError | NotificationError>\n}\n\n/**\n * The {@link Service} tag.\n *\n * @category services\n * @since 0.1.0\n */\nexport class NotificationQueue extends Context.Service<NotificationQueue, Service>()(\n \"/notifications/NotificationQueue\"\n) {}\n\n/**\n * Builds a {@link Service} from an implementation of its methods.\n *\n * @param implementation the methods to serve\n * @category constructors\n * @since 0.1.0\n */\nexport const make = (implementation: Service): Service => NotificationQueue.of(implementation)\n\nconst unavailable = (operation: string): NotificationError =>\n new NotificationError({ code: \"notification_unavailable\", message: `${operation} is unavailable` })\n\n/**\n * A {@link Service} that fails every method as unavailable. Overrides\n * replace individual methods.\n *\n * @param overrides methods to serve instead of failing\n * @category constructors\n * @since 0.1.0\n */\nexport const makeNoop = (overrides: Partial<Service> = {}): Service =>\n make({\n admit: Effect.fn(\"NotificationQueue.admit\")(() => Effect.fail(unavailable(\"admit\"))),\n drain: Effect.fn(\"NotificationQueue.drain\")(() => Effect.fail(unavailable(\"drain\"))),\n pending: Effect.fn(\"NotificationQueue.pending\")(() => Effect.fail(unavailable(\"pending\"))),\n ...overrides\n })\n\n/**\n * Provides {@link makeNoop}.\n *\n * @param overrides methods to serve instead of failing\n * @category layers\n * @since 0.1.0\n */\nexport const layerNoop = (overrides: Partial<Service> = {}): Layer.Layer<NotificationQueue> =>\n Layer.succeed(NotificationQueue)(makeNoop(overrides))\n\n/**\n * The deepest a notification's JSON may nest.\n *\n * The bound exists because the value is walked and serialized on the way to\n * the journal, and an unbounded walk turns a hostile payload into an untyped\n * `RangeError` instead of a refusal a caller can read.\n */\nconst maximumPayloadDepth = 256\n\n/**\n * The largest a notification may be, in UTF-16 code units: every string and\n * object key counted at its length, and every other value as one.\n *\n * The bound exists because an admission copies, decodes, canonicalizes,\n * fingerprints, and journals the whole value, so a producer admitting a huge\n * array or string spends the notifying process's CPU and memory and bloats\n * every replay of the run. It is checked before any of that work starts.\n */\nconst maximumNotificationCodeUnits = 1_048_576\n\n/** Bounds an issue message so a refusal cannot journal or log an essay. */\nconst maximumIssueCodeUnits = 200\n\n/**\n * The bound a value breaks, if any, walked iteratively so the walk itself\n * cannot exhaust the stack. A cycle is caught by the depth bound: it has no\n * finite depth, so it trips the limit rather than looping forever. The size\n * count stops the walk as soon as it passes the bound, so an oversized value\n * costs the walk no more than the bound does.\n */\nconst exceededBound = (value: unknown): \"depth\" | \"size\" | undefined => {\n const pending: Array<{ readonly value: unknown; readonly depth: number }> = [{ value, depth: 0 }]\n let size = 0\n while (pending.length > 0) {\n const next = pending.pop()!\n size += typeof next.value === \"string\" ? next.value.length : 1\n if (size > maximumNotificationCodeUnits) return \"size\"\n if (typeof next.value !== \"object\" || next.value === null) continue\n if (next.depth >= maximumPayloadDepth) return \"depth\"\n if (Array.isArray(next.value)) {\n for (const child of next.value) pending.push({ value: child, depth: next.depth + 1 })\n continue\n }\n for (const [key, child] of Object.entries(next.value)) {\n size += key.length\n pending.push({ value: child, depth: next.depth + 1 })\n }\n }\n return undefined\n}\n\n/**\n * A structural copy of the caller's value, so nothing the queue journals or\n * retains can be edited afterwards through a reference the caller kept. Values\n * that are not arrays or objects pass through, which is what leaves a function\n * or a symbol in place for the schema to reject.\n */\nconst copied = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(copied)\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, copied(nested)]))\n }\n return value\n}\n\nconst formatIssue = SchemaIssue.makeFormatterStandardSchemaV1({ leafHook: (issue) => issue._tag })\n\nconst bounded = (text: string): string =>\n text.length <= maximumIssueCodeUnits ? text : `${text.slice(0, maximumIssueCodeUnits - 3)}...`\n\nconst identifiedBy = (value: unknown): string | undefined => {\n if (typeof value !== \"object\" || value === null) return undefined\n const id = (value as Readonly<Record<string, unknown>>)[\"id\"]\n return typeof id === \"string\" ? id : undefined\n}\n\nconst decodeNotification = Schema.decodeUnknownEffect(NotificationModel.Notification)\n\n/**\n * Decodes the caller's argument at the durability boundary and returns a value\n * the caller cannot reach.\n *\n * Nothing downstream re-checks the shape: a structurally invalid notification\n * that reached the journal would be acknowledged at a real sequence and then\n * skipped by every replay, which is acknowledged data loss. The depth and size\n * bounds run first so a hostile payload can neither exhaust the stack nor make\n * the copy, the decode, and the fingerprint walk it in full.\n */\nconst validated = (\n notification: NotificationModel.Notification\n): Effect.Effect<NotificationModel.Notification, NotificationError> =>\n Effect.gen(function*() {\n const notificationId = identifiedBy(notification)\n const exceeded = exceededBound(notification)\n if (exceeded !== undefined) {\n return yield* new NotificationError({\n code: \"notification_invalid\",\n message: exceeded === \"depth\"\n ? `A notification nests deeper than the ${maximumPayloadDepth} level bound`\n : `A notification is larger than the ${maximumNotificationCodeUnits} code unit bound`,\n ...(notificationId === undefined ? {} : { notificationId })\n })\n }\n return yield* decodeNotification(copied(notification)).pipe(\n Effect.mapError((error) => {\n // The formatter reports at least one issue for a failure and gives\n // every issue a concrete path. Standard Schema's result type widens\n // both, so a fallback for either would be code no input can reach.\n const issue = formatIssue(error.issue).issues[0] as {\n readonly message: string\n readonly path: ReadonlyArray<PropertyKey>\n }\n const path = issue.path.map(String).join(\".\")\n return new NotificationError({\n code: \"notification_invalid\",\n message: bounded(issue.message),\n ...(notificationId === undefined ? {} : { notificationId }),\n ...(path === \"\" ? {} : { path })\n })\n })\n )\n })\n\n// Persisted notification JSON predates RFC 8785's rejection of lone surrogates.\nconst canonical = (value: unknown): string => canonicalize(value, { loneSurrogates: \"escape\" })\n\n/** Fingerprint the validated input before the journal redacts its payload. */\nconst fingerprint = (notification: NotificationModel.Notification): Effect.Effect<string> =>\n Effect.sync(() => digestSync(canonical(notification)))\n\n/** Freeze the decoded JSON graph before any queue output can expose it. */\nconst freeze = (value: unknown): void => {\n if (typeof value !== \"object\" || value === null) return\n for (const nested of Object.values(value)) freeze(nested)\n Object.freeze(value)\n}\n\n/**\n * One committed admission, as the journal recorded it.\n *\n * This is an identity, not a payload: the fold keeps the fingerprint that\n * settles a duplicate and the sequence the record lives at, and reads the\n * notification itself back from the journal on the rare path that needs it.\n * Retaining every admitted payload for a run's lifetime is what made a\n * capacity-one queue grow without bound.\n */\ninterface Committed {\n readonly version: number | undefined\n readonly fingerprint: string | undefined\n readonly decision: NotificationState.AdmissionDecision\n readonly seq: number\n}\n\n/**\n * One run's folded notification history.\n *\n * `cursor` is the sequence of the last entry folded, absent when the run has\n * no entries at all. It is what the next read pages from, so a fold costs the\n * entries added since the previous call rather than the run's whole journal.\n */\ninterface Loaded {\n readonly state: NotificationState.State\n readonly admissions: HashMap.HashMap<string, Committed>\n /** Drain identity to the sequence its record committed at. */\n readonly promotions: HashMap.HashMap<string, number>\n readonly cursor: number | undefined\n}\n\n/**\n * How many runs one layer keeps folded at a time. Evicting is safe: the next\n * call for an evicted run folds it again from the beginning, and the retention\n * policy is scan-resistant, so a supervisor sweeping more runs than this reads\n * journal tails for all but a fixed handful of them.\n */\nconst maximumCachedRuns = 64\n\n/**\n * Journal-backed production layer, with the pending capacity a composition\n * chooses.\n *\n * Admission and drain evidence is written through `emitDurableUnfenced`, so\n * both return only after the corresponding entry is durably committed and a\n * dropped lifecycle event is unrepresentable. The channel is the unfenced one\n * on purpose: the notifying process owns no run, so there is no ownership\n * fence to hand over, and both records are first-writer-wins on their own\n * identity instead.\n *\n * The capacity guard is a conditional write at the storage layer, not a check\n * against a fold one process happened to load: the fold, the guard, and the\n * admission record are decided and written inside ONE `journal.transact`\n * write transaction, which the durable writer serializes against every other\n * writer of the database and replays when a concurrent writer commits between\n * the guard's reads and the insert. Two processes admitting to one full queue\n * therefore produce one admission and one `rejected-full`, never two\n * admissions.\n *\n * @param options the pending capacity, defaulting to `NotificationState.defaultCapacity`\n * @category layers\n * @since 1.0.0\n */\nexport const layerWith = (\n options: { readonly capacity?: number | undefined } = {}\n): Layer.Layer<NotificationQueue, never, Journal.Journal> =>\n Layer.effect(\n NotificationQueue,\n Effect.gen(function*() {\n const journal = yield* Journal.Journal\n // Orders this layer's own fibers so one process never runs two of its\n // admissions or drains against the fold cache at once. It is\n // process-local by construction and is NOT what enforces capacity or\n // drain identity across processes: those are the conditional writes\n // inside `journal.transact`, decided and committed in one serialized\n // write transaction. Always enter the journal transaction before taking\n // this permit, matching callers already inside an enclosing transaction.\n const operations = yield* Semaphore.make(1)\n const capacity = options.capacity ?? NotificationState.defaultCapacity\n // Only committed folds may be shared. A transaction reads its own\n // inserts, but its read-back is still provisional until the OUTERMOST\n // commit; neither a retry nor a later caller may dedupe against it.\n const folded = FoldCache.make<Loaded>(maximumCachedRuns)\n\n /**\n * One entry by the sequence it committed at.\n *\n * The fold keeps identities and sequences rather than payloads, so the\n * paths that must report an admitted notification read it back here.\n */\n const entryAt = (\n runId: JournalEvent.RunId,\n seq: number\n ): Effect.Effect<Option.Option<JournalEvent.Entry>, Journal.JournalError> =>\n Effect.map(\n journal.entries({\n runId,\n ...(seq === 0 ? {} : { after: JournalEvent.Seq.make(seq - 1) }),\n limit: 1\n }),\n (page) => {\n const found = page.entries[0]\n return found !== undefined && found.seq === seq ? Option.some(found) : Option.none()\n }\n )\n\n const admittedAt = (\n runId: JournalEvent.RunId,\n seq: number\n ): Effect.Effect<Option.Option<NotificationEvent.Admitted>, Journal.JournalError> =>\n Effect.map(entryAt(runId, seq), (entry) => {\n if (Option.isNone(entry)) return Option.none()\n const decoded = NotificationEvent.fromEntry(entry.value)\n if (Option.isNone(decoded) || !NotificationEvent.isAdmitted(decoded.value)) return Option.none()\n freeze(decoded.value.notification)\n return Option.some(decoded.value)\n })\n\n const promotedAt = (\n runId: JournalEvent.RunId,\n seq: number\n ): Effect.Effect<Option.Option<NotificationEvent.Promoted>, Journal.JournalError> =>\n Effect.map(entryAt(runId, seq), (entry) => {\n if (Option.isNone(entry)) return Option.none()\n const decoded = NotificationEvent.fromEntry(entry.value)\n if (Option.isNone(decoded) || !NotificationEvent.isPromoted(decoded.value)) return Option.none()\n return Option.some(decoded.value)\n })\n\n const load = (runId: JournalEvent.RunId): Effect.Effect<Loaded, Journal.JournalError> =>\n Effect.gen(function*() {\n const base: Loaded = folded.get(runId) ?? {\n state: NotificationState.empty(capacity),\n admissions: HashMap.empty(),\n promotions: HashMap.empty(),\n cursor: undefined\n }\n const fresh: Array<JournalEvent.Entry> = []\n let after = base.cursor === undefined ? undefined : JournalEvent.Seq.make(base.cursor)\n while (true) {\n // `after` is an exact-optional property upstream, so an explicit\n // `undefined` is not the same as an absent key.\n const page = yield* journal.entries({\n runId,\n eventTypes: [NotificationEvent.AdmittedEventType, NotificationEvent.PromotedEventType],\n ...(after === undefined ? {} : { after }),\n limit: 512\n })\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 let state = base.state\n let cursor = base.cursor\n // Persistent maps: one event adds a node and leaves the fold the\n // previous load published untouched, where copying both maps would\n // cost the run's whole history on every event and make a long run's\n // folding quadratic in its own admissions.\n let admissions = base.admissions\n let promotions = base.promotions\n for (const entry of fresh) {\n cursor = entry.seq\n const decoded = NotificationEvent.fromEntry(entry)\n if (Option.isNone(decoded)) continue\n const event = decoded.value\n if (NotificationEvent.isAdmitted(event)) {\n freeze(event.notification)\n admissions = HashMap.set(admissions, event.notification.id, {\n version: event.version,\n fingerprint: event.fingerprint,\n decision: event.decision,\n seq: entry.seq\n })\n state = Replay.applyAdmitted(state, event, entry.seq)\n } else {\n promotions = HashMap.set(\n promotions,\n NotificationEvent.drainKey(event.targetLineageId, event.boundary),\n entry.seq\n )\n state = NotificationState.applyPromoted(state, event.ids)\n }\n }\n\n const loaded: Loaded = { state, admissions, promotions, cursor }\n yield* journal.whenCommitted(Effect.sync(() => folded.put(runId, loaded)))\n return loaded\n })\n\n /**\n * One conditional admission: the duplicate check, the capacity guard,\n * and the admission record, decided and written inside ONE journal\n * write transaction.\n *\n * This is the queue's conditional insert, the same read-guarded write\n * the journal itself uses for its dedupe and fence conditions: the\n * guard's reads and the insert share one serialized write transaction,\n * and the durable writer replays the whole body when a concurrent\n * writer commits between them. A decision a stale fold produced can\n * therefore never commit \u2014 the replay re-folds against the committed\n * state and a queue that filled meanwhile refuses \u2014 however many\n * processes share the database. The process-local `operations`\n * semaphore orders this layer's own fibers only; it is not what\n * enforces capacity across processes.\n */\n const admitInTransaction = (\n runId: JournalEvent.RunId,\n admitted: NotificationModel.Notification,\n admittedFingerprint: string,\n version?: number\n ): Effect.Effect<AdmissionReceipt, Journal.JournalError | NotificationError> =>\n Effect.gen(function*() {\n const loaded = yield* load(runId)\n const prior = Option.getOrUndefined(HashMap.get(loaded.admissions, admitted.id))\n const replacing = prior !== undefined && version !== undefined && version > (prior.version ?? 0)\n if (replacing) {\n const original = yield* admittedAt(runId, prior.seq)\n if (Option.isNone(original)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n notificationId: admitted.id,\n message: \"Original steering input is unreadable\"\n })\n }\n const identity = (input: NotificationModel.Notification) => ({ ...input, payload: null })\n if (canonical(identity(original.value.notification)) !== canonical(identity(admitted))) {\n return yield* new NotificationError({\n code: \"notification_id_reused\",\n notificationId: admitted.id,\n message: \"An edit cannot change the notification owner or delivery binding\"\n })\n }\n }\n if (replacing && !loaded.state.items.some((item) => item.notification.id === admitted.id)) {\n const original = yield* admittedAt(runId, prior.seq)\n if (Option.isNone(original)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n message: \"Consumed input is unreadable\"\n })\n }\n return {\n notificationId: admitted.id,\n decision: prior.decision,\n seq: prior.seq,\n duplicate: true,\n consumed: true,\n consumedNotification: original.value.notification\n }\n }\n if (prior !== undefined && version !== undefined && version < (prior.version ?? 0)) {\n return { notificationId: admitted.id, decision: prior.decision, seq: prior.seq, duplicate: true }\n }\n if (prior !== undefined && !replacing) {\n // Legacy rows have no fingerprint; only their persisted content is\n // available for comparison, and the fold keeps identities rather\n // than payloads, so the original is read back at its sequence.\n // New rows settle on the fingerprint alone and read nothing.\n let same = prior.fingerprint === admittedFingerprint\n if (prior.fingerprint === undefined) {\n const original = yield* admittedAt(runId, prior.seq)\n if (Option.isNone(original)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n notificationId: admitted.id,\n message: `The admission for notification ${admitted.id} is no longer readable`\n })\n }\n same = canonical(original.value.notification) === canonical(admitted)\n }\n if (!same) {\n return yield* new NotificationError({\n code: \"notification_id_reused\",\n notificationId: admitted.id,\n message: `Notification id ${admitted.id} was already admitted with different content`\n })\n }\n return {\n notificationId: admitted.id,\n decision: prior.decision,\n seq: prior.seq,\n duplicate: true\n }\n }\n\n const admission = replacing ? { decision: \"coalesced\" as const } : NotificationState.admit(\n loaded.state,\n admitted,\n loaded.cursor === undefined ? 0 : loaded.cursor + 1\n )\n if (admission.decision === \"rejected-full\") {\n // Nothing is journaled. A rejection recorded as an admission\n // would match on every later attempt and burn the id forever,\n // so the queue refuses in the receipt alone and the caller may\n // admit again once a boundary has drained.\n return {\n notificationId: admitted.id,\n decision: admission.decision,\n seq: undefined,\n duplicate: false\n }\n }\n\n const receipt = yield* journal.emitDurableUnfenced(\n new JournalEvent.Input({\n runId,\n sourceId: NotificationEvent.admissionSourceId(admitted.id),\n sourceSeq: JournalEvent.SourceSeq.make(version ?? 0),\n // The sequence is derived from the notification's own id, so\n // a collision IS this admission observed twice. Comparing\n // bytes instead would fail the second writer over `decision`,\n // a field neither caller supplied and each derives from the\n // fill level it happened to load at.\n dedupe: \"identity\",\n eventType: NotificationEvent.AdmittedEventType,\n payload: {\n notification: admitted,\n decision: admission.decision,\n fingerprint: admittedFingerprint,\n ...(version === undefined ? {} : { version })\n }\n })\n )\n const committed = Option.getOrUndefined(HashMap.get((yield* load(runId)).admissions, admitted.id))\n if (committed === undefined) {\n // Only reachable when the emit deduped against an entry this\n // queue did not write, so nothing was committed and there is\n // no admission to report.\n return yield* new NotificationError({\n code: \"notification_id_reused\",\n notificationId: admitted.id,\n message: `The journal identity for notification ${admitted.id} holds an event this queue did not write`\n })\n }\n return {\n notificationId: admitted.id,\n decision: committed.decision,\n seq: committed.seq,\n duplicate: receipt._tag === \"Duplicate\"\n }\n })\n\n return make({\n admit: Effect.fn(\"NotificationQueue.admit\")((rawRunId, notification, version) =>\n Effect.gen(function*() {\n if (version !== undefined && (!Number.isSafeInteger(version) || version < 1)) {\n return yield* new NotificationError({\n code: \"notification_invalid\",\n message: \"version must be a positive safe integer\"\n })\n }\n const admitted = yield* validated(notification)\n // T-COL-12 stays dark: nothing yet authenticates a watcher burst, pins\n // its coding run or enforces fresh machine reads. Refusing here, before\n // the journal, keeps co-admitted steers deliverable on every replay.\n const payload = admitted.payload\n if (\n typeof payload === \"object\" && payload !== null && !Array.isArray(payload) &&\n (payload as Readonly<Record<string, unknown>>)[\"kind\"] === \"outside_change\"\n ) {\n return yield* new NotificationError({\n code: \"notification_refused\",\n notificationId: admitted.id,\n message: \"Outside-change delivery requires authenticated watcher facts and stale-write enforcement\"\n })\n }\n const admittedFingerprint = yield* fingerprint(admitted)\n return yield* journal.transact(\n operations.withPermits(1)(\n admitInTransaction(JournalEvent.RunId.make(rawRunId), admitted, admittedFingerprint, version)\n )\n )\n })\n ),\n drain: Effect.fn(\"NotificationQueue.drain\")((input) =>\n journal.transact(\n operations.withPermits(1)(Effect.gen(function*() {\n // A cutoff no sequence can satisfy would commit this boundary as\n // delivering nothing, and every retry would replay that record.\n if (\n input.cutoffSeq !== undefined && !(Number.isSafeInteger(input.cutoffSeq) && input.cutoffSeq >= 0)\n ) {\n return yield* new NotificationError({\n code: \"notification_invalid\",\n message: \"A drain cutoff must be a non-negative integer journal sequence\",\n path: \"cutoffSeq\"\n })\n }\n const runId = JournalEvent.RunId.make(input.runId)\n const key = NotificationEvent.drainKey(input.targetLineageId, input.boundary)\n const loaded = yield* load(runId)\n // A replay reports what the committed record delivered, read\n // back from the journal: the fold holds the identities, not the\n // notifications, so a run's drained payloads are not retained.\n const delivered = (\n record: NotificationEvent.Promoted,\n admissions: HashMap.HashMap<string, Committed>\n ): Effect.Effect<\n ReadonlyArray<NotificationModel.Notification>,\n Journal.JournalError | NotificationError\n > =>\n Effect.forEach(record.ids, (id) =>\n Effect.gen(function*() {\n const committed = HashMap.get(admissions, id)\n const event = Option.isNone(committed)\n ? Option.none<NotificationEvent.Admitted>()\n : yield* admittedAt(runId, committed.value.seq)\n // A committed drain promises this exact delivery. Missing or\n // corrupt payloads cannot become a successful partial replay.\n if (Option.isNone(event)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n notificationId: id,\n message: `The delivered notification ${id} is no longer readable`\n })\n }\n return event.value.notification\n }))\n\n const replayed = (seq: number, admissions: HashMap.HashMap<string, Committed>) =>\n Effect.gen(function*() {\n const record = yield* promotedAt(runId, seq)\n if (Option.isNone(record)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n message: `The drain record for boundary ${input.boundary} is no longer readable`\n })\n }\n return {\n notifications: yield* delivered(record.value, admissions),\n boundary: input.boundary,\n duplicate: true\n }\n })\n\n const prior = HashMap.get(loaded.promotions, key)\n if (Option.isSome(prior)) return yield* replayed(prior.value, loaded.admissions)\n\n const cutoff = input.cutoffSeq ?? loaded.cursor ?? 0\n // The existing coding park ladder waits for a person's answer.\n // System facts must remain pending there: promoting them would\n // make the harness treat an outside edit as an answered question.\n // Filtering this projection changes only promoted IDs; the journal\n // fold retains every held admission and its original sequence.\n const promotionState = /^\\d+:[a-f0-9]{64}:park:\\d+$/.test(input.boundary)\n ? {\n ...loaded.state,\n items: loaded.state.items.filter((item) => {\n const payload = item.notification.payload\n return !(typeof payload === \"object\" && payload !== null && !Array.isArray(payload) &&\n (payload as Readonly<Record<string, unknown>>).kind === \"outside_change\")\n })\n }\n : loaded.state\n const steers = NotificationState.promoteSteers(promotionState, cutoff, input.targetLineageId)\n const queued = input.wouldIdle && steers.promoted.length === 0\n ? NotificationState.promoteQueued(steers.state, input.targetLineageId)\n : { state: steers.state, promoted: [] }\n const promoted = [...steers.promoted, ...queued.promoted].map((item) => item.notification)\n const receipt = yield* journal.emitDurableUnfenced(\n new JournalEvent.Input({\n runId,\n sourceId: NotificationEvent.drainSourceId(input.targetLineageId, input.boundary),\n sourceSeq: JournalEvent.SourceSeq.make(0),\n // The identity is the drain: this lineage closing this\n // boundary. Two processes that both reach it have observed one\n // event, and the first record committed is the delivery.\n dedupe: \"identity\",\n eventType: NotificationEvent.PromotedEventType,\n payload: {\n boundary: input.boundary,\n targetLineageId: input.targetLineageId,\n ids: promoted.map((notification) => notification.id)\n }\n })\n )\n const settled = yield* load(runId)\n const committed = HashMap.get(settled.promotions, key)\n if (Option.isNone(committed)) {\n return yield* new NotificationError({\n code: \"notification_unavailable\",\n message: `The journal identity for boundary ${input.boundary} holds an event this queue did not write`\n })\n }\n // An accepted emit wrote THIS drain, so the promoted set is the\n // one already in hand and no read-back is owed.\n if (receipt._tag === \"Accepted\") {\n return { notifications: promoted, boundary: input.boundary, duplicate: false }\n }\n return yield* replayed(committed.value, settled.admissions)\n }))\n )\n ),\n pending: Effect.fn(\"NotificationQueue.pending\")((rawRunId) =>\n Effect.map(\n load(JournalEvent.RunId.make(rawRunId)),\n // The fold `load` already performs: admissions add, promotions\n // remove. Read outside the operations semaphore, because a count\n // taken while a boundary drains is a count taken at some instant\n // either side of it, and blocking a supervisor behind a turn\n // boundary would be the worse answer.\n (loaded) => loaded.state.items.map((item) => item.notification)\n )\n )\n })\n })\n )\n\n/**\n * Journal-backed production layer at the default capacity.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer: Layer.Layer<NotificationQueue, never, Journal.Journal> = layerWith()\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,uBAA6B;AAC7B,oBAA2B;AAC3B,qBAAsC;AACtC,oBAAwF;AACxF,gBAA2B;AAC3B,aAAwB;AACxB,wBAAmC;AACnC,wBAAmC;AACnC,wBAAmC;AAmB5B,MAAM,0BAA0B,qBAAO,YAA+B;AAAA,EAC3E;AAAA,EACA;AAAA,IACE,MAAM,qBAAO,SAAS;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC,EAAE;AAAA,MACD,qBAAO,uBAAuB,qBAAO,QAAQ,0BAAmC,CAAC;AAAA,IACnF;AAAA,IACA,SAAS,qBAAO;AAAA;AAAA,IAEhB,gBAAgB,qBAAO,SAAS,qBAAO,MAAM;AAAA;AAAA,IAE7C,MAAM,qBAAO,SAAS,qBAAO,MAAM;AAAA,EACrC;AACF,EAAE;AAAC;AAyGI,MAAM,0BAA0B,sBAAQ,QAAoC;AAAA,EACjF;AACF,EAAE;AAAC;AASI,MAAM,OAAO,CAAC,mBAAqC,kBAAkB,GAAG,cAAc;AAE7F,MAAM,cAAc,CAAC,cACnB,IAAI,kBAAkB,EAAE,MAAM,4BAA4B,SAAS,GAAG,SAAS,kBAAkB,CAAC;AAU7F,MAAM,WAAW,CAAC,YAA8B,CAAC,MACtD,KAAK;AAAA,EACH,OAAO,qBAAO,GAAG,yBAAyB,EAAE,MAAM,qBAAO,KAAK,YAAY,OAAO,CAAC,CAAC;AAAA,EACnF,OAAO,qBAAO,GAAG,yBAAyB,EAAE,MAAM,q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K;AACjC,kBAAM,YAAY,sBAAQ,IAAI,QAAQ,YAAY,GAAG;AACrD,gBAAI,qBAAO,OAAO,SAAS,GAAG;AAC5B,qBAAO,OAAO,IAAI,kBAAkB;AAAA,gBAClC,MAAM;AAAA,gBACN,SAAS,qCAAqC,MAAM,QAAQ;AAAA,cAC9D,CAAC;AAAA,YACH;AAGA,gBAAI,QAAQ,SAAS,YAAY;AAC/B,qBAAO,EAAE,eAAe,UAAU,UAAU,MAAM,UAAU,WAAW,MAAM;AAAA,YAC/E;AACA,mBAAO,OAAO,SAAS,UAAU,OAAO,QAAQ,UAAU;AAAA,UAC5D,CAAC,CAAC;AAAA,QACJ;AAAA,MACF;AAAA,MACA,SAAS,qBAAO,GAAG,2BAA2B;AAAA,QAAE,CAAC,aAC/C,qBAAO;AAAA,UACL,KAAK,4BAAa,MAAM,KAAK,QAAQ,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAMtC,CAAC,WAAW,OAAO,MAAM,MAAM,IAAI,CAAC,SAAS,KAAK,YAAY;AAAA,QAChE;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH;AAQK,MAAM,QAAgE,UAAU;",
6
6
  "names": ["committed"]
7
7
  }
@@ -13,7 +13,10 @@ import * as NotificationState from "./NotificationState.ts";
13
13
  * `NotificationState.applyAdmission` applies the decision each record already
14
14
  * committed, and an admitted record is retained however many are pending. A
15
15
  * composition built with `NotificationQueue.layerWith` above the default
16
- * replays every admission it wrote.
16
+ * replays every admission it wrote. A versioned edit of a steer that is still
17
+ * pending replaces that item in place, exactly as the queue's own fold reads
18
+ * it, so an edited steer projects as one pending item rather than one per
19
+ * version.
17
20
  *
18
21
  * The projected `capacity` is `NotificationState.defaultCapacity` because the
19
22
  * initial state has to start somewhere and no journal record carries the bound
@@ -1 +1 @@
1
- {"version":3,"file":"Projection.d.ts","sourceRoot":"","sources":["../../src/Projection.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,IAAI,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AAIjE,OAAO,KAAK,iBAAiB,MAAM,wBAAwB,CAAA;AAE3D;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,MAAM,qEAejB,CAAA"}
1
+ {"version":3,"file":"Projection.d.ts","sourceRoot":"","sources":["../../src/Projection.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,IAAI,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AAKjE,OAAO,KAAK,iBAAiB,MAAM,wBAAwB,CAAA;AAE3D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,MAAM,qEAajB,CAAA"}
@@ -34,6 +34,7 @@ module.exports = __toCommonJS(Projection_exports);
34
34
  var import_journal = require("@smthrs/journal");
35
35
  var Effect = __toESM(require("effect/Effect"), 1);
36
36
  var Option = __toESM(require("effect/Option"), 1);
37
+ var Replay = __toESM(require("./internal/replay.js"), 1);
37
38
  var NotificationEvent = __toESM(require("./NotificationEvent.js"), 1);
38
39
  var NotificationState = __toESM(require("./NotificationState.js"), 1);
39
40
  const derive = import_journal.Projection.make({
@@ -44,9 +45,7 @@ const derive = import_journal.Projection.make({
44
45
  if (Option.isNone(decoded)) return Effect.succeed(state);
45
46
  const event = decoded.value;
46
47
  if (NotificationEvent.isAdmitted(event)) {
47
- return Effect.succeed(
48
- NotificationState.applyAdmission(state, event.notification, entry.seq, event.decision)
49
- );
48
+ return Effect.succeed(Replay.applyAdmitted(state, event, entry.seq));
50
49
  }
51
50
  return Effect.succeed(NotificationState.applyPromoted(state, event.ids));
52
51
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/Projection.ts"],
4
- "sourcesContent": ["/**\n * Journal projection for pending notifications.\n *\n * @since 0.1.0\n */\n\nimport { Projection as JournalProjection } from \"@smthrs/journal\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as NotificationEvent from \"./NotificationEvent.ts\"\nimport * as NotificationState from \"./NotificationState.ts\"\n\n/**\n * Re-derives pending notifications from admitted and promoted journal events.\n * Foreign journal entries leave the state unchanged.\n *\n * Replay never re-decides, so capacity does not truncate it:\n * `NotificationState.applyAdmission` applies the decision each record already\n * committed, and an admitted record is retained however many are pending. A\n * composition built with `NotificationQueue.layerWith` above the default\n * replays every admission it wrote.\n *\n * The projected `capacity` is `NotificationState.defaultCapacity` because the\n * initial state has to start somewhere and no journal record carries the bound\n * the layer was built at. Read `items`, not `capacity`, to learn what a run\n * holds.\n *\n * @category projections\n * @since 0.1.0\n */\nexport const derive = JournalProjection.make({\n name: \"flows/notifications\",\n initial: NotificationState.empty(NotificationState.defaultCapacity),\n reduce: (state, entry) => {\n const decoded = NotificationEvent.fromEntry(entry)\n if (Option.isNone(decoded)) return Effect.succeed(state)\n\n const event = decoded.value\n if (NotificationEvent.isAdmitted(event)) {\n return Effect.succeed(\n NotificationState.applyAdmission(state, event.notification, entry.seq, event.decision)\n )\n }\n return Effect.succeed(NotificationState.applyPromoted(state, event.ids))\n }\n})\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,qBAAgD;AAChD,aAAwB;AACxB,aAAwB;AACxB,wBAAmC;AACnC,wBAAmC;AAoB5B,MAAM,SAAS,eAAAA,WAAkB,KAAK;AAAA,EAC3C,MAAM;AAAA,EACN,SAAS,kBAAkB,MAAM,kBAAkB,eAAe;AAAA,EAClE,QAAQ,CAAC,OAAO,UAAU;AACxB,UAAM,UAAU,kBAAkB,UAAU,KAAK;AACjD,QAAI,OAAO,OAAO,OAAO,EAAG,QAAO,OAAO,QAAQ,KAAK;AAEvD,UAAM,QAAQ,QAAQ;AACtB,QAAI,kBAAkB,WAAW,KAAK,GAAG;AACvC,aAAO,OAAO;AAAA,QACZ,kBAAkB,eAAe,OAAO,MAAM,cAAc,MAAM,KAAK,MAAM,QAAQ;AAAA,MACvF;AAAA,IACF;AACA,WAAO,OAAO,QAAQ,kBAAkB,cAAc,OAAO,MAAM,GAAG,CAAC;AAAA,EACzE;AACF,CAAC;",
4
+ "sourcesContent": ["/**\n * Journal projection for pending notifications.\n *\n * @since 0.1.0\n */\n\nimport { Projection as JournalProjection } from \"@smthrs/journal\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Replay from \"./internal/replay.ts\"\nimport * as NotificationEvent from \"./NotificationEvent.ts\"\nimport * as NotificationState from \"./NotificationState.ts\"\n\n/**\n * Re-derives pending notifications from admitted and promoted journal events.\n * Foreign journal entries leave the state unchanged.\n *\n * Replay never re-decides, so capacity does not truncate it:\n * `NotificationState.applyAdmission` applies the decision each record already\n * committed, and an admitted record is retained however many are pending. A\n * composition built with `NotificationQueue.layerWith` above the default\n * replays every admission it wrote. A versioned edit of a steer that is still\n * pending replaces that item in place, exactly as the queue's own fold reads\n * it, so an edited steer projects as one pending item rather than one per\n * version.\n *\n * The projected `capacity` is `NotificationState.defaultCapacity` because the\n * initial state has to start somewhere and no journal record carries the bound\n * the layer was built at. Read `items`, not `capacity`, to learn what a run\n * holds.\n *\n * @category projections\n * @since 0.1.0\n */\nexport const derive = JournalProjection.make({\n name: \"flows/notifications\",\n initial: NotificationState.empty(NotificationState.defaultCapacity),\n reduce: (state, entry) => {\n const decoded = NotificationEvent.fromEntry(entry)\n if (Option.isNone(decoded)) return Effect.succeed(state)\n\n const event = decoded.value\n if (NotificationEvent.isAdmitted(event)) {\n return Effect.succeed(Replay.applyAdmitted(state, event, entry.seq))\n }\n return Effect.succeed(NotificationState.applyPromoted(state, event.ids))\n }\n})\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,qBAAgD;AAChD,aAAwB;AACxB,aAAwB;AACxB,aAAwB;AACxB,wBAAmC;AACnC,wBAAmC;AAuB5B,MAAM,SAAS,eAAAA,WAAkB,KAAK;AAAA,EAC3C,MAAM;AAAA,EACN,SAAS,kBAAkB,MAAM,kBAAkB,eAAe;AAAA,EAClE,QAAQ,CAAC,OAAO,UAAU;AACxB,UAAM,UAAU,kBAAkB,UAAU,KAAK;AACjD,QAAI,OAAO,OAAO,OAAO,EAAG,QAAO,OAAO,QAAQ,KAAK;AAEvD,UAAM,QAAQ,QAAQ;AACtB,QAAI,kBAAkB,WAAW,KAAK,GAAG;AACvC,aAAO,OAAO,QAAQ,OAAO,cAAc,OAAO,OAAO,MAAM,GAAG,CAAC;AAAA,IACrE;AACA,WAAO,OAAO,QAAQ,kBAAkB,cAAc,OAAO,MAAM,GAAG,CAAC;AAAA,EACzE;AACF,CAAC;",
6
6
  "names": ["JournalProjection"]
7
7
  }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The one replay rule for an admission record, shared by the queue's fold and
3
+ * the journal projection so the two read the same history to the same state.
4
+ *
5
+ * @private
6
+ * @since 1.0.0
7
+ */
8
+ import type * as NotificationEvent from "../NotificationEvent.ts";
9
+ import * as NotificationState from "../NotificationState.ts";
10
+ /**
11
+ * Applies one committed admission record to the state so far.
12
+ *
13
+ * A versioned record whose id is still pending is an edit: it replaces that
14
+ * item in place and keeps its original sequence, so the edit is delivered at
15
+ * the cutoff the first version was admitted under. Every other record applies
16
+ * the decision it committed.
17
+ *
18
+ * @private
19
+ * @since 1.0.0
20
+ */
21
+ export declare const applyAdmitted: (state: NotificationState.State, event: NotificationEvent.Admitted, seq: number) => NotificationState.State;
22
+ //# sourceMappingURL=replay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay.d.ts","sourceRoot":"","sources":["../../../src/internal/replay.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,KAAK,iBAAiB,MAAM,yBAAyB,CAAA;AACjE,OAAO,KAAK,iBAAiB,MAAM,yBAAyB,CAAA;AAE5D;;;;;;;;;;GAUG;AACH,eAAO,MAAM,aAAa,GACxB,OAAO,iBAAiB,CAAC,KAAK,EAC9B,OAAO,iBAAiB,CAAC,QAAQ,EACjC,KAAK,MAAM,KACV,iBAAiB,CAAC,KAYpB,CAAA"}
@@ -0,0 +1,46 @@
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 replay_exports = {};
30
+ __export(replay_exports, {
31
+ applyAdmitted: () => applyAdmitted
32
+ });
33
+ module.exports = __toCommonJS(replay_exports);
34
+ var NotificationState = __toESM(require("../NotificationState.js"), 1);
35
+ const applyAdmitted = (state, event, seq) => {
36
+ if (event.version !== void 0 && state.items.some((item) => item.notification.id === event.notification.id)) {
37
+ return Object.freeze({
38
+ ...state,
39
+ items: Object.freeze(state.items.map(
40
+ (item) => item.notification.id === event.notification.id ? Object.freeze({ notification: event.notification, seq: item.seq }) : item
41
+ ))
42
+ });
43
+ }
44
+ return NotificationState.applyAdmission(state, event.notification, seq, event.decision);
45
+ };
46
+ //# sourceMappingURL=replay.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/internal/replay.ts"],
4
+ "sourcesContent": ["/**\n * The one replay rule for an admission record, shared by the queue's fold and\n * the journal projection so the two read the same history to the same state.\n *\n * @private\n * @since 1.0.0\n */\n\nimport type * as NotificationEvent from \"../NotificationEvent.ts\"\nimport * as NotificationState from \"../NotificationState.ts\"\n\n/**\n * Applies one committed admission record to the state so far.\n *\n * A versioned record whose id is still pending is an edit: it replaces that\n * item in place and keeps its original sequence, so the edit is delivered at\n * the cutoff the first version was admitted under. Every other record applies\n * the decision it committed.\n *\n * @private\n * @since 1.0.0\n */\nexport const applyAdmitted = (\n state: NotificationState.State,\n event: NotificationEvent.Admitted,\n seq: number\n): NotificationState.State => {\n if (event.version !== undefined && state.items.some((item) => item.notification.id === event.notification.id)) {\n return Object.freeze({\n ...state,\n items: Object.freeze(state.items.map((item) =>\n item.notification.id === event.notification.id\n ? Object.freeze({ notification: event.notification, seq: item.seq })\n : item\n ))\n })\n }\n return NotificationState.applyAdmission(state, event.notification, seq, event.decision)\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,wBAAmC;AAa5B,MAAM,gBAAgB,CAC3B,OACA,OACA,QAC4B;AAC5B,MAAI,MAAM,YAAY,UAAa,MAAM,MAAM,KAAK,CAAC,SAAS,KAAK,aAAa,OAAO,MAAM,aAAa,EAAE,GAAG;AAC7G,WAAO,OAAO,OAAO;AAAA,MACnB,GAAG;AAAA,MACH,OAAO,OAAO,OAAO,MAAM,MAAM;AAAA,QAAI,CAAC,SACpC,KAAK,aAAa,OAAO,MAAM,aAAa,KACxC,OAAO,OAAO,EAAE,cAAc,MAAM,cAAc,KAAK,KAAK,IAAI,CAAC,IACjE;AAAA,MACN,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACA,SAAO,kBAAkB,eAAe,OAAO,MAAM,cAAc,KAAK,MAAM,QAAQ;AACxF;",
6
+ "names": []
7
+ }
@@ -81,7 +81,8 @@ export interface DrainInput {
81
81
  * The journal sequence that opened this turn. A steer admitted after it is
82
82
  * held for the next boundary, which is what keeps a message that arrived
83
83
  * mid-turn out of the turn already in flight. Omitting it delivers
84
- * everything pending for the lineage.
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.
85
86
  */
86
87
  readonly cutoffSeq?: number | undefined;
87
88
  }
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationQueue.d.ts","sourceRoot":"","sources":["../../src/NotificationQueue.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAAE,OAAO,EAAgB,MAAM,iBAAiB,CAAA;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAW,KAAK,EAAU,MAAM,EAA0B,MAAM,QAAQ,CAAA;AAEhG,OAAO,KAAK,iBAAiB,MAAM,mBAAmB,CAAA;AAEtD,OAAO,KAAK,iBAAiB,MAAM,wBAAwB,CAAA;;;;IAiCvD,oEAAoE;;IAEpE,sEAAsE;;;AAjC1E;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,iBAAkB,SAAQ,sBAmBtC;CAAG;AAEJ;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;IAC/B,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC,iBAAiB,CAAA;IACtD,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;IAChC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;IA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,CAAC,OAAO,EAAE,CAChB,KAAK,EAAE,MAAM,KACV,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,iBAAiB,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC,YAAY,GAAG,iBAAiB,CAAC,CAAA;CAC5G;;AAED;;;;;GAKG;AACH,qBAAa,iBAAkB,SAAQ,sBAEtC;CAAG;AAEJ;;;;;;GAMG;AACH,eAAO,MAAM,IAAI,GAAI,gBAAgB,OAAO,KAAG,OAA+C,CAAA;AAK9F;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ,GAAI,YAAW,OAAO,CAAC,OAAO,CAAM,KAAG,OAMxD,CAAA;AAEJ;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAI,YAAW,OAAO,CAAC,OAAO,CAAM,KAAG,KAAK,CAAC,KAAK,CAAC,iBAAiB,CACnC,CAAA;AAkLvD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,SAAS,GACpB,UAAS;IAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAAO,KACvD,KAAK,CAAC,KAAK,CAAC,iBAAiB,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CA2brD,CAAA;AAEH;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,iBAAiB,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAe,CAAA"}
@@ -11,6 +11,7 @@ import { digestSync } from "@smthrs/crypto/Sha256";
11
11
  import { Journal, JournalEvent } from "@smthrs/journal";
12
12
  import { Context, Effect, HashMap, Layer, Option, Schema, SchemaIssue, Semaphore } from "effect";
13
13
  import * as FoldCache from "./internal/foldCache.js";
14
+ import * as Replay from "./internal/replay.js";
14
15
  import * as NotificationModel from "./Notification.js";
15
16
  import * as NotificationEvent from "./NotificationEvent.js";
16
17
  import * as NotificationState from "./NotificationState.js";
@@ -332,18 +333,7 @@ export const layerWith = (options = {}) => Layer.effect(NotificationQueue, Effec
332
333
  decision: event.decision,
333
334
  seq: entry.seq
334
335
  });
335
- if (event.version !== undefined &&
336
- state.items.some((item) => item.notification.id === event.notification.id)) {
337
- state = Object.freeze({
338
- ...state,
339
- items: Object.freeze(state.items.map((item) => item.notification.id === event.notification.id
340
- ? Object.freeze({ notification: event.notification, seq: item.seq })
341
- : item))
342
- });
343
- }
344
- else {
345
- state = NotificationState.applyAdmission(state, event.notification, entry.seq, event.decision);
346
- }
336
+ state = Replay.applyAdmitted(state, event, entry.seq);
347
337
  }
348
338
  else {
349
339
  promotions = HashMap.set(promotions, NotificationEvent.drainKey(event.targetLineageId, event.boundary), entry.seq);
@@ -517,6 +507,15 @@ export const layerWith = (options = {}) => Layer.effect(NotificationQueue, Effec
517
507
  return yield* journal.transact(operations.withPermits(1)(admitInTransaction(JournalEvent.RunId.make(rawRunId), admitted, admittedFingerprint, version)));
518
508
  })),
519
509
  drain: Effect.fn("NotificationQueue.drain")((input) => journal.transact(operations.withPermits(1)(Effect.gen(function* () {
510
+ // A cutoff no sequence can satisfy would commit this boundary as
511
+ // delivering nothing, and every retry would replay that record.
512
+ if (input.cutoffSeq !== undefined && !(Number.isSafeInteger(input.cutoffSeq) && input.cutoffSeq >= 0)) {
513
+ return yield* new NotificationError({
514
+ code: "notification_invalid",
515
+ message: "A drain cutoff must be a non-negative integer journal sequence",
516
+ path: "cutoffSeq"
517
+ });
518
+ }
520
519
  const runId = JournalEvent.RunId.make(input.runId);
521
520
  const key = NotificationEvent.drainKey(input.targetLineageId, input.boundary);
522
521
  const loaded = yield* load(runId);