Repository navigation
Expand file tree
/
Copy pathtar.wasi.cjs
More file actions
2306 lines (2205 loc) · 85.6 KB
/
Copy pathtar.wasi.cjs
File metadata and controls
2306 lines (2205 loc) · 85.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// napi-rs-artifact-metadata:{"version":2,"rootEntry":"index.js","exports":["Archive","Builder","Entries","Entry","Header","ReadonlyHeader","EntryType"],"managedRootEntries":["browser.js","index.js","tar.wasm","tar.debug.wasm"]}
/* eslint-disable */
/* auto-generated by NAPI-RS */
const __napiBindingTarget = 'wasm32-wasi'
function __napiStampBindingTarget(exportsObject, target) {
if (
Object.prototype.hasOwnProperty.call(exportsObject, '__napiBindingTarget')
) {
if (exportsObject.__napiBindingTarget === target) {
// Already ours: the root entry aliases the object it loaded, so a WASI
// fallback candidate — or a `NAPI_RS_NATIVE_LIBRARY_PATH` override that
// is a generated loader — arrives already stamped with this same value.
return target
}
const error = new Error(
'`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = "...")].',
)
error.code = 'ERR_NAPI_BINDING_TARGET_CONFLICT'
throw error
}
if (!Object.isExtensible(exportsObject)) {
// A `#[napi(module_exports)]` hook may seal or freeze this object
// (`Object::seal` / `Object::freeze`). Reporting the artifact is metadata,
// never a reason to fail an otherwise successful load, so the stamp is
// skipped. What a consumer still sees then follows the entry point: the
// browser and deferred loaders declare `__napiBindingTarget` at module
// level and go on reporting it, while the CommonJS entries hand back this
// very object as `module.exports`, so there the value is absent.
return target
}
try {
// [[Define]], not [[Set]]: an ordinary assignment walks the prototype
// chain, so an inherited accessor could swallow the value or throw and
// fail an otherwise successful load. The descriptor is what a successful
// assignment would have produced.
Object.defineProperty(exportsObject, '__napiBindingTarget', {
configurable: true,
enumerable: true,
value: target,
writable: true,
})
} catch {
// Same rule as the non-extensible skip above: reporting the artifact is
// metadata, never a reason to fail an otherwise successful load. An exotic
// object (a Proxy whose defineProperty trap refuses) is skipped, not
// thrown over.
}
// The CommonJS loaders assign this return value so `cjs-module-lexer` — and
// therefore Node's CJS -> ESM named export detection — can see
// `__napiBindingTarget` statically.
return target
}
const __nodeFs = require('node:fs')
const __nodePath = require('node:path')
const { WASI: __nodeWASI } = require('node:wasi')
const { Worker } = require('node:worker_threads')
const {
emnapiAsyncWorkPlugin: __emnapiAsyncWorkPlugin,
emnapiTSFNPlugin: __emnapiTSFNPlugin,
createOnMessage: __wasmCreateOnMessageForFsProxy,
instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync,
} = require('@napi-rs/wasm-runtime')
const { createContext: __emnapiCreateContext } = require('@emnapi/runtime')
function __getWasiWorkerExecArgv() {
const __workerExecArgv = []
for (let __index = 0; __index < process.execArgv.length; __index += 1) {
const __arg = process.execArgv[__index]
if (
__arg === '--input-type' ||
__arg === '--eval' ||
__arg === '-e' ||
__arg === '--print' ||
__arg === '-p'
) {
__index += 1
continue
}
if (
__arg.startsWith('--input-type=') ||
__arg.startsWith('--eval=') ||
__arg.startsWith('--print=')
) {
continue
}
__workerExecArgv.push(__arg)
}
return __workerExecArgv
}
function __isInvalidWasiWorkerExecArgv(errorMessage, argument) {
const __equalsIndex = argument.indexOf('=')
const __argumentName =
__equalsIndex === -1 ? argument : argument.slice(0, __equalsIndex)
return (
errorMessage.includes(': ' + __argumentName + ',') ||
errorMessage.includes(': ' + __argumentName + '=') ||
errorMessage.endsWith(': ' + __argumentName) ||
errorMessage.includes(', ' + __argumentName + ',') ||
errorMessage.includes(', ' + __argumentName + '=') ||
errorMessage.endsWith(', ' + __argumentName)
)
}
function __removeInvalidWasiWorkerExecArgv(execArgv, error) {
if (typeof error.message !== 'string') {
return
}
const __workerExecArgv = []
let __removed = false
for (let __index = 0; __index < execArgv.length; __index += 1) {
const __arg = execArgv[__index]
if (
__arg.startsWith('-') &&
__isInvalidWasiWorkerExecArgv(error.message, __arg)
) {
__removed = true
if (
!__arg.includes('=') &&
__index + 1 < execArgv.length &&
!execArgv[__index + 1].startsWith('-')
) {
__index += 1
}
continue
}
__workerExecArgv.push(__arg)
}
return __removed ? __workerExecArgv : undefined
}
function __createWasiWorker(filename) {
let __workerExecArgv = __getWasiWorkerExecArgv()
while (true) {
try {
return new Worker(filename, {
env: process.env,
execArgv: __workerExecArgv,
workerData: {
hostRoot: __hostRoot,
rootDir: __rootDir,
crashFlag: __wasiThreadCrashFlag,
crashReport: __wasiThreadCrashReport,
addonCrashFlag: __wasiAddonCrashFlag,
},
})
} catch (error) {
if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
throw error
}
const __nextWorkerExecArgv =
__removeInvalidWasiWorkerExecArgv(__workerExecArgv, error)
if (!__nextWorkerExecArgv) {
throw error
}
__workerExecArgv = __nextWorkerExecArgv
}
}
}
// Set to 1 by a pool worker (see wasi-worker.mjs) right before it reports that
// its wasm thread died. Shared memory, so this thread reads it synchronously even
// while the worker's 'error' event is still queued behind the code that is
// exiting right now.
const __wasiThreadCrashFlag = new Int32Array(new SharedArrayBuffer(4))
// Written by the first pool worker whose wasm thread dies, before it raises the
// flag: its error and `threadId` (layout in wasi-worker.mjs). Read without
// waiting for any event, see `__readWasiThreadCrashReport`.
const __wasiThreadCrashReport = new SharedArrayBuffer(4096)
let __wasiThreadCrashReportRead
// The first error a pool worker reported through its 'error' event, and that
// worker's `threadId`. See `__getWasiThreadCrashError`.
let __wasiThreadCrashWorkerError
let __wasiThreadCrashWorkerId
let __wasiThreadCrashError
// Raised while `__runWasiInitializationRollbackSteps` runs, so its polls and
// steps stop after a crash the way a public disposal's do.
let __wasiInitializationRollbackActive = false
let __wasiThreadCrashed = false
// A view of the addon's crash flag, one word of the shared wasm memory, for the
// pool workers: they raise it when their wasm thread dies, and the shutdown
// waits inside the cleanup calls on this thread then trap instead of waiting on
// the dead thread for good. Undefined for an addon built with an older napi.
let __wasiAddonCrashFlag
function __captureWasiAddonCrashFlag(instance) {
try {
const getAddress = instance.exports.napi_wasm_thread_crash_flag_address
if (typeof getAddress !== 'function') {
return
}
const address = getAddress() >>> 0
const buffer = __sharedMemory.buffer
if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) {
return
}
__wasiAddonCrashFlag = new Int32Array(buffer, address, 1)
} catch {}
}
/**
* Whether any wasm thread of this binding has died: a trap or an uncaught error
* in a pool worker, including one that failed to load after its thread spawn
* had already been reported as started.
*
* After that the shared wasm state cannot be trusted: a lock the dead thread
* held stays held, and a join or park that waits on it — the async runtime's
* `finish_shutdown` waiting for the dead thread's work to go idle — blocks
* this thread forever in a raw `memory.atomic.wait32`, which neither
* emnapi's crash check nor a signal can interrupt.
*/
function __hasWasiThreadCrashed() {
if (__wasiThreadCrashed || Atomics.load(__wasiThreadCrashFlag, 0) !== 0) {
return true
}
const manager = __getWasiThreadManager()
return Boolean(manager && manager._fatalError)
}
let __wasiThreadCrashDisposePromise
// Raised by the crash disposal right before it terminates the workers. See
// `__wasiSetImmediate`.
let __wasiReentryClosed = false
/**
* emnapi's `features.setImmediate` for this binding's context. emnapi defers
* its calls back into wasm through it: `_emnapi_set_immediate` (libuv handle
* closes, threadsafe-function finalizers), threadsafe-function dispatch
* (`async-send`) and the finalizer queue. One queued before a crash disposal
* terminates the workers still runs after it, and a worker terminated while it
* held a lock in the wasm heap (napi's heap-sync allocator lock spins and never
* gives up) leaves that call spinning on this thread for good. The binding is
* unusable after a crash disposal, so those calls are dropped.
*
* Known residual, still able to enter wasm after a crash disposal because emnapi
* offers no hook for them: the `FinalizationRegistry` callbacks that free
* external memory when GC collects a value (`_free`, the shared-buffer meta
* release), threadsafe-function dispatch of `async-send` type 1 and
* `_emnapi_next_tick` (both `Promise.resolve().then`), and every deferred
* call under emnapi 1.x, whose `createContext` ignores `features`.
*/
function __wasiSetImmediate(callback) {
return setImmediate(function () {
if (!__wasiReentryClosed) {
callback()
}
})
}
/**
* Stores the first error a pool worker reported, with the worker's id. Called
* from the loader's own 'error' listener, which runs before emnapi's.
*/
function __recordWasiThreadCrashError(error, workerId) {
if (__wasiThreadCrashWorkerError !== undefined || error === undefined) {
return
}
__wasiThreadCrashWorkerError = error
__wasiThreadCrashWorkerId = workerId
__fillWasiThreadCrashError()
}
/**
* The error in the shared crash report, rebuilt once it is complete: the
* worker writes it before it raises the flag, so it is there as soon as the
* crash is seen. Plain JavaScript over shared memory; never enters wasm.
*/
function __readWasiThreadCrashReport() {
if (__wasiThreadCrashReportRead !== undefined) {
return __wasiThreadCrashReportRead
}
try {
const header = new Int32Array(__wasiThreadCrashReport, 0, 3)
if (Atomics.load(header, 0) !== 2) {
return
}
const length = Atomics.load(header, 1)
const threadId = Atomics.load(header, 2)
let error
if (length > 0) {
// Copied out of shared memory: TextDecoder does not take a shared view.
const bytes = new Uint8Array(__wasiThreadCrashReport, 12, length).slice()
const report = JSON.parse(new TextDecoder().decode(bytes))
error = new Error(String(report.message))
if (typeof report.name === 'string') {
error.name = report.name
}
if (typeof report.stack === 'string') {
error.stack = report.stack
}
}
__wasiThreadCrashReportRead = { error, threadId }
} catch {
__wasiThreadCrashReportRead = { error: undefined, threadId: 0 }
}
return __wasiThreadCrashReportRead
}
/**
* The one error every crash path of this binding reports, created on first
* use.
*
* The shared flag is raised before this thread has processed the worker's
* 'error' event, and once the workers are terminated that event is often
* never delivered, so neither it nor emnapi's `_fatalError` can be counted
* on. The cause is filled in from the first source that has it: the error the
* 'error' listener kept, else the worker's shared crash report, else
* `_fatalError` — here, and again from the 'error' listener when it arrives
* later. Until then the error carries only its message.
*/
function __getWasiThreadCrashError() {
if (__wasiThreadCrashError === undefined) {
__wasiThreadCrashError = new Error(
'napi-rs: WASI binding cannot be disposed after a worker thread crashed',
)
}
__fillWasiThreadCrashError()
return __wasiThreadCrashError
}
function __fillWasiThreadCrashError() {
const crashError = __wasiThreadCrashError
if (crashError === undefined) {
return
}
try {
if (crashError.cause === undefined) {
let cause = __wasiThreadCrashWorkerError
if (cause === undefined) {
const report = __readWasiThreadCrashReport()
cause = report ? report.error : undefined
}
if (cause === undefined) {
const manager = __getWasiThreadManager()
cause = manager ? manager._fatalError : undefined
}
if (cause !== undefined && cause !== null) {
crashError.cause = cause
}
}
if (crashError.workerThreadId === undefined) {
let workerId = __wasiThreadCrashWorkerId
if (workerId === undefined) {
const report = __readWasiThreadCrashReport()
workerId = report && report.threadId > 0 ? report.threadId : undefined
}
if (workerId !== undefined) {
crashError.workerThreadId = workerId
}
}
} catch {}
}
/**
* Let the event loop drain after a wasm thread died, without entering wasm.
*
* emnapi's `Context` keeps a `NodejsWaitingRequestCounter` on Node: a
* `MessagePort` (`refCounter.refHandle`) that it refs when the count of
* in-flight async work and threadsafe-function requests leaves zero and unrefs
* when it comes back. The requests the dead thread held never complete, so the
* count never returns to zero and the port holds the process open for good.
* `Context.destroy()` would not release it either — and it runs cleanup
* hooks, which is exactly what must not happen now. So unref the port directly.
* The count is left as is: it stays above zero, so a later request never refs
* the port again.
*
* The field is private in emnapi's typings, so read it defensively; a context
* without it (a non-Node host, a future emnapi) is left alone.
*/
function __releaseEmnapiWaitingRequestHandle() {
try {
const refCounter = __emnapiContext && __emnapiContext.refCounter
const refHandle = refCounter && refCounter.refHandle
if (refHandle && typeof refHandle.unref === 'function') {
refHandle.unref()
}
} catch {}
}
/**
* The public disposer after a wasm thread died. The normal chain drains async
* work, runs the environment cleanup barrier and destroys the context — every
* one of those re-enters wasm, and the barrier's shutdown waits for the dead
* thread's work in the same raw atomic wait `__disposeWasiBindingAtExit`
* avoids. An app that handled the worker's error and then disposes would block
* there for good. Only stop the workers, then reject: the binding was not
* cleaned up and cannot be, so reporting success would be a lie. The context
* is not destroyed — only its waiting-request port is unrefed, so the process
* can exit on its own — and the 'exit' listener takes its short path too.
*
* Latched: every later call returns the same promise.
*/
function __disposeWasiBindingAfterThreadCrash() {
if (__wasiThreadCrashDisposePromise) {
return __wasiThreadCrashDisposePromise
}
__releaseEmnapiWaitingRequestHandle()
// No call into wasm after this: see `__wasiSetImmediate`.
__wasiReentryClosed = true
let workerResult
try {
workerResult = __terminateWasiWorkers()
} catch (terminateError) {
workerResult = Promise.reject(terminateError)
}
// Built at settlement, after the workers stopped: by then the 'error' event
// has usually delivered the worker's error.
__wasiThreadCrashDisposePromise = Promise.resolve(workerResult).then(
() => {
throw __getWasiThreadCrashError()
},
(terminateError) => {
throw __attachCleanupErrors(__getWasiThreadCrashError(), [
terminateError,
])
},
)
return __wasiThreadCrashDisposePromise
}
/**
* Stops a public disposal that a thread crash overtook.
*
* The check at the top of `__disposeWasiBinding` only sees a crash that came
* first. A thread that dies once the chain is running leaves it polling for
* work the dead thread still counts — the async-work drain for
* `napi_wasm_async_work_pending`, the barrier's poll for
* `napi_wasm_runtime_work_pending` — and neither count ever reaches zero, so
* the poll's referenced timers keep the process alive forever with the
* disposal promise pending. Each poll turn and each step boundary calls this,
* and the throw ends the chain before anything re-enters wasm again; the
* disposer then settles it through `__settleWasiDisposalAfterThreadCrash`.
*
* The initialization rollback runs the same polls and steps, so they stop while
* it runs too; its wrapper, `__rollbackWasiInitialization`, then ends it
* through `__rollbackWasiInitializationAfterThreadCrash`. A bare poll with
* neither in flight is left alone.
*/
function __abortWasiDisposalIfThreadCrashed() {
if (
(__wasiDisposePromise !== undefined ||
__wasiInitializationRollbackActive) &&
__hasWasiThreadCrashed()
) {
throw new Error(
'napi-rs: WASI disposal stopped because a worker thread crashed',
)
}
}
/**
* Settles an in-flight public disposal whose chain failed after a thread
* died — stopped by `__abortWasiDisposalIfThreadCrashed` or failing any other
* way — through the crash disposal: it releases the waiting-request port,
* terminates the workers and rejects with the same error an entry-time crash
* gets. `__wasiDisposePromise` stays set, so this caller, every caller that
* joined it and every later one hold the same promise. Returns false when no
* thread died, leaving the ordinary failure handling alone.
*/
function __settleWasiDisposalAfterThreadCrash(resolve, reject) {
if (!__hasWasiThreadCrashed()) {
return false
}
__disposeWasiBindingAfterThreadCrash().then(resolve, reject)
return true
}
/**
* Ends an initialization rollback after a wasm thread died, without entering
* wasm: the barrier, its finish and `Context.destroy()` are skipped, and the
* crash disposal releases the waiting-request port and terminates the workers,
* once. The initialization error itself is left to propagate: the crash error
* is returned as the rollback's cleanup error, so
* `__completeWasiInitializationRollback` attaches it — as the cause when the
* error has none — and keeps the record, since the context was not destroyed.
*/
function __rollbackWasiInitializationAfterThreadCrash() {
const crashError = __getWasiThreadCrashError()
// Its rejection is `crashError` itself, which the caller reports.
void __disposeWasiBindingAfterThreadCrash().catch(() => {})
return [crashError]
}
const __wasiThreadPoolReconcileSymbol = Symbol.for('napi.rs.wasi.reconcileThreadPool')
/**
* Takes a Worker out of emnapi's reuse pool, if it is still there. emnapi
* terminates a pooled Worker that failed to load but (up to
* @emnapi/wasi-threads 2.1.0) leaves it in the pool, where the next thread
* spawn would pop it. A newer emnapi removes it itself, so this is a no-op
* then.
*/
function __removeWasiPoolWorker(manager, worker) {
const index = manager.unusedWorkers.indexOf(worker)
if (index !== -1) {
manager.unusedWorkers.splice(index, 1)
}
}
/**
* Takes a Worker the thread manager just terminated out of `__wasiWorkers`
* once it has exited, not before. `terminateWorker` only starts Node's
* asynchronous `worker.terminate()` and drops its promise, so a disposal that
* begins before the exit has to find this Worker in the set and wait for it
* like any other. A second `terminate()` settles when the Worker has exited,
* the way `__terminateWasiWorkers` waits.
*/
function __untrackWasiWorkerOnExit(worker) {
const terminated = worker.terminate()
if (__isThenable(terminated)) {
Promise.resolve(terminated).then(
() => {
__wasiWorkers.delete(worker)
},
// Left tracked: disposal terminates it again and reports the error.
() => {},
)
} else {
__wasiWorkers.delete(worker)
}
}
/**
* Matches emnapi's idle reuse pool to the addon's configured MultiThread worker
* count, which the addon exports as `napi_wasm_runtime_pool_workers`
* (napi-async-runtime; 0 under CurrentThread). `reuseWorker: true` starts the
* pool empty, so without this every pool thread the first async call spawns
* boots a Worker and loads the wasm into it first. Here each missing Worker is
* created and starts loading now; a spawn later pops one that is already
* booting. Idle Workers above the count are terminated, last in first out,
* the way a spawn takes them. A Worker a spawn already took is not in the pool
* and is left alone.
*
* Runs once after a successful load and, when the loader wraps it, after every
* successful `configureAsyncRuntime`. Also reachable as
* binding[Symbol.for('napi.rs.wasi.reconcileThreadPool')]().
* It never throws and never waits on a Worker: a Worker whose load fails is
* dropped from the pool when its load rejects. Nothing at all happens after a
* thread crash, once disposal started, or for an addon without the export.
*/
function __reconcileWasiThreadPool() {
try {
if (__wasiDisposed || __wasiDisposePromise || __hasWasiThreadCrashed()) {
return
}
const read = __napiInstance?.exports?.napi_wasm_runtime_pool_workers
if (typeof read !== 'function') {
return
}
const count = read() >>> 0
const manager = __getWasiThreadManager()
if (
!manager ||
!Array.isArray(manager.unusedWorkers) ||
typeof manager.allocateUnusedWorker !== 'function' ||
typeof manager.loadWasmModuleToWorker !== 'function'
) {
return
}
// Both loops are bounded by the difference they start from, so a manager
// that does not update `unusedWorkers` the way emnapi does cannot spin.
for (let excess = manager.unusedWorkers.length - count; excess > 0; excess--) {
const worker = manager.unusedWorkers[manager.unusedWorkers.length - 1]
manager.terminateWorker(worker)
__removeWasiPoolWorker(manager, worker)
__untrackWasiWorkerOnExit(worker)
// Compatibility with @emnapi/wasi-threads 2.1.0 and older:
// `terminateWorker` installs a reporter that logs every emnapi message
// still queued on the port, so a Worker that finished loading just
// before it was terminated prints 'received "loaded" command from
// terminated worker'. Nothing listens for that Worker any more, and a
// newer emnapi ignores the late 'loaded' itself, so this is harmless
// there. `__terminateWasiWorkers` does the same.
worker.onmessage = undefined
}
for (let missing = count - manager.unusedWorkers.length; missing > 0; missing--) {
let worker
try {
// Through `onCreateWorker`: tracked in `__wasiWorkers`, unref'd, and
// handed the crash flags like any pool Worker.
worker = manager.allocateUnusedWorker()
manager
.loadWasmModuleToWorker(worker)
.then(undefined, () => __removeWasiPoolWorker(manager, worker))
} catch {
if (worker !== undefined) {
__removeWasiPoolWorker(manager, worker)
try {
manager.terminateWorker(worker)
__untrackWasiWorkerOnExit(worker)
} catch {}
}
return
}
}
} catch {}
}
function __publishWasiThreadPoolReconcile(exports) {
Object.defineProperty(exports, __wasiThreadPoolReconcileSymbol, {
configurable: false,
enumerable: false,
value: __reconcileWasiThreadPool,
writable: false,
})
}
const __cwd = process.cwd()
const __rootDir = __nodePath.parse(__cwd).root
const __hostRoot =
process.platform === 'android' ? __cwd : __rootDir
const __wasi = new __nodeWASI({
version: 'preview1',
env: process.env,
preopens: {
[__rootDir]: __hostRoot,
[__hostRoot]: __hostRoot,
},
})
const __sharedMemory = new WebAssembly.Memory({
initial: 4000,
maximum: 65536,
shared: true,
})
let __wasmFilePath = __nodePath.join(__dirname, 'tar.wasm32-wasi.wasm')
const __wasmDebugFilePath = __nodePath.join(__dirname, 'tar.wasm32-wasi.debug.wasm')
if (__nodeFs.existsSync(__wasmDebugFilePath)) {
__wasmFilePath = __wasmDebugFilePath
} else if (!__nodeFs.existsSync(__wasmFilePath)) {
const __wasiPackageEntry = require.resolve('@napi-rs/tar-wasm32-wasi')
const __packagedWasmFilePath = __nodePath.join(
__nodePath.dirname(__wasiPackageEntry),
'tar.wasm32-wasi.wasm',
)
if (!__nodeFs.existsSync(__packagedWasmFilePath)) {
throw new Error(
'@napi-rs/tar-wasm32-wasi is installed but is missing tar.wasm32-wasi.wasm.',
)
}
__wasmFilePath = __packagedWasmFilePath
}
const __wasmFile = __nodeFs.readFileSync(__wasmFilePath)
let __emnapiContext
const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
const __wasiWorkers = new Set()
// The thread manager has to be reachable *before* anything that can throw
// during load or registration. Initialization can fail after the pool has
// already spawned workers, and the rollback still has to mark their
// terminations as expected — but `__napiModule` is assigned only when
// instantiation RETURNS, so on exactly that path it is still undefined. A
// plugin factory runs while the emnapi module is being created, before the
// wasm is loaded and before any registration function runs, and its context
// carries the very same manager instance.
let __wasiThreadManager
function __captureWasiThreadManager(context) {
if (context && context.PThread) {
__wasiThreadManager = context.PThread
}
return {}
}
function __getWasiThreadManager() {
const manager =
__wasiThreadManager !== undefined
? __wasiThreadManager
: __napiModule
? __napiModule.PThread
: undefined
if (manager && typeof manager.terminateWorker === 'function') {
return manager
}
return undefined
}
let __napiInstance
let __emnapiContextDestroyed = false
let __emnapiContextDestroyPromise
let __emnapiWasmEnvCleanupPrepared = false
let __emnapiWasmEnvCleanupPreparing = false
// The closer for a barrier that is parked between `…_begin` and `…_finish`,
// set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
// tell those two apart on its own: it is raised both for a purely synchronous
// frame — which must not be re-entered, and which nothing outside it can
// finish — and across this window, which spans real event-loop turns, so a
// caller that cannot yield can land in the middle of one. That caller can close
// this window, because `…_finish` is idempotent and joins, which is exactly
// what the single call does. See `__prepareWasmEnvCleanup`.
let __finishParkedWasmEnvCleanup
// Raised while a caller that can still yield is driving the barrier, so the
// queue it leaves behind is expected rather than lost. See
// `__reportUnreachedWasmEnvSettlements`.
let __emnapiWasmEnvCleanupYielding = false
let __emnapiWasmEnvSettlementLossReported = false
let __emnapiWasmEnvCleanupRan = false
let __emnapiWasmEnvCleanupDrained = false
let __emnapiWasmEnvCleanupDrainPromise
let __wasiDisposed = false
let __wasiAsyncWorkDrainPromise
let __wasiDisposePromise
let __completeWasiDisposal = function () {}
// Overridden by loader flavors that have a last-resort reclaim for a rollback
// that stopped short of destroying the context. See
// `__rollbackWasiInitialization`.
let __retainWasiRollbackForRetry = function () {}
function __isThenable(value) {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof value.then === 'function'
)
}
function __createCleanupError(errors, message) {
if (errors.length === 1) {
return errors[0]
}
const __AggregateError = globalThis.AggregateError
if (typeof __AggregateError === 'function') {
return new __AggregateError(errors, message)
}
const error = new Error(message)
error.errors = errors
return error
}
function __attachCleanupErrors(error, cleanupErrors) {
if (cleanupErrors.length === 0) {
return error
}
const cleanupError = __createCleanupError(
cleanupErrors,
'WASI binding cleanup failed',
)
try {
if (
error &&
(typeof error === 'object' || typeof error === 'function')
) {
if (error.cause === undefined) {
error.cause = cleanupError
if (error.cause === cleanupError) {
return error
}
}
if (Array.isArray(error.cleanupErrors)) {
error.cleanupErrors.push(cleanupError)
return error
} else {
const attachedCleanupErrors = [cleanupError]
error.cleanupErrors = attachedCleanupErrors
if (error.cleanupErrors === attachedCleanupErrors) {
return error
}
}
}
} catch {}
const aggregate = __createCleanupError(
[error, cleanupError],
'WASI binding initialization and cleanup failed',
)
try {
aggregate.cause = error
} catch {}
return aggregate
}
function __wrapEmnapiContextDestroyForSettlement(
context,
prepareEnvCleanup,
isPreparingEnvCleanup,
) {
let destroy
try {
destroy = context.destroy
} catch {
return context
}
if (typeof destroy !== 'function') {
return context
}
try {
Object.defineProperty(context, 'destroy', {
configurable: true,
enumerable: false,
writable: true,
value: function () {
// Reentered from a promise hook that fired inside the barrier: the
// frame running it destroys as soon as it returns.
if (isPreparingEnvCleanup?.()) {
return
}
prepareEnvCleanup?.()
return Reflect.apply(destroy, this, arguments)
},
})
} catch {}
return context
}
function __isPreparingWasmEnvCleanup() {
return __emnapiWasmEnvCleanupPreparing
}
function __prepareWasmEnvCleanup() {
if (__emnapiWasmEnvCleanupPrepared) {
return
}
// A handshake parked between its two halves is one this frame can close, and
// must: every caller of this function is about to destroy the context, and
// the turns the poll is waiting for will not come — an 'exit' teardown is
// the last thing the process runs, and `Context.destroy()` takes the
// environment away. Closing it here runs `…_finish`, which is the call that joins, so
// this degrades to exactly the single call below. Leaving it open instead
// destroys the context with the barrier still raised, the runtime never
// joined and the workers never drained.
const finishParked = __finishParkedWasmEnvCleanup
if (finishParked !== undefined) {
finishParked()
__reportUnreachedWasmEnvSettlements()
return
}
if (__emnapiWasmEnvCleanupPreparing) {
return
}
const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
if (typeof prepare === 'function') {
// The addon settles the promises it cancels synchronously, under a
// non-reentrant lifecycle mutex: anything a promise hook calls from in
// here must not reach this export again.
__emnapiWasmEnvCleanupPreparing = true
try {
prepare()
} finally {
__emnapiWasmEnvCleanupPreparing = false
}
__emnapiWasmEnvCleanupRan = true
__reportUnreachedWasmEnvSettlements()
}
__emnapiWasmEnvCleanupPrepared = true
}
/**
* Say so when the barrier leaves settlements queued and nothing is left that
* could deliver them.
*
* Only the disposal chain yields the event-loop turns @emnapi/core needs to
* dispatch its queue. Every other caller of the barrier destroys in the same
* turn — a raw `Context.destroy()`, the 'exit' teardown — and
* `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
* that queue with a null env and discards it. The promises those settlements
* were for then hang forever, silently.
*
* Loud, once, and never throwing: this runs from inside `Context.destroy()`,
* emnapi's own beforeExit destroy included, where throwing would take the whole
* teardown down with it. Destroying anyway is still the right trade — the queue
* is already unreachable by then.
*/
function __reportUnreachedWasmEnvSettlements() {
if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
return
}
const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
if (typeof pending !== 'function') {
return
}
let queued
try {
queued = pending()
} catch {
return
}
if (!queued) {
return
}
__emnapiWasmEnvSettlementLossReported = true
try {
const consoleHost = globalThis.console
if (consoleHost && typeof consoleHost.error === 'function') {
consoleHost.error(
"napi-rs: the wasm environment is being destroyed with " +
queued +
" queued promise settlement(s). Context.destroy() discards them, so those promises never settle. Dispose with binding[Symbol.for('napi.rs.wasi.dispose')]() instead: only it yields the event-loop turns the settlements need.",
)
}
} catch {}
}
// Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
// on, so the drain turns below interleave with that dispatch instead of racing
// ahead of it on a faster queue.
const __scheduleMacrotask = (function () {
if (typeof setImmediate === 'function') {
return function (callback) {
setImmediate(callback)
}
}
const __MessageChannel = globalThis.MessageChannel
if (typeof __MessageChannel === 'function') {
return function (callback) {
const channel = new __MessageChannel()
channel.port1.onmessage = function () {
channel.port1.onmessage = null
try {
channel.port1.close()
} catch {}
try {
channel.port2.close()
} catch {}
callback()
}
channel.port2.postMessage(null)
}
}
return function (callback) {
setTimeout(callback, 0)
}
})()
// A real, *referenced* timer, for waits that must let the whole host make
// progress between looks — the async-work drain polls the addon rather than
// interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
// would spin the loop instead of yielding it. Falls back to the macrotask
// scheduler on a host without timers.
function __scheduleTimer(callback, delay) {
const setTimer = globalThis.setTimeout
if (typeof setTimer !== 'function') {
__scheduleMacrotask(callback)
return
}
try {
setTimer(callback, delay)
} catch {
__scheduleMacrotask(callback)
}
}
// A real, referenced timer rather than a zero-delay macrotask, for the same
// reason the async-work drain uses one: this polls the addon instead of
// interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
// the loop instead of yielding it.
const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
// Arrivals it takes before the poll paces on the host's timers alone. One
// proves nothing: a timer armed before the host's timers stopped still fires.
const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
// How long a parked turn's own timer must already have been due before a
// backup that runs calls it dropped. Slack, not a deadline: a timer is due
// against the event loop's clock, which is read once per iteration, while
// these are `Date.now()` readings taken part-way through one, so the two
// drift apart by however long the loop has been inside the current iteration.
const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
// How long a backup itself waits. What is left of it after the slack and one
// interval — 149 ms — has to cover the *two* poll turns that can separate a
// parked turn from the last backup armed while the host's timers still
// worked, so the ceiling on a single turn is half of it. See the invariant on
// `__armWasmRuntimePollStallBackup`.
const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
/**
* Pacing state for one runtime-work poll.
*
* Per poll, never per module: whether the host's timers arrive is not a
* property of the module. A host can lose its timers between two disposals,
* and in the deferred shape every instance shares this module — one healthy
* instance must not disarm the fallback for the next one.
*/
function __createWasmRuntimePollPace() {
return {
// Timers armed by *this* poll that have actually arrived.
arrivals: 0,
// The turn waiting on a timer alone *right now* — undefined whenever no
// turn is parked — and when that turn's own timer came due.
settleTurn: undefined,
turnTimerDueAt: 0,
}
}
/**
* The backup that ends a turn whose timer is never going to arrive.
*
* Once the poll paces on the timer alone it has nothing left to fall back on
* if the host's timers stop mid-poll: the turn that armed the dead timer is
* the turn that parks, and a parked poll schedules nothing that could notice.
* So every turn arms one of these before it yields, and each one compares due
* times instead of measuring how long the parked turn has been waiting.
*
* Invariant: a parked turn is ended by the newest backup that was armed while
* the host's timers still worked, and a backup ends a turn only when that
* turn's own timer was already due a whole window before the backup itself.
* Neither half turns on how far apart the arms happen to fall — what bounds