@ping-app/ping-openmls-sdk 0.10.5 → 0.10.7

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/dist/index.js CHANGED
@@ -90,9 +90,10 @@ var GapFiller = class {
90
90
  // src/inbound-coalescer.ts
91
91
  var InboundCoalescer = class {
92
92
  /**
93
- * @param apply Applies one batch. A rejection settles the promises of the
94
- * frames in that batch with the error and the lane moves on to whatever
95
- * queued meanwhile, so one bad batch cannot wedge a conversation.
93
+ * @param apply Applies one batch. A rejection of a batch that carries
94
+ * several conversations hands it again one conversation at a time; the
95
+ * frames of a conversation whose own batch is rejected settle with the
96
+ * error and the lane moves on, so one bad batch cannot wedge it.
96
97
  * @param maxBatch Upper bound on frames per batch. A burst larger than
97
98
  * this goes out as consecutive batches of at most `maxBatch`, so a
98
99
  * flood cannot turn into one unbounded wasm call.
@@ -103,57 +104,98 @@ var InboundCoalescer = class {
103
104
  }
104
105
  apply;
105
106
  maxBatch;
106
- lanes = /* @__PURE__ */ new Map();
107
- /**
108
- * Queue a frame. Resolves when the batch that carried it has been applied
109
- * (rejects if that batch failed), so a transport that awaits the dispatch
110
- * to ack a watermark still sees the truth.
107
+ queue = [];
108
+ running = false;
109
+ /** The last batch left rows for want of room and no confirm came since. */
110
+ waitingForRoom = false;
111
+ /** Confirms seen, so that one landing while a batch is in flight is not lost. */
112
+ confirms = 0;
113
+ /**
114
+ * Queue a frame of the conversation `key`. Resolves when the batch that
115
+ * carried it has been applied (rejects if that batch failed), so a
116
+ * transport that awaits the dispatch to ack a watermark still sees the
117
+ * truth: a frame the engine did not take stays pending until it is.
111
118
  */
112
119
  push(key, item) {
113
- const lane = this.lanes.get(key);
114
- if (lane !== void 0) {
115
- return new Promise((resolve, reject) => {
116
- lane.queued.push(item);
117
- lane.waiters.push({ resolve, reject });
118
- });
120
+ return new Promise((resolve, reject) => {
121
+ this.queue.push({ key, item, resolve, reject });
122
+ this.pump();
123
+ });
124
+ }
125
+ /**
126
+ * The host confirmed messages (`confirmApplied` returned): the journal has
127
+ * room again, and the frames kept for want of it are handed now.
128
+ */
129
+ roomFreed() {
130
+ this.confirms += 1;
131
+ if (this.waitingForRoom) {
132
+ this.waitingForRoom = false;
133
+ this.pump();
119
134
  }
120
- const fresh = { queued: [], waiters: [] };
121
- this.lanes.set(key, fresh);
122
- return this.run(key, fresh, [item], []);
123
135
  }
124
- /** Conversations with a batch in flight (diagnostics / tests). */
136
+ /** Batches in flight: 0 or 1 (diagnostics / tests). */
125
137
  get inFlight() {
126
- return this.lanes.size;
138
+ return this.running ? 1 : 0;
127
139
  }
128
- run(key, lane, items, waiters) {
129
- let attempt;
140
+ /** Frames waiting in the lane (diagnostics / tests). */
141
+ get queued() {
142
+ return this.queue.length;
143
+ }
144
+ pump() {
145
+ if (this.running || this.waitingForRoom || this.queue.length === 0) return;
146
+ this.running = true;
147
+ const batch = this.queue.splice(0, this.maxBatch);
148
+ void this.run(batch).then(() => {
149
+ this.running = false;
150
+ this.pump();
151
+ });
152
+ }
153
+ async run(batch) {
154
+ const confirmsAtHand = this.confirms;
155
+ let left = [];
130
156
  try {
131
- attempt = this.apply(key, items);
157
+ left = await this.hand(batch);
132
158
  } catch (e) {
133
- attempt = Promise.reject(e);
134
- }
135
- attempt.then(
136
- () => {
137
- for (const w of waiters) w.resolve();
138
- },
139
- (e) => {
140
- for (const w of waiters) w.reject(e);
159
+ const groups = /* @__PURE__ */ new Map();
160
+ for (const entry of batch) {
161
+ const group = groups.get(entry.key);
162
+ if (group === void 0) groups.set(entry.key, [entry]);
163
+ else group.push(entry);
141
164
  }
142
- );
143
- void attempt.then(
144
- () => this.drain(key, lane),
145
- () => this.drain(key, lane)
146
- );
147
- return attempt;
165
+ if (groups.size <= 1) {
166
+ for (const entry of batch) entry.reject(e);
167
+ return;
168
+ }
169
+ for (const group of groups.values()) {
170
+ try {
171
+ left.push(...await this.hand(group));
172
+ } catch (error) {
173
+ for (const entry of group) entry.reject(error);
174
+ }
175
+ }
176
+ const order = new Map(batch.map((entry, index) => [entry, index]));
177
+ left.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
178
+ }
179
+ if (left.length > 0) {
180
+ this.queue.unshift(...left);
181
+ this.waitingForRoom = this.confirms === confirmsAtHand;
182
+ }
148
183
  }
149
- drain(key, lane) {
150
- if (lane.queued.length === 0) {
151
- if (this.lanes.get(key) === lane) this.lanes.delete(key);
152
- return;
184
+ /** Hand `entries`; settle the taken ones; return the ones not taken, in order. */
185
+ async hand(entries) {
186
+ let attempt;
187
+ try {
188
+ attempt = this.apply(entries.map((entry) => entry.item));
189
+ } catch (e) {
190
+ attempt = Promise.reject(e);
153
191
  }
154
- const items = lane.queued.splice(0, this.maxBatch);
155
- const waiters = lane.waiters.splice(0, items.length);
156
- void this.run(key, lane, items, waiters).catch(() => void 0);
192
+ const notTaken = new Set(await attempt ?? []);
193
+ const back = [];
194
+ entries.forEach((entry, index) => {
195
+ if (notTaken.has(index)) back.push(entry);
196
+ else entry.resolve();
197
+ });
198
+ return back;
157
199
  }
158
200
  };
159
201
 
@@ -287,7 +329,11 @@ function outcomesFromWire(r) {
287
329
  holes: (r.holes ?? []).map(logHoleFromWire),
288
330
  acks: (r.acks ?? []).map(logAckFromWire),
289
331
  // Absent from an older wasm, which never stopped for the journal.
290
- journalFull: (r.journal_full ?? []).map(journalFullAtFromWire)
332
+ journalFull: (r.journal_full ?? []).map(journalFullAtFromWire),
333
+ // Absent from an older wasm, which did not state its room: 0, so a host
334
+ // that cuts its hand by the room waits for a confirm instead of guessing.
335
+ journalRoomRows: Number(r.journal_room_rows ?? 0),
336
+ journalRoomBytes: Number(r.journal_room_bytes ?? 0)
291
337
  };
292
338
  }
293
339
  function applyBatchResultFromWire(r) {
@@ -301,6 +347,8 @@ function applyBatchResultFromWire(r) {
301
347
  joined: r.joined,
302
348
  updated: r.updated.map(conversationUpdateFromWire),
303
349
  ...outcomesFromWire(r),
350
+ // Absent from an older wasm, which named no row: nothing to hand again.
351
+ notTaken: (r.not_taken ?? []).map(Number),
304
352
  // Present only when the SDK says it: said once, with the batch at which
305
353
  // the anchor record was seen to change.
306
354
  ...r.state_backup_owed === true ? { stateBackupOwed: true } : {}
@@ -690,6 +738,50 @@ var AccountSetup = class _AccountSetup {
690
738
  storageFeatures: storageFeaturesOf(this.storage)
691
739
  });
692
740
  }
741
+ /**
742
+ * THE PREPARED DEVICE KEY (rulings V895 to V900, V913, V965): the device key
743
+ * a sign-in BY CODE names on a store with no device record, before the
744
+ * account exists. The SDK draws it (no argument is a key), keeps it in one
745
+ * row of this store and answers it; a repeat answers the SAME key, and two
746
+ * tabs that call at once answer one key (the origin's account lock).
747
+ * `createAccount`, the in-memory session and `MessagingClient.beginDeviceLink`
748
+ * then make the device with that key; a restore or a take-back never uses
749
+ * it. Store the secret BEFORE any request names the key. Refusals:
750
+ * `account-already-set-up` (the store holds a device), `rotation-in-progress`,
751
+ * `device-key-held-by-link` (a link was begun in this slot: offer "Finish
752
+ * linking" or "Start over", never a retry), `prepared-key-mismatch`.
753
+ */
754
+ prepareDeviceKey() {
755
+ return this.call({
756
+ kind: "prepareDeviceKey",
757
+ id: this.nextId++,
758
+ nowMs: this.now(),
759
+ storageFeatures: storageFeaturesOf(this.storage)
760
+ });
761
+ }
762
+ /** Delete a FREE prepared device key and nothing else; answers whether a
763
+ * row was deleted. Log the key's session out FIRST, and delete the host's
764
+ * own copy of the secret last. Refuses as `prepareDeviceKey` does. */
765
+ discardPreparedDeviceKey() {
766
+ return this.call({
767
+ kind: "discardPreparedDeviceKey",
768
+ id: this.nextId++,
769
+ storageFeatures: storageFeaturesOf(this.storage)
770
+ });
771
+ }
772
+ /** THE PREDICATE (ruling V904): what a start from the device record would
773
+ * answer on this store, as a typed value. It starts nothing, writes
774
+ * nothing and sends nothing. `expectedDeviceId` is the PUBLIC device id
775
+ * the host keeps, if it keeps one. Decide stop or retry on the answer,
776
+ * never on the words of an error. */
777
+ deviceStartCheck(expectedDeviceId) {
778
+ return this.call({
779
+ kind: "deviceStartCheck",
780
+ id: this.nextId++,
781
+ expectedDeviceId,
782
+ storageFeatures: storageFeaturesOf(this.storage)
783
+ });
784
+ }
693
785
  /** Whether the slot holds the pending root this device expects (rule R32).
694
786
  * No prompt, no read of the seed. */
695
787
  pendingStatus(slot) {
@@ -736,6 +828,21 @@ var AccountSetup = class _AccountSetup {
736
828
  storageFeatures: storageFeaturesOf(this.storage)
737
829
  });
738
830
  }
831
+ /** "Start over" on an account that was started on this device and never
832
+ * finished (rulings V1201, V1277): deletes the pending root of ONE slot and
833
+ * nothing else, or refuses with a typed answer (see `PendingRootDiscard`).
834
+ * THE HOST'S DUTY, which the SDK cannot check: the person chose it, the
835
+ * slot's stored account is the account signed in now, this sign-in's fresh
836
+ * answer is exactly `none_pinned`, and the slot's SDK store is emptied in
837
+ * the same erase. Never call it from a sweep. */
838
+ discardPendingRoot(slot) {
839
+ return this.call({
840
+ kind: "discardPendingRoot",
841
+ id: this.nextId++,
842
+ slot,
843
+ storageFeatures: storageFeaturesOf(this.storage)
844
+ });
845
+ }
739
846
  // ---- The restore as a rotation (the account identity contract, sections
740
847
  // 3.9, 3.13, 13.1). None of these needs a client or a session: the backup
741
848
  // is opened and the whole `rotation` object is built before the device
@@ -925,14 +1032,18 @@ var AccountSetup = class _AccountSetup {
925
1032
  * Begin a set-up session whose root is in memory only (rule R34 a): for the
926
1033
  * person who makes the backup during set-up. One session per object; it
927
1034
  * lives in the Worker until `sessionFinish`, `sessionKeepAsPending` or
928
- * `close`.
1035
+ * `close`. It begins ON THIS STORE (read, nothing written): the session's
1036
+ * device is made for the store's free prepared device key, when
1037
+ * `prepareDeviceKey` made one. `device-key-held-by-link`: a link was begun
1038
+ * in this slot.
929
1039
  */
930
1040
  async beginInMemory(identityState) {
931
1041
  await this.call({
932
1042
  kind: "beginAccountSetupInMemory",
933
1043
  id: this.nextId++,
934
1044
  identityState,
935
- nowMs: this.now()
1045
+ nowMs: this.now(),
1046
+ storageFeatures: storageFeaturesOf(this.storage)
936
1047
  });
937
1048
  }
938
1049
  /** The session's backup. */
@@ -1175,13 +1286,15 @@ var MessagingClient = class _MessagingClient {
1175
1286
  */
1176
1287
  metaCache = /* @__PURE__ */ new Map();
1177
1288
  /**
1178
- * Per-conversation batching of sequenced live frames: the first frame goes
1179
- * to the worker at once, frames that arrive while that batch is in flight
1180
- * go out as ONE `processSequencedBatch` when it returns. See
1289
+ * ONE lane of sequenced live frames for every conversation: the first
1290
+ * frame goes to the worker at once, frames that arrive while that batch is
1291
+ * in flight go out as ONE `processSequencedBatch` when it returns, in
1292
+ * arrival order. Rows the engine did not take (`notTaken`) stay in the
1293
+ * lane and are handed again after the next `confirmApplied`. See
1181
1294
  * {@link dispatchIncoming}.
1182
1295
  */
1183
1296
  coalescer = new InboundCoalescer(
1184
- (_key, items) => this.applyLiveBatch(items)
1297
+ (items) => this.applyLiveBatch(items)
1185
1298
  );
1186
1299
  /** Single-flight gap fills, one `syncConversationStep` loop per conversation. */
1187
1300
  gapFiller = new GapFiller();
@@ -1790,10 +1903,14 @@ var MessagingClient = class _MessagingClient {
1790
1903
  * position, holds it ahead of a hole and drops it at or below what was
1791
1904
  * applied, whatever order it arrived in. What it needs is BATCHING: one
1792
1905
  * MLS checkpoint and one host transaction per burst instead of one per
1793
- * frame. So the first frame for a conversation goes to the worker at once
1794
- * as a batch of one, and frames that arrive while that batch is in flight
1795
- * accumulate and go out as ONE `processSequencedBatch` when it returns; no
1796
- * timer ever delays a frame. Own-device echoes are NOT dropped on this
1906
+ * frame. So the first frame goes to the worker at once as a batch of one,
1907
+ * and frames of ANY conversation that arrive while that batch is in flight
1908
+ * accumulate and go out as ONE `processSequencedBatch` when it returns, in
1909
+ * arrival order (one lane for all conversations: a catch-up of 200
1910
+ * conversations is about 20 Worker calls, not 400); no timer ever delays a
1911
+ * frame. Rows the engine did not take because the pending-apply journal
1912
+ * had no room (`notTaken`) stay in the lane, in order, and are handed
1913
+ * again after the next `confirmApplied`. Own-device echoes are NOT dropped on this
1797
1914
  * path: the core advances the position past them without touching MLS,
1798
1915
  * and dropping one would leave a hole the next frame reports as a gap. A
1799
1916
  * sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and
@@ -1802,7 +1919,9 @@ var MessagingClient = class _MessagingClient {
1802
1919
  dispatchIncoming(frame) {
1803
1920
  if (isSequencedFrame(frame)) {
1804
1921
  if (frame.serverSeq > 0) {
1805
- return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame);
1922
+ return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame).catch((e) => {
1923
+ if (typeof console !== "undefined") console.debug("[ping-sdk] sequenced batch failed:", errorKind(e));
1924
+ });
1806
1925
  }
1807
1926
  return this.dispatchLegacy(frame.envelope);
1808
1927
  }
@@ -1846,17 +1965,16 @@ var MessagingClient = class _MessagingClient {
1846
1965
  }
1847
1966
  }
1848
1967
  /**
1849
- * One coalesced batch of live frames. Errors are logged at debug and
1850
- * swallowed, exactly as the legacy path treats a failed envelope: the
1851
- * dispatch promise a transport may await resolves either way, and the
1852
- * core retains anything it could not apply yet.
1968
+ * One coalesced batch of live frames, of any number of conversations.
1969
+ * Answers the indexes of the rows the engine did not take (the journal
1970
+ * had no room): the lane keeps those and hands them again after the next
1971
+ * `confirmApplied`. A rejection goes to the lane, which hands a refused
1972
+ * batch again one conversation at a time; `dispatchIncoming` logs what
1973
+ * still fails at debug and resolves.
1853
1974
  */
1854
1975
  async applyLiveBatch(items) {
1855
- try {
1856
- await this.processSequencedBatch(items);
1857
- } catch (e) {
1858
- if (typeof console !== "undefined") console.debug("[ping-sdk] sequenced batch failed:", errorKind(e));
1859
- }
1976
+ const result = await this.processSequencedBatch(items);
1977
+ return result.notTaken;
1860
1978
  }
1861
1979
  /** Start a fill for every gap a batch reported; each is single-flight. */
1862
1980
  scheduleGapFills(result) {
@@ -2252,6 +2370,14 @@ var MessagingClient = class _MessagingClient {
2252
2370
  * an interactive call behind all of them. Resolves when every conversation
2253
2371
  * held at the start of the pass (plus any joined while it ran) has been
2254
2372
  * paged, with the decrypted application messages in apply order.
2373
+ *
2374
+ * Rejects with `StoreMovedError` when the client failed closed: before the
2375
+ * pass (it then asks nothing of the server), inside one of its steps (no
2376
+ * later conversation is asked; the pages before it were delivered), or
2377
+ * during its last step. A client that failed closed before or during the
2378
+ * pass never resolves at all, with an empty list or with any other. The
2379
+ * host drops the client and starts a new one on the same store, which
2380
+ * hands what was stored (`pendingApplies`).
2255
2381
  */
2256
2382
  async syncConversations() {
2257
2383
  return await this.call({
@@ -2562,6 +2688,7 @@ var MessagingClient = class _MessagingClient {
2562
2688
  async confirmApplied(journalIds) {
2563
2689
  if (journalIds.length === 0) return;
2564
2690
  await this.call({ kind: "confirmApplied", id: this.nextId++, journalIds });
2691
+ this.coalescer.roomFreed();
2565
2692
  }
2566
2693
  /**
2567
2694
  * The version 3 handshake payload this NEW device publishes: its own signing key,