@vrtmrz/livesync-commonlib 0.7.0 → 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 (62) hide show
  1. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  2. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  3. package/dist/managers/EntryManager/EntryManagerImpls.js +76 -4
  4. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  5. package/dist/managers/StorageEventManager/admission.js +13 -3
  6. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  7. package/dist/managers/StorageEventManager/processing.js +3 -3
  8. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  9. package/dist/managers/StorageEventManager/queue.js +70 -30
  10. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  11. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  12. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  13. package/dist/managers/StorageEventManager/state.js +9 -7
  14. package/dist/managers/StorageEventManager.d.ts +6 -0
  15. package/dist/managers/StorageEventManager.js +135 -18
  16. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  17. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  18. package/dist/managers/adapters/index.d.ts +1 -1
  19. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
  20. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
  21. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
  22. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
  23. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
  24. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  25. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  26. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  27. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  28. package/dist/worker/WorkerPushStreamReader.js +179 -0
  29. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  30. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  31. package/dist/worker/bg.worker.js +2 -16
  32. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  33. package/dist/worker/bg.worker.splitting.js +46 -47
  34. package/dist/worker/bgWorker.d.ts +8 -14
  35. package/dist/worker/bgWorker.direct.d.ts +5 -28
  36. package/dist/worker/bgWorker.direct.js +32 -2
  37. package/dist/worker/bgWorker.errors.d.ts +1 -0
  38. package/dist/worker/bgWorker.errors.js +12 -0
  39. package/dist/worker/bgWorker.js +716 -296
  40. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  41. package/dist/worker/bgWorker.splitting.js +115 -107
  42. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  43. package/dist/worker/outOfBandCancelIterator.js +8 -0
  44. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  45. package/dist/worker/serveBackgroundWorker.js +35 -0
  46. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  47. package/dist/worker/splitConnectionTracker.js +73 -0
  48. package/dist/worker/splitGate.d.ts +19 -0
  49. package/dist/worker/splitGate.js +71 -0
  50. package/dist/worker/universalTypes.d.ts +0 -30
  51. package/dist/worker/universalTypes.js +0 -4
  52. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  53. package/dist/worker/workerPushStreamProtocol.js +143 -0
  54. package/docs/development.md +6 -0
  55. package/docs/storage-events-and-reflection.md +30 -2
  56. package/package.json +1 -1
  57. package/dist/worker/bg.common.d.ts +0 -2
  58. package/dist/worker/bg.common.js +0 -6
  59. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  60. package/dist/worker/bg.worker.encryption.js +0 -30
  61. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  62. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -64,6 +64,57 @@ async function deleteProvenance(ctx, path) {
64
64
  ctx.host.log(ex, LOG_LEVEL_VERBOSE);
65
65
  }
66
66
  }
67
+ async function captureRenameProvenance(ctx, oldPath, targetPath) {
68
+ if (!ctx.provenance) return void 0;
69
+ const oldKey = getProvenancePath(ctx, oldPath);
70
+ const expectedNewKey = getProvenancePath(ctx, targetPath);
71
+ if (oldKey === expectedNewKey) return void 0;
72
+ try {
73
+ const sourceRecord = await readProvenanceSnapshot(ctx, oldPath, true);
74
+ let destinationBefore = await readProvenanceSnapshot(ctx, targetPath, true);
75
+ if (!sourceRecord && destinationBefore !== void 0) {
76
+ await ctx.provenance.delete(expectedNewKey);
77
+ destinationBefore = void 0;
78
+ }
79
+ return { oldPath, oldKey, expectedNewKey, sourceRecord, destinationBefore };
80
+ } catch (ex) {
81
+ ctx.host.log(
82
+ `Could not prepare file reflection provenance before renaming ${oldPath} -> ${targetPath}`,
83
+ LOG_LEVEL_VERBOSE
84
+ );
85
+ ctx.host.log(ex, LOG_LEVEL_VERBOSE);
86
+ return false;
87
+ }
88
+ }
89
+ async function commitRenamedProvenance(ctx, snapshot, newPath) {
90
+ if (!ctx.provenance) return true;
91
+ const newKey = getProvenancePath(ctx, newPath);
92
+ if (newKey !== snapshot.expectedNewKey) return false;
93
+ if (snapshot.oldKey === newKey) return true;
94
+ try {
95
+ const destinationAfter = await readProvenanceSnapshot(ctx, newPath, true);
96
+ if (!sameProvenance(destinationAfter, snapshot.destinationBefore)) {
97
+ ctx.host.log(
98
+ `Preserving concurrent file reflection provenance update for ${newPath} after rename from ${snapshot.oldPath}`,
99
+ LOG_LEVEL_VERBOSE
100
+ );
101
+ return false;
102
+ }
103
+ if (snapshot.sourceRecord) {
104
+ await ctx.provenance.set(newKey, snapshot.sourceRecord);
105
+ await deleteProvenance(ctx, snapshot.oldPath);
106
+ return true;
107
+ }
108
+ return true;
109
+ } catch (ex) {
110
+ ctx.host.log(
111
+ `Could not update file reflection provenance after renaming ${snapshot.oldPath} -> ${newPath}`,
112
+ LOG_LEVEL_VERBOSE
113
+ );
114
+ ctx.host.log(ex, LOG_LEVEL_VERBOSE);
115
+ return false;
116
+ }
117
+ }
67
118
  async function findUniqueContentRevision(ctx, file) {
68
119
  try {
69
120
  const revisions = await ctx.host.db().findContentRevisions(file, file.body);
@@ -188,7 +239,9 @@ async function inspectCurrentFileProvenance(ctx, path, revision) {
188
239
  });
189
240
  }
