Commit 4b9549c
fix: prevent WASM double-initialization with concurrent plugin instances (#125)
## Summary
- Fix race condition in `wasmInit()` that causes `buildStart` to hang
when multiple `icpBindgen()` plugin instances run concurrently
- Replace boolean `initialized` flag with a shared Promise pattern so
concurrent callers await the same initialization
- Reset the cached promise on failure so subsequent calls can retry
## Root Cause
When multiple `icpBindgen()` plugin instances call `buildStart` in
parallel, each triggers `wasmInit()`. The boolean `initialized` flag is
only set **after** `await init()` completes, so concurrent callers all
pass the `if (initialized)` check and each call `init()` independently,
causing WASM double-initialization and a hang:
```
(vite-plugin-icp-bindgen) buildStart ← all hang
(vite-plugin-icp-bindgen) buildStart
(vite-plugin-icp-bindgen) buildStart
```
## Fix
Store the `init()` Promise so all concurrent callers share and await the
same initialization:
```ts
let initPromise: Promise<void> | undefined;
export async function wasmInit(...args: Parameters<typeof init>) {
if (!initPromise) {
initPromise = init(...args).then(
() => {},
(error: unknown) => {
initPromise = undefined;
throw error;
},
);
}
return initPromise;
}
```
The error handler resets `initPromise` on failure so callers can retry
if WASM loading fails.
## Test plan
- [x] Added `tests/wasm-init.test.ts` — 5 concurrent `wasmInit` calls
resolve without hanging
- [x] All existing tests pass (20/21; 1 pre-existing CLI test requires
`vite build` output)
- [x] Biome lint clean
- [x] CodeQL clean
Closes #124
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Nikolaos Xenakis <25032940+nikosxenakis@users.noreply.github.com>1 parent e0f87d1 commit 4b9549c
2 files changed
+34
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
5 | 5 | | |
6 | 6 | | |
7 | 7 | | |
8 | | - | |
| 8 | + | |
9 | 9 | | |
10 | 10 | | |
11 | | - | |
12 | | - | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
13 | 19 | | |
14 | | - | |
15 | | - | |
16 | | - | |
| 20 | + | |
17 | 21 | | |
18 | 22 | | |
19 | 23 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
0 commit comments