@flowscripter/pluggable-io-framework 1.1.5 → 1.2.1

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.
@@ -1,7 +1,60 @@
1
1
  import { adaptReadableStream, identityChunkConverter, } from "@flowscripter/pluggable-io-framework-api";
2
2
  import { chunkLength } from "./chunkLength.js";
3
+ import { defaultConcurrencyLimiter, mapAsyncIterableConcurrently, } from "./ConcurrencyLimiter.js";
4
+ import { withRetry } from "./withRetry.js";
3
5
  const DEFAULT_MULTIPART_THRESHOLD = 64 * 1024 * 1024;
4
- async function streamingTransfer(source, sourcePath, sink, destPath, operationId, options, totalBytes) {
6
+ const DEFAULT_PART_SIZE = 8 * 1024 * 1024;
7
+ const DEFAULT_RETRY = { maxRetries: 3 };
8
+ const UNCONSTRAINED_PART_SIZE = {
9
+ minPartSize: 0,
10
+ maxPartSize: Infinity,
11
+ maxParts: Infinity,
12
+ defaultPartSize: DEFAULT_PART_SIZE,
13
+ };
14
+ /** Wraps `hooks` so any `onProgress` event passing through gets `parentOperationId` filled in, unless the emitter already set one (nested hierarchy). */
15
+ function withParentOperationId(hooks, parentOperationId) {
16
+ if (!hooks || parentOperationId === undefined) {
17
+ return hooks ?? {};
18
+ }
19
+ return {
20
+ ...hooks,
21
+ onProgress: hooks.onProgress
22
+ ? (event) => hooks.onProgress?.({ parentOperationId, ...event })
23
+ : undefined,
24
+ };
25
+ }
26
+ function joinPath(base, relative) {
27
+ if (relative === "")
28
+ return base;
29
+ if (base === "")
30
+ return relative;
31
+ return `${base.replace(/\/+$/, "")}/${relative}`;
32
+ }
33
+ /**
34
+ * Reconciles `source`'s and `sink`'s {@link PartSizeConstraints} for a
35
+ * transfer of `totalSize` bytes into a single part size satisfying both.
36
+ * Returns `undefined` when the bounds are mutually infeasible (source's
37
+ * minimum exceeds sink's maximum) - the caller should fall back to plain
38
+ * streaming rather than throwing.
39
+ */
40
+ function negotiatePartSize(source, sink, totalSize) {
41
+ const sourceConstraints = source.getPartSizeConstraints?.(totalSize) ?? UNCONSTRAINED_PART_SIZE;
42
+ const sinkConstraints = sink.getPartSizeConstraints?.(totalSize) ?? UNCONSTRAINED_PART_SIZE;
43
+ const minPartSize = Math.max(sourceConstraints.minPartSize, sinkConstraints.minPartSize);
44
+ const maxPartSize = Math.min(sourceConstraints.maxPartSize, sinkConstraints.maxPartSize);
45
+ const maxParts = Math.min(sourceConstraints.maxParts, sinkConstraints.maxParts);
46
+ if (minPartSize > maxPartSize) {
47
+ return undefined;
48
+ }
49
+ const byMaxParts = Math.ceil(totalSize / maxParts);
50
+ const candidate = Math.max(minPartSize, sourceConstraints.defaultPartSize, sinkConstraints.defaultPartSize, byMaxParts);
51
+ return Math.min(candidate, maxPartSize);
52
+ }
53
+ function canUseMultipart(source, sink) {
54
+ return (typeof source.getMultipartReader === "function" && typeof sink.getMultipartWriter === "function");
55
+ }
56
+ async function streamingTransfer(source, sourcePath, sink, destPath, operationId, parentOperationId, options, totalBytes) {
57
+ const hooks = withParentOperationId(options.telemetry, parentOperationId);
5
58
  const readable = await source.getReadableStream(sourcePath);
6
59
  const writable = await sink.getWritableStream(destPath);
7
60
  // The source/sink kind mismatch is decided ONCE here, not per chunk.
@@ -16,7 +69,7 @@ async function streamingTransfer(source, sourcePath, sink, destPath, operationId
16
69
  break;
17
70
  await writer.write(value);
18
71
  bytesProcessed += chunkLength(value);
19
- options.telemetry?.onProgress?.({ operationId, type: "copy", bytesProcessed, totalBytes });
72
+ hooks.onProgress?.({ operationId, type: "copy", bytesProcessed, totalBytes });
20
73
  }
21
74
  await writer.close();
22
75
  }
@@ -25,78 +78,200 @@ async function streamingTransfer(source, sourcePath, sink, destPath, operationId
25
78
  throw error;
26
79
  }
27
80
  }
