@smthrs/notifications 0.0.0-stage → 1.0.0-rc.12
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/CHANGELOG.md +127 -0
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/dist/cjs/AlertPolicy.d.ts +284 -0
- package/dist/cjs/AlertPolicy.d.ts.map +1 -0
- package/dist/cjs/AlertPolicy.js +124 -0
- package/dist/cjs/AlertPolicy.js.map +7 -0
- package/dist/cjs/AlertRuntime.d.ts +90 -0
- package/dist/cjs/AlertRuntime.d.ts.map +1 -0
- package/dist/cjs/AlertRuntime.js +166 -0
- package/dist/cjs/AlertRuntime.js.map +7 -0
- package/dist/cjs/AlertSink.d.ts +101 -0
- package/dist/cjs/AlertSink.d.ts.map +1 -0
- package/dist/cjs/AlertSink.js +44 -0
- package/dist/cjs/AlertSink.js.map +7 -0
- package/dist/cjs/Alerts.d.ts +57 -0
- package/dist/cjs/Alerts.d.ts.map +1 -0
- package/dist/cjs/Alerts.js +46 -0
- package/dist/cjs/Alerts.js.map +7 -0
- package/dist/cjs/Notification.d.ts +214 -0
- package/dist/cjs/Notification.d.ts.map +1 -0
- package/dist/cjs/Notification.js +62 -0
- package/dist/cjs/Notification.js.map +7 -0
- package/dist/cjs/NotificationEvent.d.ts +214 -0
- package/dist/cjs/NotificationEvent.d.ts.map +1 -0
- package/dist/cjs/NotificationEvent.js +84 -0
- package/dist/cjs/NotificationEvent.js.map +7 -0
- package/dist/cjs/NotificationQueue.d.ts +194 -0
- package/dist/cjs/NotificationQueue.d.ts.map +1 -0
- package/dist/cjs/NotificationQueue.js +477 -0
- package/dist/cjs/NotificationQueue.js.map +7 -0
- package/dist/cjs/NotificationState.d.ts +169 -0
- package/dist/cjs/NotificationState.d.ts.map +1 -0
- package/dist/cjs/NotificationState.js +110 -0
- package/dist/cjs/NotificationState.js.map +7 -0
- package/dist/cjs/Projection.d.ts +30 -0
- package/dist/cjs/Projection.d.ts.map +1 -0
- package/dist/cjs/Projection.js +53 -0
- package/dist/cjs/Projection.js.map +7 -0
- package/dist/cjs/SteerPayload.d.ts +177 -0
- package/dist/cjs/SteerPayload.d.ts.map +1 -0
- package/dist/cjs/SteerPayload.js +61 -0
- package/dist/cjs/SteerPayload.js.map +7 -0
- package/dist/cjs/index.d.ts +41 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +47 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/cjs/internal/foldCache.d.ts +36 -0
- package/dist/cjs/internal/foldCache.d.ts.map +1 -0
- package/dist/cjs/internal/foldCache.js +54 -0
- package/dist/cjs/internal/foldCache.js.map +7 -0
- package/dist/cjs/internal/replay.d.ts +22 -0
- package/dist/cjs/internal/replay.d.ts.map +1 -0
- package/dist/cjs/internal/replay.js +46 -0
- package/dist/cjs/internal/replay.js.map +7 -0
- package/dist/cjs/layerWebhook.d.ts +60 -0
- package/dist/cjs/layerWebhook.d.ts.map +1 -0
- package/dist/cjs/layerWebhook.js +145 -0
- package/dist/cjs/layerWebhook.js.map +7 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/AlertPolicy.d.ts +284 -0
- package/dist/esm/AlertPolicy.d.ts.map +1 -0
- package/dist/esm/AlertPolicy.js +284 -0
- package/dist/esm/AlertPolicy.js.map +1 -0
- package/dist/esm/AlertRuntime.d.ts +90 -0
- package/dist/esm/AlertRuntime.d.ts.map +1 -0
- package/dist/esm/AlertRuntime.js +191 -0
- package/dist/esm/AlertRuntime.js.map +1 -0
- package/dist/esm/AlertSink.d.ts +101 -0
- package/dist/esm/AlertSink.d.ts.map +1 -0
- package/dist/esm/AlertSink.js +63 -0
- package/dist/esm/AlertSink.js.map +1 -0
- package/dist/esm/Alerts.d.ts +57 -0
- package/dist/esm/Alerts.d.ts.map +1 -0
- package/dist/esm/Alerts.js +57 -0
- package/dist/esm/Alerts.js.map +1 -0
- package/dist/esm/Notification.d.ts +214 -0
- package/dist/esm/Notification.d.ts.map +1 -0
- package/dist/esm/Notification.js +121 -0
- package/dist/esm/Notification.js.map +1 -0
- package/dist/esm/NotificationEvent.d.ts +214 -0
- package/dist/esm/NotificationEvent.d.ts.map +1 -0
- package/dist/esm/NotificationEvent.js +158 -0
- package/dist/esm/NotificationEvent.js.map +1 -0
- package/dist/esm/NotificationQueue.d.ts +194 -0
- package/dist/esm/NotificationQueue.d.ts.map +1 -0
- package/dist/esm/NotificationQueue.js +625 -0
- package/dist/esm/NotificationQueue.js.map +1 -0
- package/dist/esm/NotificationState.d.ts +169 -0
- package/dist/esm/NotificationState.d.ts.map +1 -0
- package/dist/esm/NotificationState.js +191 -0
- package/dist/esm/NotificationState.js.map +1 -0
- package/dist/esm/Projection.d.ts +30 -0
- package/dist/esm/Projection.d.ts.map +1 -0
- package/dist/esm/Projection.js +47 -0
- package/dist/esm/Projection.js.map +1 -0
- package/dist/esm/SteerPayload.d.ts +177 -0
- package/dist/esm/SteerPayload.d.ts.map +1 -0
- package/dist/esm/SteerPayload.js +139 -0
- package/dist/esm/SteerPayload.js.map +1 -0
- package/dist/esm/index.d.ts +41 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +41 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/internal/foldCache.d.ts +36 -0
- package/dist/esm/internal/foldCache.d.ts.map +1 -0
- package/dist/esm/internal/foldCache.js +58 -0
- package/dist/esm/internal/foldCache.js.map +1 -0
- package/dist/esm/internal/replay.d.ts +22 -0
- package/dist/esm/internal/replay.d.ts.map +1 -0
- package/dist/esm/internal/replay.js +31 -0
- package/dist/esm/internal/replay.js.map +1 -0
- package/dist/esm/layerWebhook.d.ts +60 -0
- package/dist/esm/layerWebhook.d.ts.map +1 -0
- package/dist/esm/layerWebhook.js +186 -0
- package/dist/esm/layerWebhook.js.map +1 -0
- package/docs/README.md +146 -0
- package/docs/api.md +443 -0
- package/docs/concepts/admission-and-promotion.md +144 -0
- package/docs/concepts/alerting.md +138 -0
- package/docs/concepts/journal-records.md +132 -0
- package/docs/guides/alert-on-a-stuck-run.md +140 -0
- package/docs/guides/drain-at-a-turn-boundary.md +95 -0
- package/docs/guides/handle-a-full-queue.md +102 -0
- package/docs/guides/report-pending-notifications.md +92 -0
- package/docs/guides/send-alerts-to-a-webhook.md +155 -0
- package/docs/guides/steer-a-run.md +127 -0
- package/docs/guides/testing.md +161 -0
- package/docs/installation.md +123 -0
- package/docs/quickstart.md +159 -0
- package/docs/troubleshooting.md +254 -0
- package/package.json +182 -3
- package/src/AlertPolicy.ts +377 -0
- package/src/AlertRuntime.ts +280 -0
- package/src/AlertSink.ts +105 -0
- package/src/Alerts.ts +71 -0
- package/src/Notification.ts +171 -0
- package/src/NotificationEvent.ts +213 -0
- package/src/NotificationQueue.ts +856 -0
- package/src/NotificationState.ts +295 -0
- package/src/Projection.ts +48 -0
- package/src/SteerPayload.ts +198 -0
- package/src/index.ts +47 -0
- package/src/internal/foldCache.ts +72 -0
- package/src/internal/replay.ts +39 -0
- package/src/layerWebhook.ts +239 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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 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,sBA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
3
|
+
*
|
|
4
|
+
* @since 0.1.0
|
|
5
|
+
*/
|
|
6
|
+
import type { Notification } from "./Notification.ts";
|
|
7
|
+
import type * as NotificationEvent from "./NotificationEvent.ts";
|
|
8
|
+
/**
|
|
9
|
+
* The default maximum number of pending notifications retained per run.
|
|
10
|
+
*
|
|
11
|
+
* The bound is what makes an undrained run a known quantity instead of a
|
|
12
|
+
* function of how long it was ignored. Admitting past it decides
|
|
13
|
+
* `rejected-full`, which retains nothing and writes no journal entry, so the
|
|
14
|
+
* notification is admissible again once a boundary drains.
|
|
15
|
+
* `NotificationQueue.layerWith` raises or lowers it for one composition.
|
|
16
|
+
*
|
|
17
|
+
* @category constants
|
|
18
|
+
* @since 0.1.0
|
|
19
|
+
*/
|
|
20
|
+
export declare const defaultCapacity = 128;
|
|
21
|
+
/**
|
|
22
|
+
* A notification retained until it is promoted at a harness safe point.
|
|
23
|
+
*
|
|
24
|
+
* `seq` is the journal sequence the admission committed at, which is what a
|
|
25
|
+
* turn-close cutoff compares against.
|
|
26
|
+
*
|
|
27
|
+
* @category models
|
|
28
|
+
* @since 0.1.0
|
|
29
|
+
*/
|
|
30
|
+
export interface Pending {
|
|
31
|
+
readonly notification: Notification;
|
|
32
|
+
readonly seq: number;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The result recorded for one durable notification admission.
|
|
36
|
+
*
|
|
37
|
+
* Re-exported from `NotificationEvent`, which owns the single declaration, so
|
|
38
|
+
* the type these signatures use and the schema the journal validates against
|
|
39
|
+
* can never drift apart.
|
|
40
|
+
*
|
|
41
|
+
* @category models
|
|
42
|
+
* @since 0.1.0
|
|
43
|
+
*/
|
|
44
|
+
export type AdmissionDecision = NotificationEvent.AdmissionDecision;
|
|
45
|
+
/**
|
|
46
|
+
* Immutable bounded queue state derived from the notification journal.
|
|
47
|
+
*
|
|
48
|
+
* The value is immutable in its own structure: the state and the `Pending`
|
|
49
|
+
* wrappers it holds are frozen, and every transition returns a new state
|
|
50
|
+
* rather than editing this one. The notifications inside are not re-frozen
|
|
51
|
+
* here, because `NotificationQueue.admit` already snapshots a notification at
|
|
52
|
+
* the durability boundary, so no state built by the queue shares mutable
|
|
53
|
+
* structure with a caller.
|
|
54
|
+
*
|
|
55
|
+
* @category models
|
|
56
|
+
* @since 0.1.0
|
|
57
|
+
*/
|
|
58
|
+
export interface State {
|
|
59
|
+
readonly capacity: number;
|
|
60
|
+
readonly items: ReadonlyArray<Pending>;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* One pure admission transition and its visible decision.
|
|
64
|
+
*
|
|
65
|
+
* @category models
|
|
66
|
+
* @since 0.1.0
|
|
67
|
+
*/
|
|
68
|
+
export interface Admission {
|
|
69
|
+
readonly state: State;
|
|
70
|
+
readonly decision: AdmissionDecision;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A pure promotion transition: what a boundary takes, and what is left.
|
|
74
|
+
*
|
|
75
|
+
* @category models
|
|
76
|
+
* @since 0.1.0
|
|
77
|
+
*/
|
|
78
|
+
export interface Promotion {
|
|
79
|
+
readonly state: State;
|
|
80
|
+
readonly promoted: ReadonlyArray<Pending>;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Creates an empty bounded notification queue.
|
|
84
|
+
*
|
|
85
|
+
* A capacity that is not a finite number becomes zero, so a misconfigured
|
|
86
|
+
* bound refuses everything loudly rather than retaining an unbounded backlog.
|
|
87
|
+
*
|
|
88
|
+
* @param capacity the maximum number of pending notifications
|
|
89
|
+
* @category constructors
|
|
90
|
+
* @since 0.1.0
|
|
91
|
+
*/
|
|
92
|
+
export declare const empty: (capacity: number) => State;
|
|
93
|
+
/**
|
|
94
|
+
* Admits a notification, coalescing only pending system events that share both
|
|
95
|
+
* a key and a target lineage. Coalescing retains the first sequence so replay
|
|
96
|
+
* order remains stable.
|
|
97
|
+
*
|
|
98
|
+
* A queue already at capacity decides `rejected-full` and retains nothing. The
|
|
99
|
+
* caller owns what happens next: `NotificationQueue.admit` writes no journal
|
|
100
|
+
* entry for that decision, so the same notification is admissible again once a
|
|
101
|
+
* boundary drains.
|
|
102
|
+
*
|
|
103
|
+
* @param state the current queue state
|
|
104
|
+
* @param notification the notification to admit
|
|
105
|
+
* @param seq the journal sequence the admission is recorded at
|
|
106
|
+
* @category operations
|
|
107
|
+
* @since 0.1.0
|
|
108
|
+
*/
|
|
109
|
+
export declare const admit: (state: State, notification: Notification, seq: number) => Admission;
|
|
110
|
+
/**
|
|
111
|
+
* Applies the decision already committed in an admission journal event.
|
|
112
|
+
*
|
|
113
|
+
* Replay never re-decides: the committed decision is the one that happened,
|
|
114
|
+
* whatever this process's state would have chosen. The `rejected-full` branch
|
|
115
|
+
* stays reachable for a record written by any other writer, even though this
|
|
116
|
+
* package never writes one.
|
|
117
|
+
*
|
|
118
|
+
* @param state the state so far
|
|
119
|
+
* @param notification the notification the record admitted
|
|
120
|
+
* @param seq the journal sequence the record committed at
|
|
121
|
+
* @param decision the decision the record carries
|
|
122
|
+
* @category operations
|
|
123
|
+
* @since 0.1.0
|
|
124
|
+
*/
|
|
125
|
+
export declare const applyAdmission: (state: State, notification: Notification, seq: number, decision: AdmissionDecision) => State;
|
|
126
|
+
/**
|
|
127
|
+
* Returns still-pending notifications in their durable journal order.
|
|
128
|
+
*
|
|
129
|
+
* @param state the current queue state
|
|
130
|
+
* @param admission which admission class to report
|
|
131
|
+
* @param targetLineageId the lineage to report for, or every lineage when absent
|
|
132
|
+
* @category getters
|
|
133
|
+
* @since 0.1.0
|
|
134
|
+
*/
|
|
135
|
+
export declare const pending: (state: State, admission: "steer" | "queue", targetLineageId?: string) => ReadonlyArray<Pending>;
|
|
136
|
+
/**
|
|
137
|
+
* Promotes every steer notification admitted at or before the turn-close
|
|
138
|
+
* cutoff. Notifications admitted after the cutoff remain pending.
|
|
139
|
+
*
|
|
140
|
+
* The cutoff is what holds a steer that arrived mid-turn until the next
|
|
141
|
+
* boundary, and `NotificationQueue.DrainInput.cutoffSeq` is how a caller sets
|
|
142
|
+
* it. A drain that names no cutoff delivers everything pending for the lineage.
|
|
143
|
+
*
|
|
144
|
+
* @param state the current queue state
|
|
145
|
+
* @param cutoffSeq the highest admission sequence this boundary may deliver
|
|
146
|
+
* @param targetLineageId the lineage the boundary belongs to, or every lineage when absent
|
|
147
|
+
* @category operations
|
|
148
|
+
* @since 0.1.0
|
|
149
|
+
*/
|
|
150
|
+
export declare const promoteSteers: (state: State, cutoffSeq: number, targetLineageId?: string) => Promotion;
|
|
151
|
+
/**
|
|
152
|
+
* Promotes exactly the oldest pending queue notification.
|
|
153
|
+
*
|
|
154
|
+
* @param state the current queue state
|
|
155
|
+
* @param targetLineageId the lineage the boundary belongs to, or every lineage when absent
|
|
156
|
+
* @category operations
|
|
157
|
+
* @since 0.1.0
|
|
158
|
+
*/
|
|
159
|
+
export declare const promoteQueued: (state: State, targetLineageId?: string) => Promotion;
|
|
160
|
+
/**
|
|
161
|
+
* Applies a durable promotion record while replaying journal history.
|
|
162
|
+
*
|
|
163
|
+
* @param state the state so far
|
|
164
|
+
* @param ids the notification ids the record promoted
|
|
165
|
+
* @category operations
|
|
166
|
+
* @since 0.1.0
|
|
167
|
+
*/
|
|
168
|
+
export declare const applyPromoted: (state: State, ids: ReadonlyArray<string>) => State;
|
|
169
|
+
//# sourceMappingURL=NotificationState.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NotificationState.d.ts","sourceRoot":"","sources":["../../src/NotificationState.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAErD,OAAO,KAAK,KAAK,iBAAiB,MAAM,wBAAwB,CAAA;AAEhE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,MAAM,CAAA;AAElC;;;;;;;;GAQG;AACH,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAA;IACnC,QAAQ,CAAC,GAA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AO,KAAK,EAAE,kBAAkB,MAAM,KAAG,SAWtE,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,GAAI,OAAO,KAAK,EAAE,KAAK,aAAa,CAAC,MAAM,CAAC,KAAG,KAIxE,CAAA"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var NotificationState_exports = {};
|
|
20
|
+
__export(NotificationState_exports, {
|
|
21
|
+
admit: () => admit,
|
|
22
|
+
applyAdmission: () => applyAdmission,
|
|
23
|
+
applyPromoted: () => applyPromoted,
|
|
24
|
+
defaultCapacity: () => defaultCapacity,
|
|
25
|
+
empty: () => empty,
|
|
26
|
+
pending: () => pending,
|
|
27
|
+
promoteQueued: () => promoteQueued,
|
|
28
|
+
promoteSteers: () => promoteSteers
|
|
29
|
+
});
|
|
30
|
+
module.exports = __toCommonJS(NotificationState_exports);
|
|
31
|
+
var import_Notification = require("./Notification.js");
|
|
32
|
+
const defaultCapacity = 128;
|
|
33
|
+
const immutable = (capacity, items) => Object.freeze({
|
|
34
|
+
capacity,
|
|
35
|
+
items: Object.freeze(items.map((item) => Object.freeze({ ...item })))
|
|
36
|
+
});
|
|
37
|
+
const normalizedCapacity = (capacity) => Number.isFinite(capacity) ? Math.max(0, Math.floor(capacity)) : 0;
|
|
38
|
+
const immutablePromotion = (state, promoted) => Object.freeze({
|
|
39
|
+
state,
|
|
40
|
+
promoted: Object.freeze(promoted.map((item) => Object.freeze({ ...item })))
|
|
41
|
+
});
|
|
42
|
+
const empty = (capacity) => immutable(normalizedCapacity(capacity), []);
|
|
43
|
+
const coalesceIndex = (state, notification) => {
|
|
44
|
+
const key = (0, import_Notification.coalesceKey)(notification);
|
|
45
|
+
if (key === null) return -1;
|
|
46
|
+
return state.items.findIndex(
|
|
47
|
+
(item) => item.notification.targetLineageId === notification.targetLineageId && (0, import_Notification.coalesceKey)(item.notification) === key
|
|
48
|
+
);
|
|
49
|
+
};
|
|
50
|
+
const admit = (state, notification, seq) => {
|
|
51
|
+
const coalesced = coalesceIndex(state, notification);
|
|
52
|
+
if (coalesced !== -1) {
|
|
53
|
+
const existing = state.items[coalesced];
|
|
54
|
+
const items = [...state.items];
|
|
55
|
+
items[coalesced] = { notification, seq: existing.seq };
|
|
56
|
+
return Object.freeze({ state: immutable(state.capacity, items), decision: "coalesced" });
|
|
57
|
+
}
|
|
58
|
+
if (state.items.length >= state.capacity) {
|
|
59
|
+
return Object.freeze({ state, decision: "rejected-full" });
|
|
60
|
+
}
|
|
61
|
+
return Object.freeze({
|
|
62
|
+
state: immutable(state.capacity, [...state.items, { notification, seq }]),
|
|
63
|
+
decision: "admitted"
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
const applyAdmission = (state, notification, seq, decision) => {
|
|
67
|
+
if (decision === "rejected-full") return state;
|
|
68
|
+
if (decision === "admitted") {
|
|
69
|
+
return immutable(state.capacity, [...state.items, { notification, seq }]);
|
|
70
|
+
}
|
|
71
|
+
const index = coalesceIndex(state, notification);
|
|
72
|
+
if (index === -1) return immutable(state.capacity, [...state.items, { notification, seq }]);
|
|
73
|
+
const items = [...state.items];
|
|
74
|
+
items[index] = { notification, seq: items[index].seq };
|
|
75
|
+
return immutable(state.capacity, items);
|
|
76
|
+
};
|
|
77
|
+
const pending = (state, admission, targetLineageId) => Object.freeze(
|
|
78
|
+
state.items.filter(
|
|
79
|
+
(item) => (0, import_Notification.admissionClass)(item.notification) === admission && (targetLineageId === void 0 || item.notification.targetLineageId === targetLineageId)
|
|
80
|
+
)
|
|
81
|
+
);
|
|
82
|
+
const promoteSteers = (state, cutoffSeq, targetLineageId) => {
|
|
83
|
+
const promoted = [];
|
|
84
|
+
const remaining = [];
|
|
85
|
+
for (const item of state.items) {
|
|
86
|
+
if (((0, import_Notification.admissionClass)(item.notification) === "steer" || item.notification._tag === "system-event" && typeof item.notification.payload === "object" && item.notification.payload !== null && !Array.isArray(item.notification.payload) && item.notification.payload.kind === "outside_change") && item.seq <= cutoffSeq && (targetLineageId === void 0 || item.notification.targetLineageId === targetLineageId)) {
|
|
87
|
+
promoted.push(item);
|
|
88
|
+
} else {
|
|
89
|
+
remaining.push(item);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return immutablePromotion(immutable(state.capacity, remaining), promoted);
|
|
93
|
+
};
|
|
94
|
+
const promoteQueued = (state, targetLineageId) => {
|
|
95
|
+
const index = state.items.findIndex(
|
|
96
|
+
(item) => (0, import_Notification.admissionClass)(item.notification) === "queue" && (targetLineageId === void 0 || item.notification.targetLineageId === targetLineageId)
|
|
97
|
+
);
|
|
98
|
+
if (index === -1) return immutablePromotion(state, []);
|
|
99
|
+
const promoted = state.items[index];
|
|
100
|
+
return immutablePromotion(
|
|
101
|
+
immutable(state.capacity, [...state.items.slice(0, index), ...state.items.slice(index + 1)]),
|
|
102
|
+
[promoted]
|
|
103
|
+
);
|
|
104
|
+
};
|
|
105
|
+
const applyPromoted = (state, ids) => {
|
|
106
|
+
if (ids.length === 0) return state;
|
|
107
|
+
const promoted = new Set(ids);
|
|
108
|
+
return immutable(state.capacity, state.items.filter((item) => !promoted.has(item.notification.id)));
|
|
109
|
+
};
|
|
110
|
+
//# sourceMappingURL=NotificationState.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/NotificationState.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Pure pending-notification queue state.\n *\n * @since 0.1.0\n */\n\nimport type { Notification } from \"./Notification.ts\"\nimport { admissionClass, coalesceKey } from \"./Notification.ts\"\nimport type * as NotificationEvent from \"./NotificationEvent.ts\"\n\n/**\n * The default maximum number of pending notifications retained per run.\n *\n * The bound is what makes an undrained run a known quantity instead of a\n * function of how long it was ignored. Admitting past it decides\n * `rejected-full`, which retains nothing and writes no journal entry, so the\n * notification is admissible again once a boundary drains.\n * `NotificationQueue.layerWith` raises or lowers it for one composition.\n *\n * @category constants\n * @since 0.1.0\n */\nexport const defaultCapacity = 128\n\n/**\n * A notification retained until it is promoted at a harness safe point.\n *\n * `seq` is the journal sequence the admission committed at, which is what a\n * turn-close cutoff compares against.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Pending {\n readonly notification: Notification\n readonly seq: number\n}\n\n/**\n * The result recorded for one durable notification admission.\n *\n * Re-exported from `NotificationEvent`, which owns the single declaration, so\n * the type these signatures use and the schema the journal validates against\n * can never drift apart.\n *\n * @category models\n * @since 0.1.0\n */\nexport type AdmissionDecision = NotificationEvent.AdmissionDecision\n\n/**\n * Immutable bounded queue state derived from the notification journal.\n *\n * The value is immutable in its own structure: the state and the `Pending`\n * wrappers it holds are frozen, and every transition returns a new state\n * rather than editing this one. The notifications inside are not re-frozen\n * here, because `NotificationQueue.admit` already snapshots a notification at\n * the durability boundary, so no state built by the queue shares mutable\n * structure with a caller.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface State {\n readonly capacity: number\n readonly items: ReadonlyArray<Pending>\n}\n\n/**\n * One pure admission transition and its visible decision.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Admission {\n readonly state: State\n readonly decision: AdmissionDecision\n}\n\n/**\n * A pure promotion transition: what a boundary takes, and what is left.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Promotion {\n readonly state: State\n readonly promoted: ReadonlyArray<Pending>\n}\n\nconst immutable = (capacity: number, items: ReadonlyArray<Pending>): State =>\n Object.freeze({\n capacity,\n items: Object.freeze(items.map((item) => Object.freeze({ ...item })))\n })\n\nconst normalizedCapacity = (capacity: number): number =>\n Number.isFinite(capacity) ? Math.max(0, Math.floor(capacity)) : 0\n\nconst immutablePromotion = (state: State, promoted: ReadonlyArray<Pending>): Promotion =>\n Object.freeze({\n state,\n promoted: Object.freeze(promoted.map((item) => Object.freeze({ ...item })))\n })\n\n/**\n * Creates an empty bounded notification queue.\n *\n * A capacity that is not a finite number becomes zero, so a misconfigured\n * bound refuses everything loudly rather than retaining an unbounded backlog.\n *\n * @param capacity the maximum number of pending notifications\n * @category constructors\n * @since 0.1.0\n */\nexport const empty = (capacity: number): State => immutable(normalizedCapacity(capacity), [])\n\n/**\n * The pending item a notification coalesces into, or `-1` when it coalesces\n * with nothing.\n *\n * A coalescing key is scoped to one lineage. `targetLineageId` is the reader's\n * address, so two branches reporting the same condition under one ordinary key\n * are two pending notifications, and neither erases the other's.\n */\nconst coalesceIndex = (state: State, notification: Notification): number => {\n const key = coalesceKey(notification)\n if (key === null) return -1\n return state.items.findIndex((item) =>\n item.notification.targetLineageId === notification.targetLineageId &&\n coalesceKey(item.notification) === key\n )\n}\n\n/**\n * Admits a notification, coalescing only pending system events that share both\n * a key and a target lineage. Coalescing retains the first sequence so replay\n * order remains stable.\n *\n * A queue already at capacity decides `rejected-full` and retains nothing. The\n * caller owns what happens next: `NotificationQueue.admit` writes no journal\n * entry for that decision, so the same notification is admissible again once a\n * boundary drains.\n *\n * @param state the current queue state\n * @param notification the notification to admit\n * @param seq the journal sequence the admission is recorded at\n * @category operations\n * @since 0.1.0\n */\nexport const admit = (state: State, notification: Notification, seq: number): Admission => {\n const coalesced = coalesceIndex(state, notification)\n if (coalesced !== -1) {\n const existing = state.items[coalesced]!\n const items = [...state.items]\n items[coalesced] = { notification, seq: existing.seq }\n return Object.freeze({ state: immutable(state.capacity, items), decision: \"coalesced\" })\n }\n\n if (state.items.length >= state.capacity) {\n return Object.freeze({ state, decision: \"rejected-full\" })\n }\n\n return Object.freeze({\n state: immutable(state.capacity, [...state.items, { notification, seq }]),\n decision: \"admitted\"\n })\n}\n\n/**\n * Applies the decision already committed in an admission journal event.\n *\n * Replay never re-decides: the committed decision is the one that happened,\n * whatever this process's state would have chosen. The `rejected-full` branch\n * stays reachable for a record written by any other writer, even though this\n * package never writes one.\n *\n * @param state the state so far\n * @param notification the notification the record admitted\n * @param seq the journal sequence the record committed at\n * @param decision the decision the record carries\n * @category operations\n * @since 0.1.0\n */\nexport const applyAdmission = (\n state: State,\n notification: Notification,\n seq: number,\n decision: AdmissionDecision\n): State => {\n if (decision === \"rejected-full\") return state\n if (decision === \"admitted\") {\n return immutable(state.capacity, [...state.items, { notification, seq }])\n }\n const index = coalesceIndex(state, notification)\n // A record whose lineage holds nothing under the key is retained rather than\n // dropped, which is also what keeps a decision recorded before coalescing\n // was lineage-scoped replayable: it applies to the item it named, or to none.\n if (index === -1) return immutable(state.capacity, [...state.items, { notification, seq }])\n const items = [...state.items]\n items[index] = { notification, seq: items[index]!.seq }\n return immutable(state.capacity, items)\n}\n\n/**\n * Returns still-pending notifications in their durable journal order.\n *\n * @param state the current queue state\n * @param admission which admission class to report\n * @param targetLineageId the lineage to report for, or every lineage when absent\n * @category getters\n * @since 0.1.0\n */\nexport const pending = (\n state: State,\n admission: \"steer\" | \"queue\",\n targetLineageId?: string\n): ReadonlyArray<Pending> =>\n Object.freeze(\n state.items.filter((item) =>\n admissionClass(item.notification) === admission &&\n (targetLineageId === undefined || item.notification.targetLineageId === targetLineageId)\n )\n )\n\n/**\n * Promotes every steer notification admitted at or before the turn-close\n * cutoff. Notifications admitted after the cutoff remain pending.\n *\n * The cutoff is what holds a steer that arrived mid-turn until the next\n * boundary, and `NotificationQueue.DrainInput.cutoffSeq` is how a caller sets\n * it. A drain that names no cutoff delivers everything pending for the lineage.\n *\n * @param state the current queue state\n * @param cutoffSeq the highest admission sequence this boundary may deliver\n * @param targetLineageId the lineage the boundary belongs to, or every lineage when absent\n * @category operations\n * @since 0.1.0\n */\nexport const promoteSteers = (state: State, cutoffSeq: number, targetLineageId?: string): Promotion => {\n const promoted: Array<Pending> = []\n const remaining: Array<Pending> = []\n for (const item of state.items) {\n if (\n (admissionClass(item.notification) === \"steer\" || (\n item.notification._tag === \"system-event\" &&\n typeof item.notification.payload === \"object\" && item.notification.payload !== null &&\n !Array.isArray(item.notification.payload) &&\n (item.notification.payload as Readonly<Record<string, unknown>>).kind === \"outside_change\"\n )) &&\n item.seq <= cutoffSeq &&\n (targetLineageId === undefined || item.notification.targetLineageId === targetLineageId)\n ) {\n promoted.push(item)\n } else {\n remaining.push(item)\n }\n }\n return immutablePromotion(immutable(state.capacity, remaining), promoted)\n}\n\n/**\n * Promotes exactly the oldest pending queue notification.\n *\n * @param state the current queue state\n * @param targetLineageId the lineage the boundary belongs to, or every lineage when absent\n * @category operations\n * @since 0.1.0\n */\nexport const promoteQueued = (state: State, targetLineageId?: string): Promotion => {\n const index = state.items.findIndex((item) =>\n admissionClass(item.notification) === \"queue\" &&\n (targetLineageId === undefined || item.notification.targetLineageId === targetLineageId)\n )\n if (index === -1) return immutablePromotion(state, [])\n const promoted = state.items[index]!\n return immutablePromotion(\n immutable(state.capacity, [...state.items.slice(0, index), ...state.items.slice(index + 1)]),\n [promoted]\n )\n}\n\n/**\n * Applies a durable promotion record while replaying journal history.\n *\n * @param state the state so far\n * @param ids the notification ids the record promoted\n * @category operations\n * @since 0.1.0\n */\nexport const applyPromoted = (state: State, ids: ReadonlyArray<string>): State => {\n if (ids.length === 0) return state\n const promoted = new Set(ids)\n return immutable(state.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AY,KAAK,aAAa,YAAY,QAC/E,CAAC,MAAM,QAAQ,KAAK,aAAa,OAAO,KACvC,KAAK,aAAa,QAA8C,SAAS,qBAE5E,KAAK,OAAO,cACX,oBAAoB,UAAa,KAAK,aAAa,oBAAoB,kBACxE;AACA,eAAS,KAAK,IAAI;AAAA,IACpB,OAAO;AACL,gBAAU,KAAK,IAAI;AAAA,IACrB;AAAA,EACF;AACA,SAAO,mBAAmB,UAAU,MAAM,UAAU,SAAS,GAAG,QAAQ;AAC1E;AAUO,MAAM,gBAAgB,CAAC,OAAc,oBAAwC;AAClF,QAAM,QAAQ,MAAM,MAAM;AAAA,IAAU,CAAC,aACnC,oCAAe,KAAK,YAAY,MAAM,YACrC,oBAAoB,UAAa,KAAK,aAAa,oBAAoB;AAAA,EAC1E;AACA,MAAI,UAAU,GAAI,QAAO,mBAAmB,OAAO,CAAC,CAAC;AACrD,QAAM,WAAW,MAAM,MAAM,KAAK;AAClC,SAAO;AAAA,IACL,UAAU,MAAM,UAAU,CAAC,GAAG,MAAM,MAAM,MAAM,GAAG,KAAK,GAAG,GAAG,MAAM,MAAM,MAAM,QAAQ,CAAC,CAAC,CAAC;AAAA,IAC3F,CAAC,QAAQ;AAAA,EACX;AACF;AAUO,MAAM,gBAAgB,CAAC,OAAc,QAAsC;AAChF,MAAI,IAAI,WAAW,EAAG,QAAO;AAC7B,QAAM,WAAW,IAAI,IAAI,GAAG;AAC5B,SAAO,UAAU,MAAM,UAAU,MAAM,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,IAAI,KAAK,aAAa,EAAE,CAAC,CAAC;AACpG;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Journal projection for pending notifications.
|
|
3
|
+
*
|
|
4
|
+
* @since 0.1.0
|
|
5
|
+
*/
|
|
6
|
+
import { Projection as JournalProjection } from "@smthrs/journal";
|
|
7
|
+
import * as NotificationState from "./NotificationState.ts";
|
|
8
|
+
/**
|
|
9
|
+
* Re-derives pending notifications from admitted and promoted journal events.
|
|
10
|
+
* Foreign journal entries leave the state unchanged.
|
|
11
|
+
*
|
|
12
|
+
* Replay never re-decides, so capacity does not truncate it:
|
|
13
|
+
* `NotificationState.applyAdmission` applies the decision each record already
|
|
14
|
+
* committed, and an admitted record is retained however many are pending. A
|
|
15
|
+
* composition built with `NotificationQueue.layerWith` above the default
|
|
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.
|
|
20
|
+
*
|
|
21
|
+
* The projected `capacity` is `NotificationState.defaultCapacity` because the
|
|
22
|
+
* initial state has to start somewhere and no journal record carries the bound
|
|
23
|
+
* the layer was built at. Read `items`, not `capacity`, to learn what a run
|
|
24
|
+
* holds.
|
|
25
|
+
*
|
|
26
|
+
* @category projections
|
|
27
|
+
* @since 0.1.0
|
|
28
|
+
*/
|
|
29
|
+
export declare const derive: JournalProjection.Projection<NotificationState.State, never, never>;
|
|
30
|
+
//# sourceMappingURL=Projection.d.ts.map
|
|
@@ -0,0 +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;AAKjE,OAAO,KAAK,iBAAiB,MAAM,wBAAwB,CAAA;AAE3D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,MAAM,qEAajB,CAAA"}
|
|
@@ -0,0 +1,53 @@
|
|
|
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 Projection_exports = {};
|
|
30
|
+
__export(Projection_exports, {
|
|
31
|
+
derive: () => derive
|
|
32
|
+
});
|
|
33
|
+
module.exports = __toCommonJS(Projection_exports);
|
|
34
|
+
var import_journal = require("@smthrs/journal");
|
|
35
|
+
var Effect = __toESM(require("effect/Effect"), 1);
|
|
36
|
+
var Option = __toESM(require("effect/Option"), 1);
|
|
37
|
+
var Replay = __toESM(require("./internal/replay.js"), 1);
|
|
38
|
+
var NotificationEvent = __toESM(require("./NotificationEvent.js"), 1);
|
|
39
|
+
var NotificationState = __toESM(require("./NotificationState.js"), 1);
|
|
40
|
+
const derive = import_journal.Projection.make({
|
|
41
|
+
name: "flows/notifications",
|
|
42
|
+
initial: NotificationState.empty(NotificationState.defaultCapacity),
|
|
43
|
+
reduce: (state, entry) => {
|
|
44
|
+
const decoded = NotificationEvent.fromEntry(entry);
|
|
45
|
+
if (Option.isNone(decoded)) return Effect.succeed(state);
|
|
46
|
+
const event = decoded.value;
|
|
47
|
+
if (NotificationEvent.isAdmitted(event)) {
|
|
48
|
+
return Effect.succeed(Replay.applyAdmitted(state, event, entry.seq));
|
|
49
|
+
}
|
|
50
|
+
return Effect.succeed(NotificationState.applyPromoted(state, event.ids));
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
//# sourceMappingURL=Projection.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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 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
|
+
"names": ["JournalProjection"]
|
|
7
|
+
}
|