unified-notification-core 0.1.0 → 0.1.2

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.
@@ -25,10 +25,42 @@ selected but opted out -> skipped
25
25
  Publishing and creating delivery rows occurs in one database transaction.
26
26
  Provider callbacks never run inside that transaction.
27
27
 
28
+ Publication first validates all runtime inputs, then loads preferences in a
29
+ fixed query wave and bulk-inserts/selects notifications and deliveries. Query
30
+ count does not grow with recipient or channel count. Per-recipient idempotency,
31
+ first-seen recipient order, and unique channel order are preserved.
32
+
33
+ Every public/configuration wrapper and channel-keyed record must be a plain or
34
+ null-prototype object. The boundary reads own keys and data descriptors once,
35
+ rejects accessors/symbols/unsupported properties, and operates only on an
36
+ immutable snapshot afterward. Public arrays are likewise descriptor-copied
37
+ without invoking caller methods, but only when they use `Array.prototype`
38
+ directly and contain canonical in-range indices with no extra properties.
39
+ Database and schema objects remain opaque Drizzle-owned values. This prevents
40
+ getter/proxy TOCTOU changes between validation, persistence predicates, and
41
+ writes.
42
+
43
+ Applications may construct a core with a Drizzle `PgTransaction` to make
44
+ `publish()` part of a larger application transaction. Such a core is
45
+ publish-only: `publishAndDispatch()` and `dispatchDue()` fail before publishing,
46
+ claiming, or invoking an adapter. Dispatch starts after the outer commit through
47
+ a core constructed with the top-level `PgDatabase`. The runtime guard uses
48
+ Drizzle's public `PgTransaction` entity identity because `PgTransaction`
49
+ inherits the `PgDatabase` TypeScript contract and cannot be excluded from that
50
+ configuration type structurally.
51
+
28
52
  `dispatchDue()` claims a bounded set of due rows in a transaction using
29
- `FOR UPDATE SKIP LOCKED`, changes them to `processing`, commits, and only then
30
- invokes adapters. The `lockedBy` token prevents a late worker from overwriting a
31
- row reclaimed after its lock expired.
53
+ `FOR UPDATE SKIP LOCKED`, increments each row's durable attempt count, changes
54
+ it to `processing`, commits, and only then invokes adapters. Every row and
55
+ attempt receives a unique `lockedBy` claim token. The diagnostic `workerId` is
56
+ only a token prefix; it is never the compare-and-set identity by itself. A late
57
+ worker therefore cannot overwrite a row reclaimed after its lock expired.
58
+
59
+ Finalization checks the claim token and reads back the written row. If the token
60
+ is stale, `DispatchResult` reflects the current durable row instead of the
61
+ callback's local assumption. Cancellation retains the current processing token:
62
+ late provider success for that claim becomes durable `sent`, while late failure
63
+ remains durable `canceled` without a retry.
32
64
 
33
65
  ## In-app as a channel
34
66
 
@@ -49,6 +81,24 @@ Preference checks occur at publication time. The resolved choice is captured in
49
81
  the delivery row as `pending` or `skipped`, so changing a preference later does
50
82
  not rewrite historical notifications.
51
83
 
84
+ All public preference boundaries canonicalize recipient, topic, and channel
85
+ keys by trimming whitespace and rejecting empty values. Application defaults
86
+ are canonicalized once during core construction; canonical key collisions are
87
+ configuration errors.
88
+
89
+ Preference reads canonicalize legacy `0.1.0` rows at query/resolution time, so
90
+ no data rewrite is required before upgrading. Conflicting rows resolve
91
+ deterministically with opt-out winning. Registry-style channel maps use own-key,
92
+ null-prototype storage to prevent JavaScript prototype properties from becoming
93
+ implicit adapters, defaults, attempt limits, or channel payloads.
94
+
95
+ The SQL canonical expression uses the complete ECMAScript `String.trim()`
96
+ WhiteSpace and LineTerminator set and is shared by read predicates and the
97
+ functional recipient index. Publication performs one exact recipient lookup and
98
+ at most one indexed legacy fallback lookup for the entire batch. Existing
99
+ `0.1.0` databases need a normal application-owned schema migration to add this
100
+ performance index; UNC never auto-migrates at runtime.
101
+
52
102
  ## Provider boundary
53
103
 
54
104
  Adapters receive:
@@ -64,6 +114,18 @@ The application resolves current contact information and credentials. That
64
114
  keeps personally identifiable addresses out of UNC tables and prevents
65
115
  stale addresses from being baked into scheduled notifications.
66
116
 