190
241
  export {
242
+ captureRenameProvenance,
191
243
  classifyStorageContent,
244
+ commitRenamedProvenance,
192
245
  contentEvidence,
193
246
  currentStorageSnapshotMatches,
194
247
  deleteProvenance,
@@ -8,7 +8,10 @@ import {
8
8
  import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
9
9
  import { infoToStub, isFolderInfo, getParentPath } from "./storage.js";
10
10
  import {
11
+ captureRenameProvenance,
12
+ commitRenamedProvenance,
11
13
  deleteProvenance,
14
+ getProvenancePath,
12
15
  contentEvidence,
13
16
  currentStorageSnapshotMatches,
14
17
  sameProvenance,
@@ -209,6 +212,19 @@ async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force
209
212
  );
210
213
  }
211
214
  async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, force, allowExistingConflicts, incomingRetry, operation) {
215
+ if (existDoc.path !== path) {
216
+ const [existingDocumentId, targetDocumentId] = await Promise.all([
217
+ ctx.path.path2id(existDoc.path),
218
+ ctx.path.path2id(path)
219
+ ]);
220
+ if (existingDocumentId !== targetDocumentId) {
221
+ ctx.host.log(
222
+ `Refusing to delete ${existDoc.path} while applying deletion for the distinct path ${path}`,
223
+ LOG_LEVEL_NOTICE
224
+ );
225
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
226
+ }
227
+ }
212
228
  let safeDeletionSnapshot;
213
229
  if (!force && !settings.writeDocumentsIfConflicted) {
214
230
  let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry, void 0);
@@ -259,11 +275,37 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
259
275
  throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
260
276
  }
261
277
  }
278
+ const observedPath = safeDeletionSnapshot?.file.path ?? existDoc.path;
279
+ if (observedPath !== path) {
280
+ if (safeDeletionSnapshot) {
281
+ if (!sameProvenance(await readProvenanceSnapshot(ctx, observedPath), safeDeletionSnapshot.revision)) {
282
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
283
+ }
284
+ const resolvedForRead = await ctx.host.storage().getStub(path);
285
+ if (!resolvedForRead || isFolderInfo(resolvedForRead) || resolvedForRead.path !== observedPath) {
286
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
287
+ }
288
+ const readResolved = await ctx.host.readFileFromStub(resolvedForRead);
289
+ if (readResolved.path !== observedPath || readResolved.stat.mtime !== safeDeletionSnapshot.file.stat.mtime || readResolved.stat.size !== safeDeletionSnapshot.file.stat.size || !await isDocContentSame(readResolved.body, safeDeletionSnapshot.file.body)) {
290
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
291
+ }
292
+ }
293
+ const resolvedTarget = await ctx.host.storage().getStub(path);
294
+ if (!resolvedTarget || isFolderInfo(resolvedTarget) || resolvedTarget.path !== observedPath || safeDeletionSnapshot && (resolvedTarget.stat.mtime !== safeDeletionSnapshot.file.stat.mtime || resolvedTarget.stat.size !== safeDeletionSnapshot.file.stat.size)) {
295
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
296
+ }
297
+ }
262
298
  if (operation?.checkpoint?.() === false) {
263
299
  return FILE_REFLECTION_CANCELLED;
264
300
  }
265
301
  await ctx.host.storage().deleteVaultItem(path);
266
- await deleteProvenance(ctx, path);
302
+ const clearedKeys = /* @__PURE__ */ new Set();
303
+ for (const candidate of [observedPath, existDoc.path, path]) {
304
+ const key = getProvenancePath(ctx, candidate);
305
+ if (clearedKeys.has(key)) continue;
306
+ clearedKeys.add(key);
307
+ await deleteProvenance(ctx, candidate);
308
+ }
267
309
  return FILE_REFLECTION_COMPLETED;
