@ping-app/ping-openmls-sdk 0.10.4 → 0.10.6

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) {
@@ -1029,14 +1121,18 @@ var AccountSetup = class _AccountSetup {
1029
1121
  * Begin a set-up session whose root is in memory only (rule R34 a): for the
1030
1122
  * person who makes the backup during set-up. One session per object; it
1031
1123
  * lives in the Worker until `sessionFinish`, `sessionKeepAsPending` or
1032
- * `close`.
1124
+ * `close`. It begins ON THIS STORE (read, nothing written): the session's
1125
+ * device is made for the store's free prepared device key, when
1126
+ * `prepareDeviceKey` made one. `device-key-held-by-link`: a link was begun
1127
+ * in this slot.
1033
1128
  */
1034
1129
  async beginInMemory(identityState) {
1035
1130
  await this.call({
1036
1131
  kind: "beginAccountSetupInMemory",
1037
1132
  id: this.nextId++,
1038
1133
  identityState,
1039
- nowMs: this.now()
1134
+ nowMs: this.now(),
1135
+ storageFeatures: storageFeaturesOf(this.storage)
1040
1136
  });
1041
1137
  }
1042
1138
  /** The session's backup. */
@@ -1280,13 +1376,15 @@ var MessagingClient = class _MessagingClient {
1280
1376
  */
1281
1377
  metaCache = /* @__PURE__ */ new Map();
1282
1378
  /**
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
1379
+ * ONE lane of sequenced live frames for every conversation: the first
1380
+ * frame goes to the worker at once, frames that arrive while that batch is
1381
+ * in flight go out as ONE `processSequencedBatch` when it returns, in
1382
+ * arrival order. Rows the engine did not take (`notTaken`) stay in the
1383
+ * lane and are handed again after the next `confirmApplied`. See
1286
1384
  * {@link dispatchIncoming}.
1287
1385
  */
1288
1386
  coalescer = new InboundCoalescer(
1289
- (_key, items) => this.applyLiveBatch(items)
1387
+ (items) => this.applyLiveBatch(items)
1290
1388
  );
1291
1389
  /** Single-flight gap fills, one `syncConversationStep` loop per conversation. */
1292
1390
  gapFiller = new GapFiller();
@@ -1895,10 +1993,14 @@ var MessagingClient = class _MessagingClient {
1895
1993
  * position, holds it ahead of a hole and drops it at or below what was
1896
1994
  * applied, whatever order it arrived in. What it needs is BATCHING: one
1897
1995
  * 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
1996
+ * frame. So the first frame goes to the worker at once as a batch of one,
1997
+ * and frames of ANY conversation that arrive while that batch is in flight
1998
+ * accumulate and go out as ONE `processSequencedBatch` when it returns, in
1999
+ * arrival order (one lane for all conversations: a catch-up of 200
2000
+ * conversations is about 20 Worker calls, not 400); no timer ever delays a
2001
+ * frame. Rows the engine did not take because the pending-apply journal
2002
+ * had no room (`notTaken`) stay in the lane, in order, and are handed
2003
+ * again after the next `confirmApplied`. Own-device echoes are NOT dropped on this
1902
2004
  * path: the core advances the position past them without touching MLS,
1903
2005
  * and dropping one would leave a hole the next frame reports as a gap. A
1904
2006
  * sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and
@@ -1907,7 +2009,9 @@ var MessagingClient = class _MessagingClient {
1907
2009
  dispatchIncoming(frame) {
1908
2010
  if (isSequencedFrame(frame)) {
1909
2011
  if (frame.serverSeq > 0) {
1910
- return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame);
2012
+ return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame).catch((e) => {
2013
+ if (typeof console !== "undefined") console.debug("[ping-sdk] sequenced batch failed:", errorKind(e));
2014
+ });
1911
2015
  }
1912
2016
  return this.dispatchLegacy(frame.envelope);
1913
2017
  }
@@ -1951,17 +2055,16 @@ var MessagingClient = class _MessagingClient {
1951
2055
  }
1952
2056
  }
1953
2057
  /**
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.
2058
+ * One coalesced batch of live frames, of any number of conversations.
2059
+ * Answers the indexes of the rows the engine did not take (the journal
2060
+ * had no room): the lane keeps those and hands them again after the next
2061
+ * `confirmApplied`. A rejection goes to the lane, which hands a refused
2062
+ * batch again one conversation at a time; `dispatchIncoming` logs what
2063
+ * still fails at debug and resolves.
1958
2064
  */
1959
2065
  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
- }
2066
+ const result = await this.processSequencedBatch(items);
2067
+ return result.notTaken;
1965
2068
  }
1966
2069
  /** Start a fill for every gap a batch reported; each is single-flight. */
1967
2070
  scheduleGapFills(result) {
@@ -2667,6 +2770,7 @@ var MessagingClient = class _MessagingClient {
2667
2770
  async confirmApplied(journalIds) {
2668
2771
  if (journalIds.length === 0) return;
2669
2772
  await this.call({ kind: "confirmApplied", id: this.nextId++, journalIds });
2773
+ this.coalescer.roomFreed();
2670
2774
  }
2671
2775
  /**
2672
2776
  * The version 3 handshake payload this NEW device publishes: its own signing key,