117
+ The adapter invocation is the only provider exception boundary. Once it
118
+ resolves, UNC validates optional output separately from durable success
119
+ finalization. Invalid `providerMessageId` or metadata is discarded and recorded
120
+ as `invalid_adapter_result` on a `sent` delivery; it is never reclassified as a
121
+ provider failure or retried. Diagnostic extraction is non-coercing and capped
122
+ at 10,000 characters consistently across storage, logs, and dispatch results.
123
+ NUL and unpaired UTF-16 surrogates are invalid in every persisted string and
124
+ JSON key/value; valid surrogate pairs are preserved. Adapter-output violations
125
+ use the same sent-safe diagnostic path. The claim timestamp is captured before
126
+ provider invocation and is reused for terminal persistence, so application
127
+ clock failures cannot occur after provider acceptance.
128
+
67
129
  ## Delivery semantics
68
130
 
69
131
  UNC provides at-least-once callback invocation. A process can exit
@@ -71,5 +133,66 @@ after a provider accepts a request but before the delivery row is marked sent.
71
133
  Applications should pass `deliveryId` as a provider idempotency key whenever the
72
134
  provider supports it.
73
135
 
136
+ Attempts are counted at claim time, so a crash does not reuse an attempt number
137
+ or bypass `maxAttempts`. Once an abandoned claim has consumed the last allowed
138
+ attempt, the next reconciliation closes it as `failed` without invoking the
139
+ adapter again.
140
+
141
+ Application retry-delay policy is isolated from claim finalization. Synchronous
142
+ return values and exact native Promises are accepted inside a deadline installed
143
+ before policy invocation and measured with a trusted monotonic clock for a fixed
144
+ maximum of 100 ms. Blocking synchronous policy work is checked after it returns
145
+ and cannot submit a late value. A throw, rejection, timeout, or runtime-invalid
146
+ delay falls back to the deterministic schedule. Late native Promise rejections
147
+ are consumed. Observability callbacks are isolated from durable state; returned
148
+ native logger Promises are observed immediately but not awaited. The logger
149
+ callback itself remains synchronous application code and must return promptly.
150
+
151
+ All retry-isolation intrinsics are captured and bound during module
152
+ initialization: the monotonic clock, timers, native Promise constructor,
153
+ prototype and `then`, the Node Promise brand check, and required Object/Reflect
154
+ inspection functions. Native deadline settlement exists before policy
155
+ invocation. An accepted Promise receives its rejection handler before the
156
+ post-callback lateness check. Its actual fulfillment/rejection callback checks
157
+ the captured monotonic clock before settling the deadline, preventing a starved
158
+ deadline timer from admitting a result after 100 ms. The boundary never calls
159
+ mutable public `Promise.race`.
160
+
161
+ The async boundary accepts only numbers plus exact same-realm native Node
162
+ Promises. A hook-free Node brand check runs before exact captured-prototype and
163
+ intrinsic descriptor checks. UNC then invokes only the captured native
164
+ `Promise.prototype.then`; it never gets or calls a caller-controlled `then`.
165
+ Promise subclasses, cross-realm Promises, custom `PromiseLike` objects, and
166
+ native Promises with own `then`/`constructor` hooks are invalid. Invalid retry
167
+ results use fallback, while invalid logger results are ignored without traversal.
168
+
169
+ `maxAttempts` is one shared positive PostgreSQL `integer` contract across core
170
+ defaults, scalar/per-channel publication, and requeue: 1 through 2,147,483,647.
171
+ Validation happens before mutation or claim, and claim predicates explicitly
172
+ guard the upper attempts boundary.
173
+
174
+ `NotificationDeliveryError` similarly descriptor-captures a plain or
175
+ null-prototype options record once. A present `retryable` field must be boolean;
176
+ only omission means `true`. Its code and message are bounded PostgreSQL-safe
177
+ persisted strings before the error can reach delivery finalization.
178
+
179
+ ## Runtime JSON contract
180
+
181
+ Every public payload value is recursively checked before a transaction. JSON
182
+ numbers must be finite; cycles, sparse/undefined members, unsupported primitive
183
+ types, accessors, symbol keys, and non-plain object instances are rejected.
184
+ Adapter metadata follows the same contract, but validation happens after the
185
+ provider resolves and therefore uses the sent-safe diagnostic behavior above.
186
+
187
+ The implementation uses an explicit stack with a maximum depth of 256 and a
188
+ maximum of 10,000 nodes per value. It inspects own keys and descriptors, treats
189
+ array `length` specially, requires the exact `Array.prototype`, accepts only
190
+ canonical indices from zero through `2^32 - 2` below the captured length,
191
+ rejects every other property, and
192
+ builds a descriptor-owned copy so later persistence cannot invoke source
193
+ getters or Proxy `get` traps. Child-node capacity is reserved immediately after
194
+ `ownKeys`, before any child descriptor is inspected, so oversized objects cannot
195
+ force work beyond the global node budget.
196
+
74
197
  Exactly-once delivery cannot be guaranteed across a database and an external
75
198
  provider without provider-side idempotency or a distributed transaction.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unified-notification-core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "UNC is a Drizzle-native multichannel notification core with durable delivery, retries, in-app inboxes, and recipient preferences.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",