@shelby-protocol/sdk 0.3.0 → 0.3.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.
Files changed (106) hide show
  1. package/dist/browser/index.d.ts +12 -3
  2. package/dist/browser/index.mjs +3717 -142
  3. package/dist/core/aptos-explorer.mjs +46 -5
  4. package/dist/core/blobs.mjs +12 -4
  5. package/dist/core/chunk.mjs +58 -9
  6. package/dist/core/clients/ShelbyBlobClient.d.ts +0 -43
  7. package/dist/core/clients/ShelbyBlobClient.mjs +1084 -17
  8. package/dist/core/clients/ShelbyClient.d.ts +12 -2
  9. package/dist/core/clients/ShelbyClient.mjs +2915 -23
  10. package/dist/core/clients/ShelbyClientConfig.mjs +0 -1
  11. package/dist/core/clients/ShelbyMetadataClient.d.ts +0 -18
  12. package/dist/core/clients/ShelbyMetadataClient.mjs +306 -6
  13. package/dist/core/clients/ShelbyMicropaymentChannelClient.d.ts +7 -49
  14. package/dist/core/clients/ShelbyMicropaymentChannelClient.mjs +839 -13
  15. package/dist/core/clients/ShelbyPlacementGroupClient.mjs +307 -8
  16. package/dist/core/clients/ShelbyRPCClient.d.ts +106 -3
  17. package/dist/core/clients/ShelbyRPCClient.mjs +1261 -12
  18. package/dist/core/clients/index.d.ts +2 -1
  19. package/dist/core/clients/index.mjs +3420 -39
  20. package/dist/core/clients/utils.mjs +65 -6
  21. package/dist/core/commitments.mjs +270 -11
  22. package/dist/core/constants.d.ts +2 -2
  23. package/dist/core/constants.mjs +39 -16
  24. package/dist/core/erasure/clay-codes.mjs +129 -4
  25. package/dist/core/erasure/constants.mjs +33 -10
  26. package/dist/core/erasure/default.mjs +191 -9
  27. package/dist/core/erasure/index.mjs +266 -23
  28. package/dist/core/erasure/reed-solomon.mjs +68 -4
  29. package/dist/core/erasure/utils.mjs +0 -2
  30. package/dist/core/errors.mjs +29 -8
  31. package/dist/core/index.d.ts +1 -1
  32. package/dist/core/index.mjs +3711 -142
  33. package/dist/core/layout.mjs +37 -5
  34. package/dist/core/networks.mjs +10 -5
  35. package/dist/core/operations/generated/sdk.d.ts +9 -0
  36. package/dist/core/operations/generated/sdk.mjs +183 -18
  37. package/dist/core/operations/index.mjs +284 -24
  38. package/dist/core/promises.mjs +4 -4
  39. package/dist/core/rpc-responses.mjs +29 -10
  40. package/dist/core/shelby-explorer.mjs +31 -6
  41. package/dist/core/strings.mjs +0 -2
  42. package/dist/core/types/blobs.mjs +0 -1
  43. package/dist/core/types/index.mjs +230 -9
  44. package/dist/core/types/payments.d.ts +6 -6
  45. package/dist/core/types/payments.mjs +230 -5
  46. package/dist/core/types/placement_groups.mjs +0 -1
  47. package/dist/core/types/storage_providers.mjs +0 -1
  48. package/dist/core/utils.mjs +94 -8
  49. package/dist/node/clients/ShelbyNodeClient.d.ts +1 -0
  50. package/dist/node/clients/ShelbyNodeClient.mjs +2919 -24
  51. package/dist/node/clients/index.d.ts +1 -0
  52. package/dist/node/clients/index.mjs +2920 -26
  53. package/dist/node/index.d.ts +1 -1
  54. package/dist/node/index.mjs +3734 -149
  55. package/dist/node/parallel/commitment_worker.d.ts +9 -0
  56. package/dist/node/parallel/commitment_worker.mjs +298 -0
  57. package/dist/node/parallel/commitment_worker_pool.d.ts +35 -0
  58. package/dist/node/parallel/commitment_worker_pool.mjs +286 -0
  59. package/dist/node/parallel/default_commitment_worker_pool.d.ts +24 -0
  60. package/dist/node/parallel/default_commitment_worker_pool.mjs +302 -0
  61. package/dist/node/parallel/index.d.ts +11 -0
  62. package/dist/node/parallel/index.mjs +563 -0
  63. package/dist/node/parallel/parallel_commitments.d.ts +32 -0
  64. package/dist/node/parallel/parallel_commitments.mjs +561 -0
  65. package/dist/node/parallel/worker_pool.d.ts +74 -0
  66. package/dist/node/parallel/worker_pool.mjs +248 -0
  67. package/dist/node/testUtil.mjs +8 -4
  68. package/package.json +6 -2
  69. package/dist/chunk-3NRBHSMQ.mjs +0 -12
  70. package/dist/chunk-5BVSWXQJ.mjs +0 -801
  71. package/dist/chunk-6FJNAUU5.mjs +0 -278
  72. package/dist/chunk-6XSZRDLJ.mjs +0 -375
  73. package/dist/chunk-7P6ASYW6.mjs +0 -9
  74. package/dist/chunk-A4IG6GSE.mjs +0 -21
  75. package/dist/chunk-AD2G3QYD.mjs +0 -0
  76. package/dist/chunk-AUQDI5BS.mjs +0 -43
  77. package/dist/chunk-AY3HBWXA.mjs +0 -51
  78. package/dist/chunk-BDSW5PHM.mjs +0 -37
  79. package/dist/chunk-C6RQ3AEU.mjs +0 -51
  80. package/dist/chunk-CQ6QPIZK.mjs +0 -37
  81. package/dist/chunk-D6GQHO6G.mjs +0 -15
  82. package/dist/chunk-EM67QTMR.mjs +0 -0
  83. package/dist/chunk-I6NG5GNL.mjs +0 -8
  84. package/dist/chunk-JTXYKO3U.mjs +0 -38
  85. package/dist/chunk-KG2TMLEV.mjs +0 -207
  86. package/dist/chunk-M3CP5TFP.mjs +0 -39
  87. package/dist/chunk-M7W43K2Q.mjs +0 -505
  88. package/dist/chunk-MB7C7VQF.mjs +0 -0
  89. package/dist/chunk-MNCQBEMS.mjs +0 -55
  90. package/dist/chunk-MQUVYMNQ.mjs +0 -0
  91. package/dist/chunk-NEO7Z3ZQ.mjs +0 -49
  92. package/dist/chunk-NHWWORCH.mjs +0 -72
  93. package/dist/chunk-OEK24ON7.mjs +0 -135
  94. package/dist/chunk-QQ57OGQ2.mjs +0 -0
  95. package/dist/chunk-RNNJXTX2.mjs +0 -154
  96. package/dist/chunk-S6Q4OG7H.mjs +0 -83
  97. package/dist/chunk-TET3DJEO.mjs +0 -199
  98. package/dist/chunk-UEZNZBJO.mjs +0 -104
  99. package/dist/chunk-V46D5NBW.mjs +0 -11
  100. package/dist/chunk-V4B3GAMQ.mjs +0 -42
  101. package/dist/chunk-WFWRBNTW.mjs +0 -412
  102. package/dist/chunk-WTICJPDB.mjs +0 -0
  103. package/dist/chunk-XNEIWM4O.mjs +0 -0
  104. package/dist/chunk-Z4FZ7W6L.mjs +0 -39
  105. package/dist/chunk-Z7RFCADT.mjs +0 -0
  106. package/dist/chunk-ZHXCVRZX.mjs +0 -0