268
310
  }
269
311
  async function reconcileStoragePath(ctx, existDoc, path, settings) {
@@ -291,12 +333,26 @@ async function reconcileStoragePath(ctx, existDoc, path, settings) {
291
333
  );
292
334
  return false;
293
335
  }
336
+ const oldPath = existDoc.path;
337
+ const renameProvenance = await captureRenameProvenance(ctx, oldPath, path);
338
+ if (renameProvenance === false) {
339
+ return false;
340
+ }
294
341
  const renamedFile = await ctx.host.storage().renameFile(existDoc, path);
295
342
  if (!renamedFile) {
296
- ctx.host.log(`Could not apply the stored filename case: ${existDoc.path} -> ${path}`, LOG_LEVEL_NOTICE);
343
+ ctx.host.log(`Could not apply the stored filename case: ${oldPath} -> ${path}`, LOG_LEVEL_NOTICE);
344
+ return false;
345
+ }
346
+ if (getProvenancePath(ctx, renamedFile.path) !== getProvenancePath(ctx, path)) {
347
+ ctx.host.log(
348
+ `Could not align renamed filename identity: ${oldPath} -> ${renamedFile.path} (expected ${path})`,
349
+ LOG_LEVEL_NOTICE
350
+ );
351
+ return false;
352
+ }
353
+ if (renameProvenance && !await commitRenamedProvenance(ctx, renameProvenance, renamedFile.path)) {
297
354
  return false;
298
355
  }
299
- await deleteProvenance(ctx, existDoc.path);
300
356
  existDoc = renamedFile;
301
357
  }
302
358
  return existDoc;
@@ -4,8 +4,8 @@ import { ServiceBase, type ServiceContext } from "./ServiceBase.js";
4
4
  import type { KeyValueDatabase, KeyValueDatabaseFactory } from "../../interfaces/KeyValueDatabase.js";
5
5
  import type { InjectableDatabaseEventService } from "../implements/injectable/InjectableDatabaseEventService.js";
6
6
  import type { AppLifecycleServiceBase } from "../implements/injectable/InjectableAppLifecycleService.js";
7
- export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContext> {
8
- openKeyValueDatabase: KeyValueDatabaseFactory;
7
+ export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContext, TDatabase extends KeyValueDatabase = KeyValueDatabase> {
8
+ openKeyValueDatabase: KeyValueDatabaseFactory<TDatabase>;
9
9
  databaseEvents: InjectableDatabaseEventService<T>;
10
10
  vault: IVaultService;
11
11
  appLifecycle: AppLifecycleServiceBase<T>;
@@ -15,13 +15,13 @@ export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContex
15
15
  * The KeyValueDBService provides methods for managing the local key-value database.
16
16
  * Please note that each event of database lifecycle is handled in DatabaseEventService.
17
17
  */
18
- export declare abstract class KeyValueDBService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IKeyValueDBService {
18
+ export declare abstract class KeyValueDBService<T extends ServiceContext = ServiceContext, TDatabase extends KeyValueDatabase = KeyValueDatabase> extends ServiceBase<T> implements IKeyValueDBService {
19
19
  private _kvDB;
20
20
  private databaseKey;
21
21
  private readonly lifecycleLock;
22
22
  private _simpleStore;
23
23
  get simpleStore(): SimpleStore<unknown, any>;
24
- get kvDB(): KeyValueDatabase;
24
+ get kvDB(): TDatabase;
25
25
  private databaseEvents;
26
26
  private vault;
27
27
  private appLifecycle;
@@ -33,7 +33,7 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
33
33
  private openSelectedDatabase;
34
34
  private openKeyValueDB;
35
35
  private _everyOnloadAfterLoadSettings;
36
- constructor(context: T, dependencies: KeyValueDBDependencies<T>);
36
+ constructor(context: T, dependencies: KeyValueDBDependencies<T, TDatabase>);
37
37
  /**
38
38
  * Create an inert namespaced handle over the service's current database.
39
39
  * @param kind - Namespace identifier; stored keys receive this identifier and a trailing hyphen.
@@ -48,6 +48,6 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
48
48
  set: (key: string, value: unknown) => Promise<void>;
49
49
  delete: (key: string) => Promise<void>;
50
50
  keys: (from: string | undefined, to: string | undefined, count?: number) => Promise<string[]>;
51
- readonly db: Promise<KeyValueDatabase>;
51
+ readonly db: Promise<Awaited<TDatabase>>;
52
52
  };
53
53
  }
@@ -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>;