@vrtmrz/livesync-commonlib 0.6.1 → 0.8.0

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.
Files changed (124) hide show
  1. package/README.md +29 -19
  2. package/dist/common/models/shared.definition.d.ts +10 -1
  3. package/dist/common/models/shared.definition.js +4 -3
  4. package/dist/events/coreEvents.d.ts +3 -0
  5. package/dist/events/coreEvents.js +2 -0
  6. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  7. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  8. package/dist/managers/EntryManager/EntryManager.d.ts +1 -1
  9. package/dist/managers/EntryManager/EntryManager.js +2 -2
  10. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +1 -1
  11. package/dist/managers/EntryManager/EntryManagerImpls.js +80 -8
  12. package/dist/managers/StorageEventManager/admission.d.ts +16 -3
  13. package/dist/managers/StorageEventManager/admission.js +18 -4
  14. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  15. package/dist/managers/StorageEventManager/processing.js +3 -3
  16. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  17. package/dist/managers/StorageEventManager/queue.js +70 -30
  18. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  19. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  20. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  21. package/dist/managers/StorageEventManager/state.js +9 -7
  22. package/dist/managers/StorageEventManager.d.ts +8 -0
  23. package/dist/managers/StorageEventManager.js +136 -18
  24. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  25. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  26. package/dist/managers/adapters/index.d.ts +1 -1
  27. package/dist/pouchdb/LiveSyncLocalDB.d.ts +1 -1
  28. package/dist/pouchdb/LiveSyncLocalDB.js +2 -2
  29. package/dist/replication/LiveSyncAbstractReplicator.d.ts +7 -0
  30. package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
  31. package/dist/replication/ReplicatorInstance.d.ts +3 -0
  32. package/dist/replication/ReplicatorProvider.d.ts +23 -2
  33. package/dist/replication/ReplicatorProvider.js +10 -0
  34. package/dist/replication/SyncParamsHandler.js +26 -25
  35. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +14 -2
  36. package/dist/replication/couchdb/LiveSyncReplicator.js +247 -122
  37. package/dist/replication/index.d.ts +4 -2
  38. package/dist/replication/index.js +6 -0
  39. package/dist/replication/remoteTransportFailure.d.ts +24 -0
  40. package/dist/replication/remoteTransportFailure.js +80 -0
  41. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +1 -1
  42. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +2 -2
  43. package/dist/replication/trystero/TrysteroRpcRoom.d.ts +14 -0
  44. package/dist/replication/trystero/TrysteroRpcRoom.js +168 -0
  45. package/dist/replication/trystero/rpcCompat.d.ts +1 -0
  46. package/dist/replication/trystero/rpcCompat.js +15 -0
  47. package/dist/rpc/RpcRoom.d.ts +1 -0
  48. package/dist/rpc/RpcRoom.js +21 -9
  49. package/dist/rpc/RpcSession.d.ts +8 -13
  50. package/dist/rpc/RpcSession.js +14 -35
  51. package/dist/rpc/commonlibRpcRoom.d.ts +1 -0
  52. package/dist/rpc/commonlibRpcRoom.js +4 -0
  53. package/dist/rpc/errors.d.ts +9 -3
  54. package/dist/rpc/errors.js +13 -16
  55. package/dist/rpc/index.d.ts +10 -1
  56. package/dist/rpc/index.js +2 -1
  57. package/dist/rpc/pouchdb/RpcPouchDBProxy.d.ts +1 -1
  58. package/dist/rpc/pouchdb/RpcPouchDBServer.d.ts +1 -1
  59. package/dist/serviceFeatures/targetFilter.d.ts +3 -1
  60. package/dist/serviceFeatures/targetFilter.js +2 -2
  61. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
  62. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
  63. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
  64. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
  65. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
  66. package/dist/services/base/IService.d.ts +9 -6
  67. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  68. package/dist/services/base/ReadinessEvaluator.d.ts +7 -6
  69. package/dist/services/base/ReadinessEvaluator.js +4 -2
  70. package/dist/services/base/RemoteConnection.d.ts +4 -0
  71. package/dist/services/base/RemoteService.d.ts +5 -3
  72. package/dist/services/base/RemoteService.js +85 -33
  73. package/dist/services/base/ReplicationService.d.ts +10 -2
  74. package/dist/services/base/ReplicationService.js +13 -7
  75. package/dist/services/base/ReplicationService.readiness.d.ts +14 -4
  76. package/dist/services/base/ReplicationService.readiness.js +29 -2
  77. package/dist/services/base/ReplicationService.typedReplication.d.ts +5 -2
  78. package/dist/services/base/ReplicationService.typedReplication.js +67 -6
  79. package/dist/services/base/ReplicationStaticsOwner.d.ts +18 -0
  80. package/dist/services/base/ReplicationStaticsOwner.js +33 -0
  81. package/dist/services/base/ReplicatorService.d.ts +2 -10
  82. package/dist/services/base/ReplicatorService.js +6 -3
  83. package/dist/services/base/VaultService.d.ts +1 -0
  84. package/dist/string_and_binary/chunks.d.ts +1 -1
  85. package/dist/string_and_binary/chunks.js +63 -50
  86. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  87. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  88. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  89. package/dist/worker/WorkerPushStreamReader.js +179 -0
  90. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  91. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  92. package/dist/worker/bg.worker.js +2 -14
  93. package/dist/worker/bg.worker.splitting.d.ts +3 -6
  94. package/dist/worker/bg.worker.splitting.js +65 -30
  95. package/dist/worker/bgWorker.d.ts +9 -11
  96. package/dist/worker/bgWorker.direct.d.ts +5 -28
  97. package/dist/worker/bgWorker.direct.js +32 -2
  98. package/dist/worker/bgWorker.errors.d.ts +1 -0
  99. package/dist/worker/bgWorker.errors.js +12 -0
  100. package/dist/worker/bgWorker.js +718 -268
  101. package/dist/worker/bgWorker.splitting.d.ts +12 -27
  102. package/dist/worker/bgWorker.splitting.js +114 -110
  103. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  104. package/dist/worker/outOfBandCancelIterator.js +8 -0
  105. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  106. package/dist/worker/serveBackgroundWorker.js +35 -0
  107. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  108. package/dist/worker/splitConnectionTracker.js +73 -0
  109. package/dist/worker/splitGate.d.ts +19 -0
  110. package/dist/worker/splitGate.js +71 -0
  111. package/dist/worker/universalTypes.d.ts +1 -19
  112. package/dist/worker/universalTypes.js +0 -4
  113. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  114. package/dist/worker/workerPushStreamProtocol.js +143 -0
  115. package/docs/development.md +75 -32
  116. package/docs/p2p-transport-lifecycle.md +2 -3
  117. package/docs/storage-events-and-reflection.md +40 -5
  118. package/package.json +3 -2
  119. package/dist/worker/bg.common.d.ts +0 -2
  120. package/dist/worker/bg.common.js +0 -6
  121. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  122. package/dist/worker/bg.worker.encryption.js +0 -30
  123. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  124. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -1,6 +1,8 @@