@@ -0,0 +1,561 @@
1
+ // src/node/parallel/parallel_commitments.ts
2
+ import { Hex as Hex3 } from "@aptos-labs/ts-sdk";
3
+
4
+ // src/core/commitments.ts
5
+ import { Hex as Hex2 } from "@aptos-labs/ts-sdk";
6
+ import { z } from "zod";
7
+
8
+ // src/core/erasure/constants.ts
9
+ var ERASURE_CODE_PARAMS = {
10
+ ["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */]: {
11
+ // total chunks (data + parity)
12
+ erasure_n: 16,
13
+ // data chunks
14
+ erasure_k: 10,
15
+ // helper nodes
16
+ erasure_d: 13,
17
+ // enum index
18
+ enumIndex: 0
19
+ },
20
+ ["ClayCode_4Total_2Data_3Helper" /* ClayCode_4Total_2Data_3Helper */]: {
21
+ // total chunks (data + parity)
22
+ erasure_n: 4,
23
+ // data chunks
24
+ erasure_k: 2,
25
+ // helper nodes
26
+ erasure_d: 3,
27
+ // enum index
28
+ enumIndex: 1
29
+ }
30
+ };
31
+ var DEFAULT_ERASURE_N = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_n;
32
+ var DEFAULT_ERASURE_K = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_k;
33
+ var DEFAULT_ERASURE_D = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_d;
34
+ var DEFAULT_ERASURE_M = DEFAULT_ERASURE_N - DEFAULT_ERASURE_K;
35
+
36
+ // src/core/chunk.ts
37
+ var CHUNK_SIZE_PARAMS = {
38
+ ["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */]: {
39
+ // 1MiB
40
+ chunkSizeBytes: 1 * 1024 * 1024,
41
+ // 10MiB
42
+ chunksetSizeBytes: 10 * 1024 * 1024
43
+ },
44
+ ["ChunkSet2MiB_Chunk1MiB" /* ChunkSet2MiB_Chunk1MiB */]: {
45
+ // 1MiB
46
+ chunkSizeBytes: 1 * 1024 * 1024,
47
+ // 2MiB
48
+ chunksetSizeBytes: 2 * 1024 * 1024
49
+ }
50
+ };
51
+ var DEFAULT_CHUNK_SIZE_BYTES = CHUNK_SIZE_PARAMS["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */].chunkSizeBytes;
52
+ var DEFAULT_CHUNKSET_SIZE_BYTES = CHUNK_SIZE_PARAMS["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */].chunksetSizeBytes;
53
+ var ERASURE_CODE_AND_CHUNK_MAPPING = {
54
+ ["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */]: {
55
+ ...CHUNK_SIZE_PARAMS.ChunkSet10MiB_Chunk1MiB
56
+ },
57
+ ["ClayCode_4Total_2Data_3Helper" /* ClayCode_4Total_2Data_3Helper */]: {
58
+ ...CHUNK_SIZE_PARAMS.ChunkSet2MiB_Chunk1MiB
59
+ }
60
+ };
61
+
62
+ // src/core/utils.ts
63
+ import {
64
+ AccountAddress,
65
+ Hex
66
+ } from "@aptos-labs/ts-sdk";
67
+ async function* readInChunks(input, chunkSize) {
68
+ let idx = 0;
69
+ if (isReadableStream(input)) {
70
+ const reader = input.getReader();
71
+ let buffer = new Uint8Array(chunkSize);
72
+ let bufferWriteOffset = 0;
73
+ try {
74
+ while (true) {
75
+ const { value, done } = await reader.read();
76
+ if (done) break;
77
+ if (value === void 0) continue;
78
+ let srcOffset = 0;
79
+ while (srcOffset < value.length) {
80
+ const remainingCapacity = chunkSize - bufferWriteOffset;
81
+ const bytesToCopy = Math.min(
82
+ remainingCapacity,
83
+ value.length - srcOffset
84
+ );
85
+ buffer.set(
86
+ value.subarray(srcOffset, srcOffset + bytesToCopy),
87
+ bufferWriteOffset
88
+ );
89
+ bufferWriteOffset += bytesToCopy;
90
+ srcOffset += bytesToCopy;
91
+ if (bufferWriteOffset >= chunkSize) {
92
+ yield [idx++, buffer];
93
+ buffer = new Uint8Array(chunkSize);
94
+ bufferWriteOffset = 0;
95
+ }
96
+ }
97
+ }
98
+ } finally {
99
+ reader.releaseLock();
100
+ }
101
+ if (bufferWriteOffset > 0) {
102
+ yield [idx++, buffer.subarray(0, bufferWriteOffset)];
103
+ }
104
+ return;
105
+ }
106
+ const view = toUint8Array(input);
107
+ for (let offset = 0; offset < view.byteLength; offset += chunkSize) {
108
+ yield [
109
+ idx++,
110
+ view.subarray(offset, Math.min(offset + chunkSize, view.byteLength))
111
+ ];
112
+ }
113
+ }
114
+ async function concatHashes(parts) {
115
+ const chunks = parts.map((part) => Hex.fromHexInput(part).toUint8Array());
116
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
117
+ const combined = new Uint8Array(totalLength);
118
+ let offset = 0;
119
+ for (const chunk of chunks) {
120
+ combined.set(chunk, offset);
121
+ offset += chunk.byteLength;
122
+ }
123
+ return Hex.fromHexInput(
124
+ new Uint8Array(await crypto.subtle.digest("SHA-256", combined))
125
+ );
126
+ }
127
+ function isReadableStream(value) {
128
+ return typeof value === "object" && value !== null && "getReader" in value && typeof value.getReader === "function";
129
+ }
130
+ function toUint8Array(view) {
131
+ return view instanceof Uint8Array ? view : new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
132
+ }
133
+
134
+ // src/core/commitments.ts
135
+ var COMMITMENT_SCHEMA_VERSION = "1.3";
136
+ var ChunksetCommitmentSchema = z.object({
137
+ // Chunkset root (vector commitment of child chunks)
138
+ chunkset_root: z.string(),
139
+ // the size is known statically from the current configuration
140
+ chunk_commitments: z.array(z.string())
141
+ }).refine(
142
+ (data) => {
143
+ return data.chunk_commitments.length === DEFAULT_ERASURE_K + DEFAULT_ERASURE_M;
144
+ },
145
+ {
146
+ message: `Chunkset must have exactly ${DEFAULT_ERASURE_K + DEFAULT_ERASURE_M} chunks (ERASURE_K + ERASURE_M = ${DEFAULT_ERASURE_K} + ${DEFAULT_ERASURE_M})`,
147
+ path: ["chunk_commitments"]
148
+ }
149
+ );
150
+ function expectedTotalChunksets(rawSize, chunksetSize = DEFAULT_CHUNKSET_SIZE_BYTES) {
151
+ if (chunksetSize <= 0) {
152
+ throw new Error("chunksetSize must be positive");
153
+ }
154
+ if (rawSize === 0) return 1;
155
+ return Math.ceil(rawSize / chunksetSize);
156
+ }
157
+ var BlobCommitmentsSchema = z.object({
158
+ schema_version: z.string(),
159
+ raw_data_size: z.number(),
160
+ // FIXME I am not sure about this being here, or if it should be somewhere else
161
+ blob_merkle_root: z.string(),
162
+ chunkset_commitments: z.array(ChunksetCommitmentSchema)
163
+ }).refine(
164
+ (data) => {
165
+ return expectedTotalChunksets(data.raw_data_size) === data.chunkset_commitments.length;
166
+ },
167
+ {
168
+ message: "Total chunkset count mismatches with raw data size",
169
+ // FIXME put more details in here
170
+ path: ["chunkset_commitments"]
171
+ }
172
+ );
173
+ async function generateMerkleRoot(leafHashes) {
174
+ if (!leafHashes.length) {
175
+ throw new Error(
176
+ "An empty array cannot be used to construct a Merkle tree."
177
+ );
178
+ }
179
+ const zeroArray = new Uint8Array(leafHashes[0].toUint8Array().length);
180
+ const zeroBytes = Hex2.fromHexInput(zeroArray);
181
+ let currentLeaves = leafHashes;
182
+ while (currentLeaves.length > 1) {
183
+ if (currentLeaves.length % 2 !== 0) {
184
+ currentLeaves.push(zeroBytes);
185
+ }
186
+ const nextLeaves = [];
187
+ for (let i = 0; i < currentLeaves.length; i += 2) {
188
+ nextLeaves.push(
189
+ await concatHashes([
190
+ currentLeaves[i].toUint8Array(),
191
+ currentLeaves[i + 1].toUint8Array()
192
+ ])
193
+ );
194
+ }
195
+ currentLeaves = nextLeaves;
196
+ }
197
+ return currentLeaves[0];
198
+ }
199
+
200
+ // src/node/parallel/default_commitment_worker_pool.ts
201
+ import { availableParallelism } from "os";
202
+
203
+ // src/node/parallel/worker_pool.ts
204
+ import fs from "fs";
205
+ import path from "path";
206
+ import { fileURLToPath } from "url";
207
+ import { Worker } from "worker_threads";
208
+ var WorkerPool = class {
209
+ workers = [];
210
+ queue = [];
211
+ maxWorkers;
212
+ workerPath;
213
+ isTerminating = false;
214
+ activeTasks = /* @__PURE__ */ new Set();
215
+ inFlightCount = 0;
216
+ slotWaiters = [];
217
+ constructor(maxWorkers, workerPath) {
218
+ if (!Number.isSafeInteger(maxWorkers) || maxWorkers < 1) {
219
+ throw new Error(
220
+ `maxWorkers must be a positive safe integer, got ${maxWorkers}`
221
+ );
222
+ }
223
+ this.maxWorkers = maxWorkers;
224
+ this.workerPath = workerPath;
225
+ }
226
+ /**
227
+ * Resolve the path to a worker script relative to the calling module.
228
+ *
229
+ * Pass `import.meta.url` from the subclass file along with the script name
230
+ * (without extension). The extension is inferred from the calling module's
231
+ * own extension so that both the TypeScript source (.ts) and the compiled
232
+ * output (.mjs / .js) are handled correctly.
233
+ *
234
+ * @example
235
+ * constructor(maxWorkers: number) {
236
+ * super(maxWorkers, WorkerPool.resolveWorkerPath(import.meta.url, "my_worker"));
237
+ * }
238
+ */
239
+ static resolveWorkerPath(importMetaUrl, scriptName) {
240
+ const currentPath = fileURLToPath(importMetaUrl);
241
+ const dir = path.dirname(currentPath);
242
+ const ext = path.extname(currentPath);
243
+ const workerExt = ext === ".mjs" ? ".mjs" : ext === ".js" ? ".js" : ".ts";
244
+ return path.join(dir, `${scriptName}${workerExt}`);
245
+ }
246
+ initialize() {
247
+ this.isTerminating = false;
248
+ if (!fs.existsSync(this.workerPath)) {
249
+ throw new Error(
250
+ `Could not find worker script at ${this.workerPath}. Running as ${path.extname(this.workerPath)}, expected worker at same extension.`
251
+ );
252
+ }
253
+ for (let i = 0; i < this.maxWorkers; i++) {
254
+ this.workers.push({ worker: new Worker(this.workerPath), busy: false });
255
+ }
256
+ }
257
+ isInitialized() {
258
+ return this.workers.length > 0;
259
+ }
260
+ /**
261
+ * Acquire a back-pressure slot before submitting work to the pool.
262
+ * Resolves immediately if fewer than `maxWorkers` chunksets are in flight;
263
+ * otherwise waits until a slot is released. Callers must call `releaseSlot()`
264
+ * when the submitted task settles (resolve or reject).
265
+ *
266
+ * Moving back-pressure into the pool ensures a single global bound on
267
+ * buffered memory regardless of how many concurrent callers share the pool.
268
+ */
269
+ acquireSlot() {
270
+ if (this.inFlightCount < this.maxWorkers) {
271
+ this.inFlightCount++;
272
+ return Promise.resolve();
273
+ }
274
+ return new Promise((resolve, reject) => {
275
+ this.slotWaiters.push({
276
+ resolve: () => {
277
+ this.inFlightCount++;
278
+ resolve();
279
+ },
280
+ reject
281
+ });
282
+ });
283
+ }
284
+ releaseSlot() {
285
+ this.inFlightCount--;
286
+ const next = this.slotWaiters.shift();
287
+ if (next) {
288
+ next.resolve();
289
+ }
290
+ }
291
+ enqueueTask(task) {
292
+ this.activeTasks.add(task);
293
+ if (this.isTerminating) {
294
+ this.activeTasks.delete(task);
295
+ task.reject(
296
+ new Error("Worker pool is being terminated - cannot process new tasks")
297
+ );
298
+ return;
299
+ }
300
+ const availableWorker = this.workers.find((w) => !w.busy);
301
+ if (availableWorker) {
302
+ this.executeTask(availableWorker, task);
303
+ } else {
304
+ this.queue.push(task);
305
+ }
306
+ }
307
+ processNextQueuedTask(preferredWorker) {
308
+ const nextTask = this.queue.shift();
309
+ if (!nextTask) return;
310
+ if (preferredWorker && !preferredWorker.busy && preferredWorker.worker) {
311
+ this.executeTask(preferredWorker, nextTask);
312
+ return;
313
+ }
314
+ const availableWorker = this.workers.find((w) => !w.busy && w.worker);
315
+ if (availableWorker) {
316
+ this.executeTask(availableWorker, nextTask);
317
+ } else {
318
+ this.queue.unshift(nextTask);
319
+ }
320
+ }
321
+ rejectAllQueuedTasks(error) {
322
+ const tasks = this.queue.splice(0);
323
+ for (const task of tasks) {
324
+ this.activeTasks.delete(task);
325
+ task.reject(error);
326
+ }
327
+ }
328
+ rejectAllActiveTasks(error) {
329
+ const tasks = Array.from(this.activeTasks);
330
+ this.activeTasks.clear();
331
+ for (const task of tasks) {
332
+ task.reject(error);
333
+ }
334
+ }
335
+ executeTask(workerWrapper, task) {
336
+ workerWrapper.busy = true;
337
+ const cleanup = () => {
338
+ workerWrapper.worker.off("message", messageHandler);
339
+ workerWrapper.worker.off("error", errorHandler);
340
+ workerWrapper.worker.off("exit", exitHandler);
341
+ workerWrapper.busy = false;
342
+ };
343
+ const messageHandler = (message) => {
344
+ cleanup();
345
+ this.activeTasks.delete(task);
346
+ if (message.success && message.result !== void 0) {
347
+ task.resolve(message.result);
348
+ } else {
349
+ task.reject(new Error(message.error ?? "Worker processing failed"));
350
+ }
351
+ this.processNextQueuedTask(workerWrapper);
352
+ };
353
+ const errorHandler = (error) => {
354
+ workerWrapper.worker.off("message", messageHandler);
355
+ workerWrapper.worker.off("error", errorHandler);
356
+ workerWrapper.busy = false;
357
+ this.activeTasks.delete(task);
358
+ task.reject(error);
359
+ };
360
+ const exitHandler = (exitCode) => {
361
+ workerWrapper.worker.off("message", messageHandler);
362
+ workerWrapper.worker.off("error", errorHandler);
363
+ workerWrapper.worker.off("exit", exitHandler);
364
+ workerWrapper.busy = false;
365
+ this.activeTasks.delete(task);
366
+ task.reject(
367
+ new Error(`Worker terminated unexpectedly with exit code ${exitCode}`)
368
+ );
369
+ if (this.isTerminating) return;
370
+ try {
371
+ const newWorker = new Worker(this.workerPath);
372
+ if (this.isTerminating) {
373
+ newWorker.terminate().catch(() => {
374
+ });
375
+ return;
376
+ }
377
+ workerWrapper.worker = newWorker;
378
+ this.processNextQueuedTask(workerWrapper);
379
+ } catch (_error) {
380
+ const index = this.workers.indexOf(workerWrapper);
381
+ if (index > -1) this.workers.splice(index, 1);
382
+ if (this.workers.length === 0) {
383
+ this.rejectAllQueuedTasks(
384
+ new Error(
385
+ "All workers have died and could not be replaced - worker pool is non-functional"
386
+ )
387
+ );
388
+ return;
389
+ }
390
+ this.processNextQueuedTask();
391
+ }
392
+ };
393
+ workerWrapper.worker.on("message", messageHandler);
394
+ workerWrapper.worker.on("error", errorHandler);
395
+ workerWrapper.worker.on("exit", exitHandler);
396
+ this.postTaskMessage(workerWrapper.worker, task);
397
+ }
398
+ /**
399
+ * Terminate all workers and reject all pending tasks.
400
+ *
401
+ * This pool is NOT designed to be reused after termination.
402
+ * Create a new instance if a fresh pool is needed.
403
+ */
404
+ async terminate() {
405
+ this.isTerminating = true;
406
+ const terminationError = new Error(
407
+ "Worker pool is being terminated - task cancelled"
408
+ );
409
+ this.rejectAllQueuedTasks(terminationError);
410
+ this.rejectAllActiveTasks(terminationError);
411
+ const waiters = this.slotWaiters.splice(0);
412
+ for (const waiter of waiters) {
413
+ waiter.reject(terminationError);
414
+ }
415
+ const terminatePromises = this.workers.map((workerWrapper) => {
416
+ return new Promise((resolve) => {
417
+ const worker = workerWrapper.worker;
418
+ let resolved = false;
419
+ const doResolve = () => {
420
+ if (!resolved) {
421
+ resolved = true;
422
+ resolve();
423
+ }
424
+ };
425
+ let timeoutId;
426
+ const exitHandler = () => {
427
+ if (timeoutId) clearTimeout(timeoutId);
428
+ doResolve();
429
+ };
430
+ worker.removeAllListeners("message");
431
+ worker.removeAllListeners("error");
432
+ worker.once("exit", exitHandler);
433
+ timeoutId = setTimeout(() => {
434
+ worker.removeListener("exit", exitHandler);
435
+ doResolve();
436
+ }, 2e3);
437
+ worker.terminate().catch(() => {
438
+ });
439
+ });
440
+ });
441
+ await Promise.all(terminatePromises);
442
+ this.workers = [];
443
+ this.queue = [];
444
+ this.inFlightCount = 0;
445
+ this.isTerminating = false;
446
+ }
447
+ };
448
+
449
+ // src/node/parallel/commitment_worker_pool.ts
450
+ var CommitmentWorkerPool = class extends WorkerPool {
451
+ constructor(maxWorkers) {
452
+ super(
453
+ maxWorkers,
454
+ WorkerPool.resolveWorkerPath(import.meta.url, "commitment_worker")
455
+ );
456
+ }
457
+ postTaskMessage(worker, task) {
458
+ worker.postMessage(
459
+ {
460
+ chunksetData: task.chunksetData,
461
+ encoding: task.encoding
462
+ },
463
+ [task.chunksetData.buffer]
464
+ );
465
+ }
466
+ /**
467
+ * Dispatch a chunkset to a worker for encoding. Returns a promise that
468
+ * resolves to the chunkset's commitment once the worker finishes.
469
+ *
470
+ * The caller must ensure `chunksetData` is not used after this call
471
+ * (its underlying buffer is transferred to the worker thread).
472
+ */
473
+ encodeChunkset(chunksetIdx, chunksetData, encoding) {
474
+ return new Promise((resolve, reject) => {
475
+ const task = {
476
+ chunksetIdx,
477
+ chunksetData,
478
+ encoding,
479
+ resolve,
480
+ reject
481
+ };
482
+ this.enqueueTask(task);
483
+ });
484
+ }
485
+ };
486
+
487
+ // src/node/parallel/default_commitment_worker_pool.ts
488
+ function defaultCommitmentWorkerCount() {
489
+ return Math.max(1, availableParallelism() - 1);
490
+ }
491
+ function createDefaultCommitmentWorkerPool(options = {}) {
492
+ const pool = new CommitmentWorkerPool(
493
+ options.workers ?? defaultCommitmentWorkerCount()
494
+ );
495
+ pool.initialize();
496
+ return pool;
497
+ }
498
+
499
+ // src/node/parallel/parallel_commitments.ts
500
+ function toCommitmentEncoding(provider) {
501
+ const cfg = provider.config;
502
+ if (typeof cfg.erasure_d !== "number" || typeof cfg.enumIndex !== "number") {
503
+ throw new Error(
504
+ "generateCommitmentsParallel requires a Clay erasure coding provider (erasure_d and enumIndex must be set on provider.config)"
505
+ );
506
+ }
507
+ return {
508
+ erasure_n: cfg.erasure_n,
509
+ erasure_k: cfg.erasure_k,
510
+ erasure_d: cfg.erasure_d,
511
+ chunkSizeBytes: cfg.chunkSizeBytes,
512
+ enumIndex: cfg.enumIndex
513
+ };
514
+ }
515
+ async function generateCommitmentsParallel(provider, data, options) {
516
+ const encoding = toCommitmentEncoding(provider);
517
+ const chunksetSize = encoding.erasure_k * encoding.chunkSizeBytes;
518
+ const ownPool = options?.pool === void 0;
519
+ const pool = options?.pool ?? createDefaultCommitmentWorkerPool({ workers: options?.concurrency });
520
+ if (!pool.isInitialized()) {
521
+ throw new Error(
522
+ "The provided CommitmentWorkerPool has not been initialized. Call pool.initialize() before passing it to generateCommitmentsParallel."
523
+ );
524
+ }
525
+ try {
526
+ const pending = [];
527
+ let rawDataSize = 0;
528
+ for await (const [idx, chunkData] of readInChunks(data, chunksetSize)) {
529
+ rawDataSize += chunkData.length;
530
+ await pool.acquireSlot();
531
+ const copy = new Uint8Array(chunkData);
532
+ const p = pool.encodeChunkset(idx, copy, encoding);
533
+ pending[idx] = p;
534
+ p.then(pool.releaseSlot.bind(pool), pool.releaseSlot.bind(pool));
535
+ }
536
+ if (rawDataSize === 0) {
537
+ pending[0] = pool.encodeChunkset(
538
+ 0,
539
+ new Uint8Array(chunksetSize),
540
+ encoding
541
+ );
542
+ }
543
+ const chunksetCommitments = await Promise.all(pending);
544
+ const chunksetHashes = chunksetCommitments.map(
545
+ (c) => Hex3.fromHexInput(c.chunkset_root)
546
+ );
547
+ return {
548
+ schema_version: COMMITMENT_SCHEMA_VERSION,
549
+ raw_data_size: rawDataSize,
550
+ blob_merkle_root: (await generateMerkleRoot(chunksetHashes)).toString(),
551
+ chunkset_commitments: chunksetCommitments
552
+ };
553
+ } finally {
554
+ if (ownPool) {
555
+ await pool.terminate();
556
+ }
557
+ }
558
+ }
559
+ export {
560
+ generateCommitmentsParallel
561
+ };
@@ -0,0 +1,74 @@
1
+ import { Worker } from 'node:worker_threads';
2
+
3
+ interface WorkerPoolTask<TResult> {
4
+ resolve: (result: TResult) => void;
5
+ reject: (error: Error) => void;
6
+ }
7
+ interface WorkerWrapper {
8
+ worker: Worker;
9
+ busy: boolean;
10
+ }
11
+ /**
12
+ * Generic worker pool. Subclasses define the task type and how to post messages
13
+ * to the worker. The pool manages the worker lifecycle, task queue, and
14
+ * worker replacement on crash.
15
+ *
16
+ * Worker responses must follow the shape { success: boolean, result?: TResult, error?: string }.
17
+ *
18
+ * The worker script path is passed to the constructor and resolved relative to the
19
+ * subclass file using the static `resolveWorkerPath` helper.
20
+ */
21
+ declare abstract class WorkerPool<TTask extends WorkerPoolTask<TResult>, TResult> {
22
+ protected workers: WorkerWrapper[];
23
+ private queue;
24
+ readonly maxWorkers: number;
25
+ private readonly workerPath;
26
+ private isTerminating;
27
+ private activeTasks;
28
+ private inFlightCount;
29
+ private slotWaiters;
30
+ constructor(maxWorkers: number, workerPath: string);
31
+ /**
32
+ * Resolve the path to a worker script relative to the calling module.
33
+ *
34
+ * Pass `import.meta.url` from the subclass file along with the script name
35
+ * (without extension). The extension is inferred from the calling module's
36
+ * own extension so that both the TypeScript source (.ts) and the compiled
37
+ * output (.mjs / .js) are handled correctly.
38
+ *
39
+ * @example
40
+ * constructor(maxWorkers: number) {
41
+ * super(maxWorkers, WorkerPool.resolveWorkerPath(import.meta.url, "my_worker"));
42
+ * }
43
+ */
44
+ static resolveWorkerPath(importMetaUrl: string, scriptName: string): string;
45
+ /** Post the task's payload to the worker. */
46
+ protected abstract postTaskMessage(worker: Worker, task: TTask): void;
47
+ initialize(): void;
48
+ isInitialized(): boolean;
49
+ /**
50
+ * Acquire a back-pressure slot before submitting work to the pool.
51
+ * Resolves immediately if fewer than `maxWorkers` chunksets are in flight;
52
+ * otherwise waits until a slot is released. Callers must call `releaseSlot()`
53
+ * when the submitted task settles (resolve or reject).
54
+ *
55
+ * Moving back-pressure into the pool ensures a single global bound on
56
+ * buffered memory regardless of how many concurrent callers share the pool.
57
+ */
58
+ acquireSlot(): Promise<void>;
59
+ releaseSlot(): void;
60
+ protected enqueueTask(task: TTask): void;
61
+ private processNextQueuedTask;
62
+ private rejectAllQueuedTasks;
63
+ private rejectAllActiveTasks;
64
+ private executeTask;
65
+ /**
66
+ * Terminate all workers and reject all pending tasks.
67
+ *
68
+ * This pool is NOT designed to be reused after termination.
69
+ * Create a new instance if a fresh pool is needed.
70
+ */
71
+ terminate(): Promise<void>;
72
+ }
73
+
74
+ export { WorkerPool, type WorkerPoolTask };