@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.cjs CHANGED
@@ -193,9 +193,10 @@ var GapFiller = class {
193
193
  // src/inbound-coalescer.ts
194
194
  var InboundCoalescer = class {
195
195
  /**
196
- * @param apply Applies one batch. A rejection settles the promises of the
197
- * frames in that batch with the error and the lane moves on to whatever
198
- * queued meanwhile, so one bad batch cannot wedge a conversation.
196
+ * @param apply Applies one batch. A rejection of a batch that carries
197
+ * several conversations hands it again one conversation at a time; the
198
+ * frames of a conversation whose own batch is rejected settle with the
199
+ * error and the lane moves on, so one bad batch cannot wedge it.
199
200
  * @param maxBatch Upper bound on frames per batch. A burst larger than
200
201
  * this goes out as consecutive batches of at most `maxBatch`, so a
201
202
  * flood cannot turn into one unbounded wasm call.
@@ -206,57 +207,98 @@ var InboundCoalescer = class {
206
207
  }
207
208
  apply;
208
209
  maxBatch;
209
- lanes = /* @__PURE__ */ new Map();
210
- /**
211
- * Queue a frame. Resolves when the batch that carried it has been applied
212
- * (rejects if that batch failed), so a transport that awaits the dispatch
213
- * to ack a watermark still sees the truth.
210
+ queue = [];
211
+ running = false;
212
+ /** The last batch left rows for want of room and no confirm came since. */
213
+ waitingForRoom = false;
214
+ /** Confirms seen, so that one landing while a batch is in flight is not lost. */
215
+ confirms = 0;
216
+ /**
217
+ * Queue a frame of the conversation `key`. Resolves when the batch that
218
+ * carried it has been applied (rejects if that batch failed), so a
219
+ * transport that awaits the dispatch to ack a watermark still sees the
220
+ * truth: a frame the engine did not take stays pending until it is.
214
221
  */
215
222
  push(key, item) {
216
- const lane = this.lanes.get(key);
217
- if (lane !== void 0) {
218
- return new Promise((resolve, reject) => {
219
- lane.queued.push(item);
220
- lane.waiters.push({ resolve, reject });
221
- });
223
+ return new Promise((resolve, reject) => {
224
+ this.queue.push({ key, item, resolve, reject });
225
+ this.pump();
226
+ });
227
+ }
228
+ /**
229
+ * The host confirmed messages (`confirmApplied` returned): the journal has
230
+ * room again, and the frames kept for want of it are handed now.
231
+ */
232
+ roomFreed() {
233
+ this.confirms += 1;
234
+ if (this.waitingForRoom) {
235
+ this.waitingForRoom = false;
236
+ this.pump();
222
237
  }
223
- const fresh = { queued: [], waiters: [] };
224
- this.lanes.set(key, fresh);
225
- return this.run(key, fresh, [item], []);
226
238
  }
227
- /** Conversations with a batch in flight (diagnostics / tests). */
239
+ /** Batches in flight: 0 or 1 (diagnostics / tests). */
228
240
  get inFlight() {
229
- return this.lanes.size;
241
+ return this.running ? 1 : 0;
230
242
  }
231
- run(key, lane, items, waiters) {
232
- let attempt;
243
+ /** Frames waiting in the lane (diagnostics / tests). */
244
+ get queued() {
245
+ return this.queue.length;
246
+ }
247
+ pump() {
248
+ if (this.running || this.waitingForRoom || this.queue.length === 0) return;
249
+ this.running = true;
250
+ const batch = this.queue.splice(0, this.maxBatch);
251
+ void this.run(batch).then(() => {
252
+ this.running = false;
253
+ this.pump();
254
+ });
255
+ }
256
+ async run(batch) {
257
+ const confirmsAtHand = this.confirms;
258
+ let left = [];
233
259
  try {
234
- attempt = this.apply(key, items);
260
+ left = await this.hand(batch);
235
261
  } catch (e) {
236
- attempt = Promise.reject(e);
237
- }
238
- attempt.then(
239
- () => {
240
- for (const w of waiters) w.resolve();
241
- },
242
- (e) => {
243
- for (const w of waiters) w.reject(e);
262
+ const groups = /* @__PURE__ */ new Map();
263
+ for (const entry of batch) {
264
+ const group = groups.get(entry.key);
265
+ if (group === void 0) groups.set(entry.key, [entry]);
266
+ else group.push(entry);
244
267
  }
245
- );
246
- void attempt.then(
247
- () => this.drain(key, lane),
248
- () => this.drain(key, lane)
249
- );
250
- return attempt;
268
+ if (groups.size <= 1) {
269
+ for (const entry of batch) entry.reject(e);
270
+ return;
271
+ }
272
+ for (const group of groups.values()) {
273
+ try {
274
+ left.push(...await this.hand(group));
275
+ } catch (error) {
276
+ for (const entry of group) entry.reject(error);
277
+ }
278
+ }
279
+ const order = new Map(batch.map((entry, index) => [entry, index]));
280
+ left.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
281
+ }
282
+ if (left.length > 0) {
283
+ this.queue.unshift(...left);
284
+ this.waitingForRoom = this.confirms === confirmsAtHand;
285
+ }
251
286
  }
252
- drain(key, lane) {
253
- if (lane.queued.length === 0) {
254
- if (this.lanes.get(key) === lane) this.lanes.delete(key);
255
- return;
287
+ /** Hand `entries`; settle the taken ones; return the ones not taken, in order. */
288
+ async hand(entries) {
289
+ let attempt;
290
+ try {
291
+ attempt = this.apply(entries.map((entry) => entry.item));
292
+ } catch (e) {
293
+ attempt = Promise.reject(e);
256
294
  }
257
- const items = lane.queued.splice(0, this.maxBatch);
258
- const waiters = lane.waiters.splice(0, items.length);
259
- void this.run(key, lane, items, waiters).catch(() => void 0);
295
+ const notTaken = new Set(await attempt ?? []);
296
+ const back = [];
297
+ entries.forEach((entry, index) => {
298
+ if (notTaken.has(index)) back.push(entry);
299
+ else entry.resolve();
300
+ });
301
+ return back;
260
302
  }
261
303
  };
262
304
 
@@ -390,7 +432,11 @@ function outcomesFromWire(r) {
390
432
  holes: (r.holes ?? []).map(logHoleFromWire),
391
433
  acks: (r.acks ?? []).map(logAckFromWire),
392
434
  // Absent from an older wasm, which never stopped for the journal.
393
- journalFull: (r.journal_full ?? []).map(journalFullAtFromWire)
435
+ journalFull: (r.journal_full ?? []).map(journalFullAtFromWire),
436
+ // Absent from an older wasm, which did not state its room: 0, so a host
437
+ // that cuts its hand by the room waits for a confirm instead of guessing.
438
+ journalRoomRows: Number(r.journal_room_rows ?? 0),
439
+ journalRoomBytes: Number(r.journal_room_bytes ?? 0)
394
440
  };
395
441
  }
396
442
  function applyBatchResultFromWire(r) {
@@ -404,6 +450,8 @@ function applyBatchResultFromWire(r) {
404
450
  joined: r.joined,
405
451
  updated: r.updated.map(conversationUpdateFromWire),
406
452
  ...outcomesFromWire(r),
453
+ // Absent from an older wasm, which named no row: nothing to hand again.
454
+ notTaken: (r.not_taken ?? []).map(Number),
407
455
  // Present only when the SDK says it: said once, with the batch at which
408
456
  // the anchor record was seen to change.
409
457
  ...r.state_backup_owed === true ? { stateBackupOwed: true } : {}
@@ -794,6 +842,50 @@ var AccountSetup = class _AccountSetup {
794
842
  storageFeatures: storageFeaturesOf(this.storage)
795
843
  });
796
844
  }
845
+ /**
846
+ * THE PREPARED DEVICE KEY (rulings V895 to V900, V913, V965): the device key
847
+ * a sign-in BY CODE names on a store with no device record, before the
848
+ * account exists. The SDK draws it (no argument is a key), keeps it in one
849
+ * row of this store and answers it; a repeat answers the SAME key, and two
850
+ * tabs that call at once answer one key (the origin's account lock).
851
+ * `createAccount`, the in-memory session and `MessagingClient.beginDeviceLink`
852
+ * then make the device with that key; a restore or a take-back never uses
853
+ * it. Store the secret BEFORE any request names the key. Refusals:
854
+ * `account-already-set-up` (the store holds a device), `rotation-in-progress`,
855
+ * `device-key-held-by-link` (a link was begun in this slot: offer "Finish
856
+ * linking" or "Start over", never a retry), `prepared-key-mismatch`.
857
+ */
858
+ prepareDeviceKey() {
859
+ return this.call({
860
+ kind: "prepareDeviceKey",
861
+ id: this.nextId++,
862
+ nowMs: this.now(),
863
+ storageFeatures: storageFeaturesOf(this.storage)
864
+ });
865
+ }
866
+ /** Delete a FREE prepared device key and nothing else; answers whether a
867
+ * row was deleted. Log the key's session out FIRST, and delete the host's
868
+ * own copy of the secret last. Refuses as `prepareDeviceKey` does. */
869
+ discardPreparedDeviceKey() {
870
+ return this.call({
871
+ kind: "discardPreparedDeviceKey",
872
+ id: this.nextId++,
873
+ storageFeatures: storageFeaturesOf(this.storage)
874
+ });
875
+ }
876
+ /** THE PREDICATE (ruling V904): what a start from the device record would
877
+ * answer on this store, as a typed value. It starts nothing, writes
878
+ * nothing and sends nothing. `expectedDeviceId` is the PUBLIC device id
879
+ * the host keeps, if it keeps one. Decide stop or retry on the answer,
880
+ * never on the words of an error. */
881
+ deviceStartCheck(expectedDeviceId) {
882
+ return this.call({
883
+ kind: "deviceStartCheck",
884
+ id: this.nextId++,
885
+ expectedDeviceId,
886
+ storageFeatures: storageFeaturesOf(this.storage)
887
+ });
888
+ }
797
889
  /** Whether the slot holds the pending root this device expects (rule R32).
798
890
  * No prompt, no read of the seed. */
799
891
  pendingStatus(slot) {
@@ -840,6 +932,21 @@ var AccountSetup = class _AccountSetup {
840
932
  storageFeatures: storageFeaturesOf(this.storage)
841
933
  });
842
934
  }
935
+ /** "Start over" on an account that was started on this device and never
936
+ * finished (rulings V1201, V1277): deletes the pending root of ONE slot and
937
+ * nothing else, or refuses with a typed answer (see `PendingRootDiscard`).
938
+ * THE HOST'S DUTY, which the SDK cannot check: the person chose it, the
939
+ * slot's stored account is the account signed in now, this sign-in's fresh
940
+ * answer is exactly `none_pinned`, and the slot's SDK store is emptied in
941
+ * the same erase. Never call it from a sweep. */
942
+ discardPendingRoot(slot) {
943
+ return this.call({
944
+ kind: "discardPendingRoot",
945
+ id: this.nextId++,
946
+ slot,
947
+ storageFeatures: storageFeaturesOf(this.storage)
948
+ });
949
+ }
843
950
  // ---- The restore as a rotation (the account identity contract, sections
844
951
  // 3.9, 3.13, 13.1). None of these needs a client or a session: the backup
845
952
  // is opened and the whole `rotation` object is built before the device
@@ -1029,14 +1136,18 @@ var AccountSetup = class _AccountSetup {
1029
1136
  * Begin a set-up session whose root is in memory only (rule R34 a): for the
1030
1137
  * person who makes the backup during set-up. One session per object; it
1031
1138
  * lives in the Worker until `sessionFinish`, `sessionKeepAsPending` or
1032
- * `close`.
1139
+ * `close`. It begins ON THIS STORE (read, nothing written): the session's
1140
+ * device is made for the store's free prepared device key, when
1141
+ * `prepareDeviceKey` made one. `device-key-held-by-link`: a link was begun
1142
+ * in this slot.
1033
1143
  */
1034
1144
  async beginInMemory(identityState) {
1035
1145
  await this.call({
1036
1146
  kind: "beginAccountSetupInMemory",
1037
1147
  id: this.nextId++,
1038
1148
  identityState,
1039
- nowMs: this.now()
1149
+ nowMs: this.now(),
1150
+ storageFeatures: storageFeaturesOf(this.storage)
1040
1151
  });
1041
1152
  }
1042
1153
  /** The session's backup. */
@@ -1280,13 +1391,15 @@ var MessagingClient = class _MessagingClient {
1280
1391
  */
1281
1392
  metaCache = /* @__PURE__ */ new Map();
1282
1393
  /**
1283
- * Per-conversation batching of sequenced live frames: the first frame goes
1284
- * to the worker at once, frames that arrive while that batch is in flight
1285
- * go out as ONE `processSequencedBatch` when it returns. See
1394
+ * ONE lane of sequenced live frames for every conversation: the first
1395
+ * frame goes to the worker at once, frames that arrive while that batch is
1396
+ * in flight go out as ONE `processSequencedBatch` when it returns, in
1397
+ * arrival order. Rows the engine did not take (`notTaken`) stay in the
1398
+ * lane and are handed again after the next `confirmApplied`. See
1286
1399
  * {@link dispatchIncoming}.
1287
1400
  */
1288
1401
  coalescer = new InboundCoalescer(
1289
- (_key, items) => this.applyLiveBatch(items)
1402
+ (items) => this.applyLiveBatch(items)
1290
1403
  );
1291
1404
  /** Single-flight gap fills, one `syncConversationStep` loop per conversation. */
1292
1405
  gapFiller = new GapFiller();
@@ -1895,10 +2008,14 @@ var MessagingClient = class _MessagingClient {
1895
2008
  * position, holds it ahead of a hole and drops it at or below what was
1896
2009
  * applied, whatever order it arrived in. What it needs is BATCHING: one
1897
2010
  * MLS checkpoint and one host transaction per burst instead of one per
1898
- * frame. So the first frame for a conversation goes to the worker at once
1899
- * as a batch of one, and frames that arrive while that batch is in flight
1900
- * accumulate and go out as ONE `processSequencedBatch` when it returns; no
1901
- * timer ever delays a frame. Own-device echoes are NOT dropped on this
2011
+ * frame. So the first frame goes to the worker at once as a batch of one,
2012
+ * and frames of ANY conversation that arrive while that batch is in flight
2013
+ * accumulate and go out as ONE `processSequencedBatch` when it returns, in
2014
+ * arrival order (one lane for all conversations: a catch-up of 200
2015
+ * conversations is about 20 Worker calls, not 400); no timer ever delays a
2016
+ * frame. Rows the engine did not take because the pending-apply journal
2017
+ * had no room (`notTaken`) stay in the lane, in order, and are handed
2018
+ * again after the next `confirmApplied`. Own-device echoes are NOT dropped on this
1902
2019
  * path: the core advances the position past them without touching MLS,
1903
2020
  * and dropping one would leave a hole the next frame reports as a gap. A
1904
2021
  * sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and
@@ -1907,7 +2024,9 @@ var MessagingClient = class _MessagingClient {
1907
2024
  dispatchIncoming(frame) {
1908
2025
  if (isSequencedFrame(frame)) {
1909
2026
  if (frame.serverSeq > 0) {
1910
- return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame);
2027
+ return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame).catch((e) => {
2028
+ if (typeof console !== "undefined") console.debug("[ping-sdk] sequenced batch failed:", errorKind(e));
2029
+ });
1911
2030
  }
1912
2031
  return this.dispatchLegacy(frame.envelope);
1913
2032
  }
@@ -1951,17 +2070,16 @@ var MessagingClient = class _MessagingClient {
1951
2070
  }
1952
2071
  }
1953
2072
  /**
1954
- * One coalesced batch of live frames. Errors are logged at debug and
1955
- * swallowed, exactly as the legacy path treats a failed envelope: the
1956
- * dispatch promise a transport may await resolves either way, and the
1957
- * core retains anything it could not apply yet.
2073
+ * One coalesced batch of live frames, of any number of conversations.
2074
+ * Answers the indexes of the rows the engine did not take (the journal
2075
+ * had no room): the lane keeps those and hands them again after the next
2076
+ * `confirmApplied`. A rejection goes to the lane, which hands a refused
2077
+ * batch again one conversation at a time; `dispatchIncoming` logs what
2078
+ * still fails at debug and resolves.
1958
2079
  */
1959
2080
  async applyLiveBatch(items) {
1960
- try {
1961
- await this.processSequencedBatch(items);
1962
- } catch (e) {
1963
- if (typeof console !== "undefined") console.debug("[ping-sdk] sequenced batch failed:", errorKind(e));
1964
- }
2081
+ const result = await this.processSequencedBatch(items);
2082
+ return result.notTaken;
1965
2083
  }
1966
2084
  /** Start a fill for every gap a batch reported; each is single-flight. */
1967
2085
  scheduleGapFills(result) {
@@ -2357,6 +2475,14 @@ var MessagingClient = class _MessagingClient {
2357
2475
  * an interactive call behind all of them. Resolves when every conversation
2358
2476
  * held at the start of the pass (plus any joined while it ran) has been
2359
2477
  * paged, with the decrypted application messages in apply order.
2478
+ *
2479
+ * Rejects with `StoreMovedError` when the client failed closed: before the
2480
+ * pass (it then asks nothing of the server), inside one of its steps (no
2481
+ * later conversation is asked; the pages before it were delivered), or
2482
+ * during its last step. A client that failed closed before or during the
2483
+ * pass never resolves at all, with an empty list or with any other. The
2484
+ * host drops the client and starts a new one on the same store, which
2485
+ * hands what was stored (`pendingApplies`).
2360
2486
  */
2361
2487
  async syncConversations() {
2362
2488
  return await this.call({
@@ -2667,6 +2793,7 @@ var MessagingClient = class _MessagingClient {
2667
2793
  async confirmApplied(journalIds) {
2668
2794
  if (journalIds.length === 0) return;
2669
2795
  await this.call({ kind: "confirmApplied", id: this.nextId++, journalIds });
2796
+ this.coalescer.roomFreed();
2670
2797
  }
2671
2798
  /**
2672
2799
  * The version 3 handshake payload this NEW device publishes: its own signing key,