28
- async function multipartTransfer(source, sourcePath, sink, destPath, operationId, options, totalBytes) {
81
+ async function multipartTransfer(source, sourcePath, sink, destPath, operationId, parentOperationId, partSize, limiter, options, totalBytes) {
82
+ const hooks = withParentOperationId(options.telemetry, parentOperationId);
29
83
  let bytesProcessed = 0;
30
- const writer = sink.getMultipartWriter(destPath);
31
- async function* transferParts() {
32
- for await (const part of source.getMultipartReader(sourcePath)) {
33
- // Kind mismatch decided once per part, not once per chunk within it.
34
- const adaptedStream = adaptReadableStream(part.stream, part.kind, sink.kind, options.chunkConverter ?? identityChunkConverter);
35
- const reader = adaptedStream.getReader();
36
- const chunks = [];
37
- for (;;) {
38
- const { done, value } = await reader.read();
39
- if (done)
40
- break;
41
- chunks.push(value);
42
- bytesProcessed += chunkLength(value);
43
- options.telemetry?.onProgress?.({ operationId, type: "copy", bytesProcessed, totalBytes });
44
- }
45
- yield {
46
- index: part.index,
47
- offset: part.offset,
48
- kind: sink.kind,
49
- stream: new ReadableStream({
50
- start(controller) {
51
- for (const chunk of chunks)
52
- controller.enqueue(chunk);
53
- controller.close();
54
- },
55
- }),
56
- complete: () => part.complete(),
57
- };
84
+ async function transferPart(sourcePart) {
85
+ const partOperationId = crypto.randomUUID();
86
+ // Kind mismatch decided once per part, not once per chunk within it.
87
+ const adaptedStream = adaptReadableStream(sourcePart.stream, sourcePart.kind, sink.kind, options.chunkConverter ?? identityChunkConverter);
88
+ const reader = adaptedStream.getReader();
89
+ const chunks = [];
90
+ let partBytesProcessed = 0;
91
+ for (;;) {
92
+ const { done, value } = await reader.read();
93
+ if (done)
94
+ break;
95
+ chunks.push(value);
96
+ const length = chunkLength(value);
97
+ partBytesProcessed += length;
98
+ bytesProcessed += length;
99
+ hooks.onProgress?.({
100
+ operationId: partOperationId,
101
+ parentOperationId: operationId,
102
+ type: "copy",
103
+ bytesProcessed: partBytesProcessed,
104
+ });
105
+ hooks.onProgress?.({ operationId, type: "copy", bytesProcessed, totalBytes });
58
106
  }
107
+ return {
108
+ index: sourcePart.index,
109
+ offset: sourcePart.offset,
110
+ kind: sink.kind,
111
+ stream: new ReadableStream({
112
+ start(controller) {
113
+ for (const chunk of chunks)
114
+ controller.enqueue(chunk);
115
+ controller.close();
116
+ },
117
+ }),
118
+ complete: () => sourcePart.complete(),
119
+ };
120
+ }
121
+ const writer = sink.getMultipartWriter(destPath, partSize);
122
+ const transferredParts = mapAsyncIterableConcurrently(source.getMultipartReader(sourcePath, partSize), transferPart, limiter);
123
+ await writer.write(transferredParts);
124
+ }
125
+ async function copySingle(source, sourcePath, sink, destPath, options, parentOperationId, properties) {
126
+ const operationId = crypto.randomUUID();
127
+ if (source.canDirectTransfer?.(sink) && source.directCopy) {
128
+ await source.directCopy(sourcePath, destPath, {
129
+ operationId,
130
+ hooks: withParentOperationId(options.telemetry, parentOperationId),
131
+ });
132
+ return;
133
+ }
134
+ const threshold = options.multipartThreshold ?? DEFAULT_MULTIPART_THRESHOLD;
135
+ const size = properties.size;
136
+ const partSize = size !== undefined && size >= threshold && canUseMultipart(source, sink)
137
+ ? negotiatePartSize(source, sink, size)
138
+ : undefined;
139
+ const limiter = options.concurrencyLimiter ?? defaultConcurrencyLimiter;
140
+ const retryOptions = options.retry ?? DEFAULT_RETRY;
141
+ await withRetry(async () => {
142
+ if (partSize !== undefined) {
143
+ await multipartTransfer(source, sourcePath, sink, destPath, operationId, parentOperationId, partSize, limiter, options, size);
144
+ }
145
+ else {
146
+ await streamingTransfer(source, sourcePath, sink, destPath, operationId, parentOperationId, options, size);
147
+ }
148
+ }, retryOptions);
149
+ }
150
+ async function moveSingle(source, sourcePath, sink, destPath, options, parentOperationId, properties) {
151
+ if (source.canDirectTransfer?.(sink) && source.directMove) {
152
+ const operationId = crypto.randomUUID();
153
+ await source.directMove(sourcePath, destPath, {
154
+ operationId,
155
+ hooks: withParentOperationId(options.telemetry, parentOperationId),
156
+ });
157
+ return;
59
158
  }
60
- await writer.write(transferParts());
159
+ await copySingle(source, sourcePath, sink, destPath, options, parentOperationId, properties);
160
+ await withRetry(() => source.delete(sourcePath), options.retry ?? DEFAULT_RETRY);
61
161
  }
62
- function canUseMultipart(source, sink, size, threshold) {
63
- return (size !== undefined &&
64
- size >= threshold &&
65
- typeof source.getMultipartReader === "function" &&
66
- typeof sink.getMultipartWriter === "function");
162
+ /**
163
+ * Resolves the effective destination root for a recursive transfer,
164
+ * following `cp -r`/`mv` semantics: a destination that doesn't exist becomes
165
+ * the copy itself; an existing folder gets the source nested inside it as
166
+ * `dest/<source-basename>`; an existing file is rejected.
167
+ */
168
+ async function resolveRecursiveDestRoot(sourcePath, sink, destPath) {
169
+ let destProperties;
170
+ try {
171
+ destProperties = await sink.getProperties(destPath);
172
+ }
173
+ catch {
174
+ destProperties = undefined;
175
+ }
176
+ if (destProperties === undefined) {
177
+ return destPath;
178
+ }
179
+ if (!destProperties.isFolder) {
180
+ throw new Error(`Cannot copy/move folder "${sourcePath}" onto existing file "${destPath}"`);
181
+ }
182
+ const baseName = sourcePath.replace(/\/+$/, "").split("/").pop() || sourcePath;
183
+ return joinPath(destPath, baseName);
184
+ }
185
+ async function recursiveTransfer(source, sourcePath, sink, destPath, options, mode) {
186
+ if (source.canDirectTransfer?.(sink) && source.supportsRecursiveDirectTransfer) {
187
+ const directFn = mode === "copy" ? source.directCopy : source.directMove;
188
+ if (directFn) {
189
+ const operationId = crypto.randomUUID();
190
+ await directFn(sourcePath, destPath, { operationId, hooks: options.telemetry ?? {} });
191
+ return;
192
+ }
193
+ }
194
+ const resolvedDestRoot = await resolveRecursiveDestRoot(sourcePath, sink, destPath);
195
+ const recursiveOperationId = crypto.randomUUID();
196
+ const limiter = options.concurrencyLimiter ?? defaultConcurrencyLimiter;
197
+ let discovered = 0;
198
+ let completed = 0;
199
+ const reportProgress = () => {
200
+ options.telemetry?.onProgress?.({
201
+ operationId: recursiveOperationId,
202
+ type: mode,
203
+ bytesProcessed: 0,
204
+ itemsProcessed: completed,
205
+ totalItems: discovered,
206
+ });
207
+ };
208
+ async function processEntry(entry) {
209
+ discovered += 1;
210
+ reportProgress();
211
+ const entrySourcePath = joinPath(sourcePath, entry.path);
212
+ const entryDestPath = joinPath(resolvedDestRoot, entry.path);
213
+ if (entry.properties.isFolder) {
214
+ await sink.createFolder?.(entryDestPath);
215
+ }
216
+ else if (mode === "copy") {
217
+ await copySingle(source, entrySourcePath, sink, entryDestPath, options, recursiveOperationId, entry.properties);
218
+ }
219
+ else if (source.canDirectTransfer?.(sink) && source.directMove) {
220
+ // A per-file directMove deletes its source atomically as part of the
221
+ // provider's own operation - safe to do immediately. The non-direct
222
+ // case below must NOT delete per entry: only after every entry
223
+ // succeeds does the caller delete the whole source root once.
224
+ const operationId = crypto.randomUUID();
225
+ await source.directMove(entrySourcePath, entryDestPath, {
226
+ operationId,
227
+ hooks: withParentOperationId(options.telemetry, recursiveOperationId),
228
+ });
229
+ }
230
+ else {
231
+ await copySingle(source, entrySourcePath, sink, entryDestPath, options, recursiveOperationId, entry.properties);
232
+ }
233
+ completed += 1;
234
+ reportProgress();
235
+ }
236
+ for await (const _entry of mapAsyncIterableConcurrently(source.list(sourcePath, { recursive: true }), processEntry, limiter)) {
237
+ // work happens inside processEntry - nothing to do with the (void) result.
238
+ }
239
+ if (mode === "move") {
240
+ await withRetry(() => source.delete(sourcePath), options.retry ?? DEFAULT_RETRY);
241
+ }
67
242
  }
68
243
  /**
69
- * Copies `sourcePath` on `source` to `destPath` on `sink`.
244
+ * Copies `sourcePath` on `source` to `destPath` on `sink`. When `sourcePath`
245
+ * is a folder, recurses: uses a folder-aware `directCopy` when the source
246
+ * declares `supportsRecursiveDirectTransfer`, otherwise lists the folder and
247
+ * transfers each entry (bounded by `options.concurrencyLimiter`), following
248
+ * `cp -r` target semantics (see {@link resolveRecursiveDestRoot}).
70
249
  *
71
- * Uses `source.directCopy` when `source.canDirectTransfer?.(sink)` reports
72
- * eligibility (same-provider direct transfer). Otherwise falls back to
73
- * multipart transfer (when both sides support it and size crosses
74
- * `options.multipartThreshold`) or plain streaming.
250
+ * For a single file: uses `source.directCopy` when
251
+ * `source.canDirectTransfer?.(sink)` reports eligibility. Otherwise falls
252
+ * back to multipart transfer (when both sides support it, size crosses
253
+ * `options.multipartThreshold`, and part-size negotiation succeeds) or plain
254
+ * streaming - retried per `options.retry` on `TransientIOError`.
75
255
  */
76
256
  export async function copy(source, sourcePath, sink, destPath, options = {}) {
77
- const operationId = crypto.randomUUID();
78
- if (source.canDirectTransfer?.(sink) && source.directCopy) {
79
- await source.directCopy(sourcePath, destPath);
80
- return;
81
- }
82
257
  const properties = await source.getProperties(sourcePath);
83
- const threshold = options.multipartThreshold ?? DEFAULT_MULTIPART_THRESHOLD;
84
- if (canUseMultipart(source, sink, properties.size, threshold)) {
85
- await multipartTransfer(source, sourcePath, sink, destPath, operationId, options, properties.size);
258
+ if (properties.isFolder) {
259
+ await recursiveTransfer(source, sourcePath, sink, destPath, options, "copy");
86
260
  return;
87
261
  }
88
- await streamingTransfer(source, sourcePath, sink, destPath, operationId, options, properties.size);
262
+ await copySingle(source, sourcePath, sink, destPath, options, undefined, properties);
89
263
  }
90
264
  /**
91
- * Moves `sourcePath` on `source` to `destPath` on `sink`. Uses
92
- * `source.directMove` when eligible, otherwise performs a {@link copy}
93
- * followed by deleting the source item.
265
+ * Moves `sourcePath` on `source` to `destPath` on `sink`. Folder handling
266
+ * mirrors {@link copy}. For a single file, uses `source.directMove` when
267
+ * eligible, otherwise performs a {@link copy} followed by deleting the
268
+ * source item (each retried independently per `options.retry`).
94
269
  */
95
270
  export async function move(source, sourcePath, sink, destPath, options = {}) {
96
- if (source.canDirectTransfer?.(sink) && source.directMove) {
97
- await source.directMove(sourcePath, destPath);
271
+ const properties = await source.getProperties(sourcePath);
272
+ if (properties.isFolder) {
273
+ await recursiveTransfer(source, sourcePath, sink, destPath, options, "move");
98
274
  return;
99
275
  }
100
- await copy(source, sourcePath, sink, destPath, options);
101
- await source.delete(sourcePath);
276
+ await moveSingle(source, sourcePath, sink, destPath, options, undefined, properties);
102
277
  }
@@ -0,0 +1,13 @@
1
+ export interface RetryOptions {
2
+ readonly maxRetries: number;
3
+ /** Delay in ms before the given retry attempt (1-based). Defaults to `min(200 * 2^attempt, 5000)`. */
4
+ readonly backoffMs?: (attempt: number) => number;
5
+ }
6
+ /**
7
+ * Runs `fn`, retrying only on `TransientIOError` up to `options.maxRetries`
8
+ * times with a delay between attempts. Any other error - including a plain
9
+ * `Error` a provider hasn't wrapped - is treated as non-retryable and
10
+ * rethrown immediately.
11
+ */
12
+ export declare function withRetry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T>;
13
+ //# sourceMappingURL=withRetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withRetry.d.ts","sourceRoot":"","sources":["../../src/withRetry.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,sGAAsG;IACtG,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,MAAM,CAAC;CAClD;AAMD;;;;;GAKG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,CAAC,CAAC,CAc1F"}
@@ -0,0 +1,26 @@
1
+ import { TransientIOError } from "@flowscripter/pluggable-io-framework-api";
2
+ function defaultBackoffMs(attempt) {
3
+ return Math.min(200 * 2 ** attempt, 5000);
4
+ }
5
+ /**
6
+ * Runs `fn`, retrying only on `TransientIOError` up to `options.maxRetries`
7
+ * times with a delay between attempts. Any other error - including a plain
8
+ * `Error` a provider hasn't wrapped - is treated as non-retryable and
9
+ * rethrown immediately.
10
+ */
11
+ export async function withRetry(fn, options) {
12
+ const backoffMs = options.backoffMs ?? defaultBackoffMs;
13
+ let attempt = 0;
14
+ for (;;) {
15
+ try {
16
+ return await fn();
17
+ }
18
+ catch (error) {
19
+ if (!(error instanceof TransientIOError) || attempt >= options.maxRetries) {
20
+ throw error;
21
+ }
22
+ attempt += 1;
23
+ await new Promise((resolve) => setTimeout(resolve, backoffMs(attempt)));
24
+ }
25
+ }
26
+ }
package/index.ts CHANGED
@@ -1,4 +1,6 @@
1
+ export * from "./src/ConcurrencyLimiter.ts";
1
2
  export * from "./src/ProviderRegistry.ts";
2
3
  export * from "./src/copyMove.ts";
3
4
  export * from "./src/decorators/locallyCached.ts";
4
5
  export * from "./src/decorators/seekable.ts";
6
+ export * from "./src/withRetry.ts";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowscripter/pluggable-io-framework",
3
- "version": "1.1.5",
3
+ "version": "1.2.1",
4
4
  "description": "A pluggable source/sink IO framework using https://github.com/flowscripter/dynamic-plugin-framework",
5
5
  "keywords": [
6
6
  "bun",
@@ -40,8 +40,8 @@
40
40
  "test": "bun test"
41
41
  },
42
42
  "dependencies": {
43
- "@flowscripter/dynamic-plugin-framework": "^2.2.6",
44
- "@flowscripter/pluggable-io-framework-api": "^1.0.9"
43
+ "@flowscripter/dynamic-plugin-framework": "^2.2.8",
44
+ "@flowscripter/pluggable-io-framework-api": "^1.1.1"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/bun": "^1.4.2",
@@ -0,0 +1,178 @@
1
+ const DEFAULT_MAX_CONCURRENCY = 4;
2
+
3
+ /**
4
+ * A semaphore bounding how many `run()` callbacks execute at once. A single
5
+ * shared instance (see {@link defaultConcurrencyLimiter}) enforces its cap
6
+ * *globally* across concurrently invoked `copy()`/`move()` calls, not just
7
+ * within one call - two folder copies started at the same time and sharing
8
+ * a limiter will never together exceed its `maxConcurrency`.
9
+ */
10
+ export class ConcurrencyLimiter {
11
+ #maxConcurrency: number;
12
+ #active = 0;
13
+ #queue: (() => void)[] = [];
14
+
15
+ public constructor(maxConcurrency: number) {
16
+ ConcurrencyLimiter.#validate(maxConcurrency);
17
+ this.#maxConcurrency = maxConcurrency;
18
+ }
19
+
20
+ public get maxConcurrency(): number {
21
+ return this.#maxConcurrency;
22
+ }
23
+
24
+ public setMaxConcurrency(maxConcurrency: number): void {
25
+ ConcurrencyLimiter.#validate(maxConcurrency);
26
+ this.#maxConcurrency = maxConcurrency;
27
+ this.#drain();
28
+ }
29
+
30
+ public async run<T>(fn: () => Promise<T>): Promise<T> {
31
+ await this.#acquire();
32
+ try {
33
+ return await fn();
34
+ } finally {
35
+ this.#active -= 1;
36
+ this.#drain();
37
+ }
38
+ }
39
+
40
+ #acquire(): Promise<void> {
41
+ if (this.#active < this.#maxConcurrency) {
42
+ this.#active += 1;
43
+ return Promise.resolve();
44
+ }
45
+ return new Promise((resolve) => {
46
+ this.#queue.push(() => {
47
+ this.#active += 1;
48
+ resolve();
49
+ });
50
+ });
51
+ }
52
+
53
+ #drain(): void {
54
+ while (this.#active < this.#maxConcurrency && this.#queue.length > 0) {
55
+ this.#queue.shift()?.();
56
+ }
57
+ }
58
+
59
+ static #validate(maxConcurrency: number): void {
60
+ if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1) {
61
+ throw new Error(`maxConcurrency must be a positive integer, got ${maxConcurrency}`);
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Process-wide default limiter, used by `copy()`/`move()` whenever
68
+ * `TransferOptions.concurrencyLimiter` is omitted - so any two calls in the
69
+ * same process share one cap unless a caller explicitly opts out with its
70
+ * own instance (e.g. for test isolation).
71
+ */
72
+ export const defaultConcurrencyLimiter = new ConcurrencyLimiter(DEFAULT_MAX_CONCURRENCY);
73
+
74
+ /** Minimal single-consumer async FIFO queue backing {@link mapAsyncIterableConcurrently}. */
75
+ class AsyncChannel<T> implements AsyncIterable<T> {
76
+ #items: T[] = [];
77
+ #waiters: { resolve: (result: IteratorResult<T>) => void; reject: (error: unknown) => void }[] =
78
+ [];
79
+ #closed = false;
80
+ #hasError = false;
81
+ #error: unknown;
82
+
83
+ push(item: T): void {
84
+ const waiter = this.#waiters.shift();
85
+ if (waiter) {
86
+ waiter.resolve({ value: item, done: false });
87
+ } else {
88
+ this.#items.push(item);
89
+ }
90
+ }
91
+
92
+ close(): void {
93
+ this.#closed = true;
94
+ for (const waiter of this.#waiters.splice(0)) {
95
+ if (this.#hasError) {
96
+ waiter.reject(this.#error);
97
+ } else {
98
+ waiter.resolve({ value: undefined as never, done: true });
99
+ }
100
+ }
101
+ }
102
+
103
+ fail(error: unknown): void {
104
+ this.#hasError = true;
105
+ this.#error = error;
106
+ this.close();
107
+ }
108
+
109
+ async #next(): Promise<IteratorResult<T>> {
110
+ if (this.#items.length > 0) {
111
+ return { value: this.#items.shift() as T, done: false };
112
+ }
113
+ if (this.#closed) {
114
+ if (this.#hasError) {
115
+ throw this.#error;
116
+ }
117
+ return { value: undefined as never, done: true };
118
+ }
119
+ return new Promise((resolve, reject) => this.#waiters.push({ resolve, reject }));
120
+ }
121
+
122
+ [Symbol.asyncIterator](): AsyncIterator<T> {
123
+ return { next: () => this.#next() };
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Pulls items from `source` and runs `fn` on each, bounded by `limiter`:
129
+ * exactly `limiter.maxConcurrency` worker loops each pull-then-process one
130
+ * item at a time through `limiter.run`, so at most that many items are ever
131
+ * pulled/in-flight at once (important for sources like a multipart reader
132
+ * where pulling an item eagerly opens a file/network handle). Results are
133
+ * yielded in completion order, not source order. If `fn` throws, no new
134
+ * items are pulled but already-in-flight ones are allowed to finish before
135
+ * the error is rethrown from the returned iterable.
136
+ */
137
+ export function mapAsyncIterableConcurrently<T, R>(
138
+ source: AsyncIterable<T>,
139
+ fn: (item: T) => Promise<R>,
140
+ limiter: ConcurrencyLimiter,
141
+ ): AsyncIterable<R> {
142
+ const channel = new AsyncChannel<R>();
143
+ const iterator = source[Symbol.asyncIterator]();
144
+ let stopped = false;
145
+ let firstError: unknown;
146
+ let errorRecorded = false;
147
+
148
+ async function worker(): Promise<void> {
149
+ for (;;) {
150
+ if (stopped) return;
151
+ const { done, value } = await iterator.next();
152
+ if (done) return;
153
+ try {
154
+ const result = await limiter.run(() => fn(value));
155
+ channel.push(result);
156
+ } catch (error) {
157
+ stopped = true;
158
+ if (!errorRecorded) {
159
+ errorRecorded = true;
160
+ firstError = error;
161
+ }
162
+ return;
163
+ }
164
+ }
165
+ }
166
+
167
+ void (async () => {
168
+ const workerCount = Math.max(1, limiter.maxConcurrency);
169
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
170
+ if (errorRecorded) {
171
+ channel.fail(firstError);
172
+ } else {
173
+ channel.close();
174
+ }
175
+ })();
176
+
177
+ return channel;
178
+ }