1
1
  function isTextBlob(blob) {
2
2
  return blob.type === "text/plain";
3
3
  }
4
+ import { iterateBlobBlocks } from "octagonal-wheels/binary/blob";
5
+ import { concatUInt8Array } from "octagonal-wheels/binary/typedArray";
4
6
  import { LOG_LEVEL_VERBOSE, Logger } from "../common/logger.js";
5
7
  import { arrayBufferToBase64Single, readString } from "./convert.js";
6
8
  import { wrapByDefault } from "../common/utils.js";
@@ -384,7 +386,7 @@ async function splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, fi
384
386
  } while (i < size);
385
387
  };
386
388
  }
387
- async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter) {
389
+ async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter, signal) {
388
390
  let plainSplit = doPlainSplit || isTextBlob(dataSrc);
389
391
  const dataSize = dataSrc.size;
390
392
  let chunkUnitPlain = 64;
@@ -417,66 +419,77 @@ async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit,
417
419
  const windowSize = 48;
418
420
  const hashModulus = avgChunkSize;
419
421
  const boundaryPattern = 1;
420
- const PRIME = 31;
421
- let P_pow_w = 1;
422
+ const prime = 31;
423
+ let outgoingByteWeight = 1;
422
424
  for (let i = 0; i < windowSize - 1; i++) {
423
- P_pow_w = Math.imul(P_pow_w, PRIME);
425
+ outgoingByteWeight = Math.imul(outgoingByteWeight, prime);
424
426
  }
425
- const buffer = new Uint8Array(await dataSrc.arrayBuffer());
426
- let pos = 0;
427
- let hash = 0;
428
- let start = 0;
429
427
  const isText = isTextBlob(dataSrc);
430
- const length = buffer.length;
431
- return async function* piecesBlob() {
432
- while (pos < length) {
433
- const byte = buffer[pos];
434
- if (pos >= windowSize) {
435
- const oldByte = buffer[pos - windowSize];
436
- const oldByteTerm = Math.imul(oldByte, P_pow_w);
437
- hash = hash - oldByteTerm | 0;
438
- hash = Math.imul(hash, PRIME);
439
- hash = hash + byte | 0;
440
- } else {
441
- hash = Math.imul(hash, PRIME);
442
- hash = hash + byte | 0;
443
- }
444
- const currentChunkSize = pos - start + 1;
445
- let isBoundaryCandidate = false;
446
- if (currentChunkSize >= minChunkSize) {
447
- if ((hash >>> 0) % hashModulus === boundaryPattern) {
448
- isBoundaryCandidate = true;
449
- }
428
+ const readBlockBytes = 1024 * 1024;
429
+ async function* readChunks() {
430
+ if (dataSize === 0 || signal?.aborted) {
431
+ return;
432
+ }
433
+ const previousWindow = new Uint8Array(windowSize);
434
+ const pendingParts = [];
435
+ let remainingBytes = dataSize;
436
+ let hash = 0;
437
+ let chunkSize = 0;
438
+ function isBoundaryCandidate() {
439
+ return chunkSize >= maxChunkSize || chunkSize >= minChunkSize && (hash >>> 0) % hashModulus === boundaryPattern;
440
+ }
441
+ function finishChunk(lastPart) {
442
+ if (pendingParts.length === 0) {
443
+ return lastPart;
450
444
  }
451
- if (currentChunkSize >= maxChunkSize) {
452
- isBoundaryCandidate = true;
445
+ if (lastPart.length > 0) {
446
+ pendingParts.push(lastPart);
453
447
  }
454
- if (isBoundaryCandidate) {
455
- let isSafeBoundary = true;
456
- if (isText) {
457
- if (pos + 1 < length && (buffer[pos + 1] & 192) === 128) {
458
- isSafeBoundary = false;
459
- }
448
+ const bytes = pendingParts.length === 1 ? pendingParts[0] : concatUInt8Array(pendingParts);
449
+ pendingParts.length = 0;
450
+ return bytes;
451
+ }
452
+ const blocks = dataSize > readBlockBytes ? iterateBlobBlocks(dataSrc, readBlockBytes) : void 0;
453
+ try {
454
+ while (remainingBytes > 0 && !signal?.aborted) {
455
+ const block = blocks ? (await blocks.next()).value : new Uint8Array(await dataSrc.arrayBuffer());
456
+ if (!block || signal?.aborted) {
457
+ return;
460
458
  }
461
- if (isSafeBoundary) {
462
- if (isText) {
463
- yield Promise.resolve(readString(buffer.subarray(start, pos + 1)));
464
- } else {
465
- yield await arrayBufferToBase64Single(buffer.subarray(start, pos + 1));
459
+ let chunkStart = 0;
460
+ for (let index = 0; index < block.length; index++) {
461
+ const byte = block[index];
462
+ if (isBoundaryCandidate() && (!isText || (byte & 192) !== 128)) {
463
+ const chunk = finishChunk(block.subarray(chunkStart, index));
464
+ chunkStart = index;
465
+ chunkSize = 0;
466
+ yield isText ? readString(chunk) : await arrayBufferToBase64Single(chunk);
466
467
  }
467
- start = pos + 1;
468
+ const oldByte = index < windowSize ? previousWindow[index] : block[index - windowSize];
469
+ hash = Math.imul(hash - Math.imul(oldByte, outgoingByteWeight), prime) + byte | 0;
470
+ chunkSize++;
471
+ }
472
+ remainingBytes -= block.length;
473
+ const lastPart = block.subarray(chunkStart);
474
+ if (remainingBytes === 0 || !isText && isBoundaryCandidate()) {
475
+ const chunk = finishChunk(lastPart);
476
+ chunkSize = 0;
477
+ yield isText ? readString(chunk) : await arrayBufferToBase64Single(chunk);
478
+ } else {
479
+ pendingParts.push(lastPart);
480
+ }
481
+ if (remainingBytes > 0) {
482
+ previousWindow.set(block.subarray(block.length - windowSize));
468
483
  }
469
484
  }
470
- pos++;
471
- }
472
- if (start < length) {
473
- if (isText) {
474
- yield Promise.resolve(readString(buffer.subarray(start, length)));
475
- } else {
476
- yield await arrayBufferToBase64Single(buffer.subarray(start, length));
485
+ } finally {
486
+ if (blocks) {
487
+ await blocks.return();
477
488
  }
478
489
  }
479
- };
490
+ }
491
+ const chunks = readChunks();
492
+ return () => chunks;
480
493
  }
481
494
  async function splitPiecesRabinKarpOld(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter) {
482
495
  const plainSplit = doPlainSplit || isTextBlob(dataSrc);
@@ -0,0 +1,45 @@
1
+ import { type ServeOptions } from "./workerPushStreamProtocol.js";
2
+ export declare class WorkerPushStreamProducer<T> {
3
+ private readonly options;
4
+ readonly readerPort: MessagePort;
5
+ private readonly producerPort;
6
+ private readonly controller;
7
+ private readonly batchTargetBytes;
8
+ private readonly maxBatchItems;
9
+ private readonly signal;
10
+ private source;
11
+ private finished;
12
+ private pumping;
13
+ private initialGrant;
14
+ private inFlightBytes;
15
+ private oversizedInFlight;
16
+ private batch;
17
+ private batchCharge;
18
+ private stagedItem;
19
+ private flushTimer;
20
+ private yieldChannel;
21
+ private yieldAfterBatch;
22
+ private resolveYield;
23
+ private readonly claimTimer;
24
+ constructor(options: ServeOptions<T>);
25
+ private post;
26
+ /** Unblock the pump and close both ends of its scheduling channel. */
27
+ private clearYield;
28
+ /** Let pending port events run between batches without relying on a timer. */
29
+ private scheduleYield;
30
+ private finish;
31
+ private postBatch;
32
+ private flushWhileReading;
33
+ /** Flush a full batch before admitting the staged item against the remaining credit. */
34
+ private admitStagedItem;
35
+ /** Flush an accumulated batch if the source takes another task to produce an item. */
36
+ private readNextItem;
37
+ private pump;
38
+ private applyCancel;
39
+ private applyCredit;
40
+ private onMessage;
41
+ private onMessageError;
42
+ private onClose;
43
+ private onAbort;
44
+ }
45
+ export declare function serveWorkerPushStream<T>(options: ServeOptions<T>): import("@vrtmrz/rpc").WithTransfer<MessagePort, MessagePort>;
@@ -0,0 +1,299 @@
1
+ import { RpcError, withTransfer } from "@vrtmrz/rpc";
2
+ import {
3
+ VERSION,
4
+ DEFAULT_BATCH_TARGET_BYTES,
5
+ DEFAULT_CLAIM_TIMEOUT_MS,
6
+ DEFAULT_MAX_BATCH_ITEMS,
7
+ canSend,
8
+ checkLimits,
9
+ deserialiseError,
10
+ disconnected,
11
+ isPositiveSafeInteger,
12
+ isRecord,
13
+ isWireError,
14
+ measureItem,
15
+ protocolError,
16
+ serialiseError
17
+ } from "./workerPushStreamProtocol.js";
18
+ class WorkerPushStreamProducer {
19
+ constructor(options) {
20
+ this.options = options;
21
+ const {
22
+ batchTargetBytes = DEFAULT_BATCH_TARGET_BYTES,
23
+ maxBatchItems = DEFAULT_MAX_BATCH_ITEMS,
24
+ claimTimeoutMs = DEFAULT_CLAIM_TIMEOUT_MS,
25
+ signal
26
+ } = options;
27
+ this.batchTargetBytes = batchTargetBytes;
28
+ this.maxBatchItems = maxBatchItems;
29
+ this.signal = signal;
30
+ checkLimits(options.maxItemBytes, this.batchTargetBytes, this.maxBatchItems, claimTimeoutMs);
31
+ const { port1, port2 } = new MessageChannel();
32
+ this.producerPort = port1;
33
+ this.readerPort = port2;
34
+ this.claimTimer = setTimeout(
35
+ () => this.finish({ error: new RpcError("timeout", "Worker stream port was not claimed.") }),
36
+ claimTimeoutMs
37
+ );
38
+ this.producerPort.addEventListener("message", this.onMessage);
39
+ this.producerPort.addEventListener("messageerror", this.onMessageError);
40
+ this.producerPort.addEventListener("close", this.onClose);
41
+ signal?.addEventListener("abort", this.onAbort, { once: true });
42
+ this.producerPort.start();
43
+ if (signal?.aborted) {
44
+ this.onAbort();
45
+ }
46
+ }
47
+ options;
48
+ readerPort;
49
+ producerPort;
50
+ controller = new AbortController();
51
+ batchTargetBytes;
52
+ maxBatchItems;
53
+ signal;
54
+ source;
55
+ finished = false;
56
+ pumping = false;
57
+ initialGrant = 0;
58
+ inFlightBytes = 0;
59
+ oversizedInFlight = false;
60
+ batch = [];
61
+ batchCharge = 0;
62
+ stagedItem;
63
+ flushTimer;
64
+ yieldChannel;
65
+ yieldAfterBatch;
66
+ resolveYield;
67
+ claimTimer;
68
+ post(message) {
69
+ this.producerPort.postMessage(message);
70
+ }
71
+ /** Unblock the pump and close both ends of its scheduling channel. */
72
+ clearYield() {
73
+ const resolve = this.resolveYield;
74
+ this.resolveYield = void 0;
75
+ this.yieldAfterBatch = void 0;
76
+ resolve?.();
77
+ if (this.yieldChannel !== void 0) {
78
+ this.yieldChannel.port1.onmessage = null;
79
+ this.yieldChannel.port1.close();
80
+ this.yieldChannel.port2.close();
81
+ this.yieldChannel = void 0;
82
+ }
83
+ }
84
+ /** Let pending port events run between batches without relying on a timer. */
85
+ scheduleYield() {
86
+ if (this.yieldAfterBatch !== void 0) {
87
+ return;
88
+ }
89
+ if (this.yieldChannel === void 0) {
90
+ this.yieldChannel = new MessageChannel();
91
+ }
92
+ const channel = this.yieldChannel;
93
+ this.yieldAfterBatch = new Promise((resolve) => {
94
+ this.resolveYield = resolve;
95
+ channel.port1.onmessage = () => {
96
+ if (this.resolveYield === resolve) {
97
+ this.resolveYield = void 0;
98
+ this.yieldAfterBatch = void 0;
99
+ resolve();
100
+ }
101
+ };
102
+ channel.port2.postMessage(void 0);
103
+ });
104
+ }
105
+ finish(failure, notifyPeer = true) {
106
+ if (this.finished) {
107
+ return;
108
+ }
109
+ this.finished = true;
110
+ clearTimeout(this.claimTimer);
111
+ clearTimeout(this.flushTimer);
112
+ this.clearYield();
113
+ this.batch = [];
114
+ this.stagedItem = void 0;
115
+ this.producerPort.removeEventListener("message", this.onMessage);
116
+ this.producerPort.removeEventListener("messageerror", this.onMessageError);
117
+ this.producerPort.removeEventListener("close", this.onClose);
118
+ this.signal?.removeEventListener("abort", this.onAbort);
119
+ try {
120
+ if (failure && notifyPeer) {
121
+ this.post({ version: VERSION, type: "error", error: serialiseError(failure.error) });
122
+ }
123
+ } catch {
124
+ } finally {
125
+ this.producerPort.close();
126
+ if (failure || this.source) {
127
+ this.controller.abort(failure?.error);
128
+ }
129
+ if (this.source) {
130
+ try {
131
+ void Promise.resolve(this.source.return?.()).catch(() => void 0);
132
+ } catch {
133
+ }
134
+ this.source = void 0;
135
+ }
136
+ }
137
+ }
138
+ postBatch(shouldYield) {
139
+ this.post({ version: VERSION, type: "batch", items: this.batch, chargeBytes: this.batchCharge });
140
+ this.inFlightBytes += this.batchCharge;
141
+ this.oversizedInFlight = this.batchCharge > this.initialGrant;
142
+ this.batch = [];
143
+ this.batchCharge = 0;
144
+ if (shouldYield) {
145
+ this.scheduleYield();
146
+ }
147
+ }
148
+ flushWhileReading = () => {
149
+ if (!this.finished && this.batch.length > 0) {
150
+ try {
151
+ this.postBatch(true);
152
+ } catch (error) {
153
+ this.finish({ error });
154
+ }
155
+ }
156
+ };
157
+ /** Flush a full batch before admitting the staged item against the remaining credit. */
158
+ admitStagedItem(limit) {
159
+ const next = this.stagedItem;
160
+ if (this.batch.length > 0 && next.charge > limit - this.batchCharge) {
161
+ this.postBatch(true);
162
+ return "continue";
163
+ }
164
+ if (!canSend(next.charge, this.inFlightBytes, this.initialGrant)) {
165
+ return "wait";
166
+ }
167
+ this.batch.push(next.item);
168
+ this.batchCharge += next.charge;
169
+ this.stagedItem = void 0;
170
+ if (this.batchCharge >= limit || this.batch.length === this.maxBatchItems) {
171
+ this.postBatch(true);
172
+ }
173
+ return "continue";
174
+ }
175
+ /** Flush an accumulated batch if the source takes another task to produce an item. */
176
+ async readNextItem(iterator) {
177
+ if (this.batch.length > 0) {
178
+ this.flushTimer = setTimeout(this.flushWhileReading, 0);
179
+ }
180
+ try {
181
+ return await iterator.next();
182
+ } finally {
183
+ clearTimeout(this.flushTimer);
184
+ }
185
+ }
186
+ async pump(iterator) {
187
+ if (this.pumping) {
188
+ return;
189
+ }
190
+ this.pumping = true;
191
+ try {
192
+ while (!this.finished) {
193
+ if (this.yieldAfterBatch !== void 0) {
194
+ await this.yieldAfterBatch;
195
+ if (this.finished) {
196
+ return;
197
+ }
198
+ }
199
+ if (this.oversizedInFlight) {
200
+ return;
201
+ }
202
+ const available = this.initialGrant - this.inFlightBytes;
203
+ const limit = Math.min(this.batchTargetBytes, available);
204
+ if (this.stagedItem !== void 0) {
205
+ if (this.admitStagedItem(limit) === "wait") {
206
+ return;
207
+ }
208
+ continue;
209
+ }
210
+ if (available <= 0) {
211
+ return;
212
+ }
213
+ const result = await this.readNextItem(iterator);
214
+ if (this.finished) {
215
+ return;
216
+ }
217
+ if (result.done) {
218
+ if (this.batch.length > 0) {
219
+ this.postBatch(false);
220
+ }
221
+ this.post({ version: VERSION, type: "end" });
222
+ this.source = void 0;
223
+ this.finish();
224
+ return;
225
+ }
226
+ this.stagedItem = { item: result.value, charge: measureItem(this.options, result.value) };
227
+ }
228
+ } catch (error) {
229
+ this.finish({ error });
230
+ } finally {
231
+ this.pumping = false;
232
+ }
233
+ }
234
+ applyCancel(rawError) {
235
+ if (rawError === void 0) {
236
+ this.finish({ error: new RpcError("aborted", "Worker stream reader cancelled.") }, false);
237
+ } else if (isWireError(rawError)) {
238
+ this.finish({ error: deserialiseError(rawError) }, false);
239
+ } else {
240
+ this.finish({ error: protocolError("Invalid Worker stream cancellation error.") });
241
+ }
242
+ }
243
+ applyCredit(bytes) {
244
+ if (this.initialGrant === 0) {
245
+ this.initialGrant = bytes;
246
+ clearTimeout(this.claimTimer);
247
+ try {
248
+ this.source = this.options.createSource(this.controller.signal)[Symbol.asyncIterator]();
249
+ } catch (error) {
250
+ this.finish({ error });
251
+ return;
252
+ }
253
+ } else {
254
+ if (bytes > this.inFlightBytes) {
255
+ this.finish({ error: protocolError("Worker stream refunded more than the outstanding charge.") });
256
+ return;
257
+ }
258
+ this.inFlightBytes -= bytes;
259
+ if (this.inFlightBytes === 0) {
260
+ this.oversizedInFlight = false;
261
+ }
262
+ }
263
+ if (this.source) {
264
+ void this.pump(this.source);
265
+ }
266
+ }
267
+ onMessage = ({ data }) => {
268
+ if (!isRecord(data) || data.version !== VERSION) {
269
+ this.finish({ error: protocolError("Invalid Worker stream reader message.") });
270
+ return;
271
+ }
272
+ if (data.type === "cancel") {
273
+ this.applyCancel(data.error);
274
+ return;
275
+ }
276
+ if (data.type !== "credit" || !isPositiveSafeInteger(data.bytes)) {
277
+ this.finish({ error: protocolError("Invalid Worker stream credit.") });
278
+ return;
279
+ }
280
+ this.applyCredit(data.bytes);
281
+ };
282
+ onMessageError = () => {
283
+ this.finish({ error: protocolError("Could not decode Worker stream reader message.") });
284
+ };
285
+ onClose = () => {
286
+ this.finish({ error: new RpcError("disconnected", "Worker stream port closed unexpectedly.") }, false);
287
+ };
288
+ onAbort = () => {
289
+ this.finish({ error: disconnected(this.signal) });
290
+ };
291
+ }
292
+ function serveWorkerPushStream(options) {
293
+ const { readerPort } = new WorkerPushStreamProducer(options);
294
+ return withTransfer(readerPort, [readerPort]);
295
+ }
296
+ export {
297
+ WorkerPushStreamProducer,
298
+ serveWorkerPushStream
299
+ };
@@ -0,0 +1,28 @@
1
+ import { type ReadOptions } from "./workerPushStreamProtocol.js";
2
+ export declare class WorkerPushStreamReader<T> {
3
+ private readonly options;
4
+ private readonly port;
5
+ private readonly initialCreditBytes;
6
+ private readonly maxBatchItems;
7
+ private readonly signal;
8
+ private readonly onRemoteEnd;
9
+ private readonly onError;
10
+ private readonly queue;
11
+ private inFlightBytes;
12
+ private remoteEnded;
13
+ private outcome;
14
+ private waiting;
15
+ constructor(options: ReadOptions<T>);
16
+ start(): void;
17
+ cancel(): void;
18
+ private detach;
19
+ private finish;
20
+ private acceptBatch;
21
+ private onMessage;
22
+ private onMessageError;
23
+ private onClose;
24
+ private onAbort;
25
+ private sendCredit;
26
+ read(): AsyncGenerator<readonly T[], void, unknown>;
27
+ }
28
+ export declare function readWorkerPushStream<T>(options: ReadOptions<T>): AsyncGenerator<readonly T[], void, unknown>;
@@ -0,0 +1,179 @@
1
+ import { RpcError } from "@vrtmrz/rpc";
2
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
3
+ import {
4
+ VERSION,
5
+ DEFAULT_INITIAL_CREDIT_BYTES,
6
+ DEFAULT_MAX_BATCH_ITEMS,
7
+ cancelWorkerPushStream,
8
+ checkLimits,
9
+ deserialiseError,
10
+ disconnected,
11
+ isRecord,
12
+ isWireError,
13
+ protocolError,
14
+ stopGeneratorOnReturn,
15
+ validateBatch
16
+ } from "./workerPushStreamProtocol.js";
17
+ class WorkerPushStreamReader {
18
+ constructor(options) {
19
+ this.options = options;
20
+ const {
21
+ port,
22
+ signal,
23
+ onRemoteEnd,
24
+ onError,
25
+ initialCreditBytes = DEFAULT_INITIAL_CREDIT_BYTES,
26
+ maxBatchItems = DEFAULT_MAX_BATCH_ITEMS
27
+ } = options;
28
+ this.port = port;
29
+ this.initialCreditBytes = initialCreditBytes;
30
+ this.maxBatchItems = maxBatchItems;
31
+ this.signal = signal;
32
+ this.onRemoteEnd = onRemoteEnd;
33
+ this.onError = onError;
34
+ checkLimits(options.maxItemBytes, this.initialCreditBytes, this.maxBatchItems);
35
+ }
36
+ options;
37
+ port;
38
+ initialCreditBytes;
39
+ maxBatchItems;
40
+ signal;
41
+ onRemoteEnd;
42
+ onError;
43
+ queue = [];
44
+ inFlightBytes = 0;
45
+ remoteEnded = false;
46
+ outcome;
47
+ waiting;
48
+ start() {
49
+ this.port.addEventListener("message", this.onMessage);
50
+ this.port.addEventListener("messageerror", this.onMessageError);
51
+ this.port.addEventListener("close", this.onClose);
52
+ this.signal?.addEventListener("abort", this.onAbort, { once: true });
53
+ this.port.start();
54
+ if (this.signal?.aborted) {
55
+ this.onAbort();
56
+ } else {
57
+ this.sendCredit(this.initialCreditBytes);
58
+ }
59
+ }
60
+ cancel() {
61
+ this.finish("return");
62
+ }
63
+ detach() {
64
+ this.port.removeEventListener("message", this.onMessage);
65
+ this.port.removeEventListener("messageerror", this.onMessageError);
66
+ this.port.removeEventListener("close", this.onClose);
67
+ this.signal?.removeEventListener("abort", this.onAbort);
68
+ }
69
+ finish(result, notifyPeer = true) {
70
+ if (this.outcome !== void 0) {
71
+ return;
72
+ }
73
+ this.outcome = result;
74
+ this.queue.length = 0;
75
+ this.waiting?.resolve();
76
+ if (!this.remoteEnded) {
77
+ this.detach();
78
+ if (notifyPeer) {
79
+ cancelWorkerPushStream(this.port, result === "return" ? void 0 : result);
80
+ } else {
81
+ this.port.close();
82
+ }
83
+ }
84
+ if (result !== "return") {
85
+ const { onError } = this;
86
+ onError?.(result.error);
87
+ }
88
+ }
89
+ acceptBatch(data) {
90
+ const batch = validateBatch(
91
+ this.options,
92
+ data,
93
+ this.maxBatchItems,
94
+ this.inFlightBytes,
95
+ this.initialCreditBytes
96
+ );
97
+ this.inFlightBytes += batch.chargeBytes;
98
+ this.queue.push(batch);
99
+ this.waiting?.resolve();
100
+ }
101
+ onMessage = ({ data }) => {
102
+ try {
103
+ if (!isRecord(data) || data.version !== VERSION) {
104
+ throw protocolError("Invalid Worker stream producer message.");
105
+ }
106
+ switch (data.type) {
107
+ case "batch":
108
+ this.acceptBatch(data);
109
+ return;
110
+ case "end": {
111
+ this.remoteEnded = true;
112
+ this.detach();
113
+ this.port.close();
114
+ this.waiting?.resolve();
115
+ const { onRemoteEnd } = this;
116
+ onRemoteEnd?.();
117
+ return;
118
+ }
119
+ case "error":
120
+ if (isWireError(data.error)) {
121
+ this.finish({ error: deserialiseError(data.error) }, false);
122
+ return;
123
+ }
124
+ }
125
+ throw protocolError("Invalid Worker stream producer message type or error.");
126
+ } catch (error) {
127
+ this.finish({ error });
128
+ }
129
+ };
130
+ onMessageError = () => {
131
+ this.finish({ error: protocolError("Could not decode Worker stream producer message.") });
132
+ };
133
+ onClose = () => {
134
+ if (!this.remoteEnded) {
135
+ this.finish({ error: new RpcError("disconnected", "Worker stream port closed unexpectedly.") }, false);
136
+ }
137
+ };
138
+ onAbort = () => {
139
+ this.finish({ error: disconnected(this.signal) });
140
+ };
141
+ sendCredit(bytes) {
142
+ try {
143
+ const message = { version: VERSION, type: "credit", bytes };
144
+ this.port.postMessage(message);
145
+ } catch (error) {
146
+ this.finish({ error });
147
+ }
148
+ }
149
+ async *read() {
150
+ while (this.outcome === void 0) {
151
+ const batch = this.queue.shift();
152
+ if (batch !== void 0) {
153
+ yield batch.items;
154
+ if (this.outcome === void 0 && !this.remoteEnded) {
155
+ this.inFlightBytes -= batch.chargeBytes;
156
+ this.sendCredit(batch.chargeBytes);
157
+ }
158
+ } else if (this.remoteEnded) {
159
+ return;
160
+ } else {
161
+ this.waiting = promiseWithResolvers();
162
+ await this.waiting.promise;
163
+ this.waiting = void 0;
164
+ }
165
+ }
166
+ if (this.outcome !== "return") {
167
+ throw this.outcome.error;
168
+ }
169
+ }
170
+ }
171
+ function readWorkerPushStream(options) {
172
+ const reader = new WorkerPushStreamReader(options);
173
+ reader.start();
174
+ return stopGeneratorOnReturn(reader.read(), () => reader.cancel());
175
+ }
176
+ export {
177
+ WorkerPushStreamReader,
178
+ readWorkerPushStream
179
+ };