@mrwinston/fibers 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,26 @@
1
+ Copyright 2011 Marcel Laverdet
2
+ Permission is hereby granted, free of charge, to any person obtaining a copy
3
+ of this software and associated documentation files (the "Software"), to
4
+ deal in the Software without restriction, including without limitation the
5
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
6
+ sell copies of the Software, and to permit persons to whom the Software is
7
+ furnished to do so, subject to the following conditions:
8
+
9
+ The above copyright notice and this permission notice shall be included in
10
+ all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
18
+ IN THE SOFTWARE.
19
+
20
+ ----
21
+
22
+ native/fibers.cc and native/coroutine.{h,cc} are derived from node-fibers
23
+ (https://github.com/laverdet/node-fibers, Copyright 2011 Marcel Laverdet, the
24
+ license above). native/libcoro is libcoro as vendored by node-fibers, under its
25
+ own license (native/libcoro/LICENSE). The changes and the other files are
26
+ Copyright 2026 its contributors, under the same MIT terms.
package/README.md CHANGED
@@ -1,3 +1,413 @@
1
- # Temporary Holding Version
1
+ # @mrwinston/fibers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Fibers for **stock Node.js 24 and 26** on **x64 Linux**. Call promise-returning code from a plain
4
+ synchronous function: only the calling fiber waits, while the event loop and every other fiber
5
+ keep running.
6
+
7
+ ```js
8
+ import { Fiber } from "@mrwinston/fibers";
9
+ import { readFile } from "node:fs/promises";
10
+
11
+ const readText = Fiber.wrap(readFile); // looks synchronous, doesn't block the thread
12
+
13
+ function loadConfig(path) {
14
+ // a plain function, no async/await
15
+ return JSON.parse(readText(path, "utf8"));
16
+ }
17
+
18
+ const config = await Fiber.run(() => loadConfig("config.json"));
19
+ ```
20
+
21
+ > [!WARNING]
22
+ > **Alpha.** Read [Limits](#limits) before using this in production. Prefer `async`/`await`
23
+ > wherever you can. Use fibers only where synchronous code, such as code shared between client
24
+ > and server, has to call async code.
25
+
26
+ The native core is derived from [node-fibers](https://github.com/laverdet/node-fibers), which no
27
+ longer works on current Node.js. It needs no patched Node: it runs on the official binaries.
28
+
29
+ ## Contents
30
+
31
+ - [Requirements](#requirements)
32
+ - [Install](#install)
33
+ - [Usage](#usage)
34
+ - [API](#api)
35
+ - [Where `Fiber.await` throws](#where-fiberawait-throws)
36
+ - [Error codes](#error-codes)
37
+ - [Limits](#limits)
38
+ - [Upgrading Node.js](#upgrading-nodejs)
39
+ - [Environment variables](#environment-variables)
40
+ - [How it works](#how-it-works)
41
+ - [Performance](#performance)
42
+ - [Development](#development)
43
+ - [License](#license)
44
+
45
+ ## Requirements
46
+
47
+ - **Node.js 24 or 26.** Prebuilt binaries ship for both. Other versions build from source on
48
+ install, and load only if their thread-local variables are known (see
49
+ [Upgrading Node.js](#upgrading-nodejs)).
50
+ - **x64 Linux with glibc.** Not macOS, Windows, arm64 or musl (Alpine).
51
+ - **An unstripped `node` executable.** The addon reads the binary's symbol table. Official
52
+ builds and nvm/fnm/Volta downloads have it. Some distribution packages strip it, and the addon
53
+ then refuses to load with `ERR_FIBER_UNSUPPORTED_NODE`.
54
+ - **No CET shadow stacks.** A node built with shadow stacks (SHSTK) breaks any stack switching.
55
+
56
+ ## Install
57
+
58
+ ```sh
59
+ npm install @mrwinston/fibers
60
+ # or: pnpm add @mrwinston/fibers / yarn add @mrwinston/fibers
61
+ ```
62
+
63
+ On Node 24 and 26 the install uses the prebuilt binary and compiles nothing. On other versions
64
+ it compiles with node-gyp, which needs `g++`, `make` and `python3`.
65
+
66
+ The package is CommonJS with an ES module entry that re-exports it, so `import` and `require`
67
+ load the same copy. Only one copy may be loaded per process; a second copy throws
68
+ `ERR_FIBER_ALREADY_LOADED` when it loads (check with `npm ls @mrwinston/fibers`).
69
+
70
+ ## Usage
71
+
72
+ ### Run synchronous code in a fiber
73
+
74
+ `Fiber.run(fn)` starts a fiber and returns a promise of `fn`'s result. Inside the fiber,
75
+ `Fiber.await(promise)` suspends only that fiber until the promise settles. It returns the value
76
+ or throws the rejection:
77
+
78
+ ```js
79
+ const user = await Fiber.run(() => {
80
+ const response = Fiber.await(fetch("https://example.com/user/1"));
81
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
82
+ return Fiber.await(response.json());
83
+ });
84
+ ```
85
+
86
+ `fn` must be a plain function. If it returns a promise (an `async` function, for example), the
87
+ promise from `Fiber.run` rejects with `ERR_FIBER_RUN_RETURNED_PROMISE`.
88
+
89
+ ### Wrap async APIs once, call them synchronously
90
+
91
+ `Fiber.wrap(fn)` turns a promise-returning function into one that suspends the calling fiber.
92
+ This is the usual way to give shared synchronous code a server-side implementation:
93
+
94
+ ```js
95
+ // shared code: written synchronously, runs as-is on the client
96
+ function priceFor(Products, id) {
97
+ const product = Products.findOne({ _id: id });
98
+ return product.price * 1.21;
99
+ }
100
+
101
+ // server: the same interface, backed by the async MongoDB driver
102
+ const Products = {
103
+ findOne: Fiber.wrap((query) => collection.findOne(query)),
104
+ };
105
+
106
+ app.get("/price/:id", async (req, res) => {
107
+ res.json(await Fiber.run(() => priceFor(Products, req.params.id)));
108
+ });
109
+ ```
110
+
111
+ A wrapped function keeps `this`. Called outside a fiber, or anywhere `Fiber.await` would throw,
112
+ it throws **before** calling `fn`, so the work never starts unawaited.
113
+
114
+ ### Concurrency
115
+
116
+ Each fiber suspends on its own, so many requests can wait at once on one thread:
117
+
118
+ ```js
119
+ const results = await Promise.all(ids.map((id) => Fiber.run(() => priceFor(Products, id))));
120
+ ```
121
+
122
+ A fiber can start other fibers (`Fiber.run` inside a fiber), and await them with
123
+ `Fiber.await(Fiber.run(...))`.
124
+
125
+ ### AsyncLocalStorage, workers and custom promises
126
+
127
+ - Each fiber has its own AsyncLocalStorage context. A fiber starts in the context of its
128
+ `Fiber.run` caller and keeps it across awaits.
129
+ - Works in worker threads. Each thread has its own fibers, pool, pool size and refused-await
130
+ handler. A new worker starts with the pool size of the thread that created it. The stack size
131
+ is one setting for the whole process.
132
+ - `Fiber.run` and `Fiber.await` use the engine's `Promise`, even when the global `Promise` was
133
+ replaced (bluebird and similar).
134
+
135
+ ### Modules with top-level await
136
+
137
+ When `require()` runs in a fiber, the module's top level may use `Fiber.await`. While it is
138
+ suspended there, `require()` of that module (or of a module still requiring it) from another
139
+ fiber or the root throws `ERR_FIBER_REQUIRE_IN_PROGRESS`, instead of returning half-initialized
140
+ exports. Require shared modules before the fibers that use them start. `import` is not affected:
141
+ it evaluates modules outside fibers.
142
+
143
+ ## API
144
+
145
+ All functions are static methods of `Fiber`. TypeScript types are included.
146
+
147
+ ### `Fiber.run<T>(fn: () => T): Promise<T>`
148
+
149
+ Runs `fn` in a new fiber. `fn` runs synchronously up to its first `Fiber.await`. The promise
150
+ resolves with `fn`'s return value or rejects with what it throws. Rejects with
151
+ `ERR_FIBER_RUN_RETURNED_PROMISE` if `fn` returns a promise. Rejects with a `RangeError` with
152
+ code `ERR_FIBER_STACK_ALLOC` if no stack can be mapped.
153
+
154
+ ### `Fiber.await<T>(value: T | PromiseLike<T>): T`
155
+
156
+ Inside a fiber: suspends the fiber until `value` (a promise, thenable or plain value) settles,
157
+ then returns its value or throws its rejection. Outside a fiber
158
+ (`ERR_FIBER_AWAIT_OUTSIDE_FIBER`), and in the places listed under
159
+ [Where `Fiber.await` throws](#where-fiberawait-throws), it throws without suspending.
160
+
161
+ ### `Fiber.wrap<A, R>(fn: (...args: A) => R | PromiseLike<R>): (...args: A) => R`
162
+
163
+ Returns a synchronous version of `fn` for use inside fibers. It is equivalent to
164
+ `(...args) => Fiber.await(fn(...args))`, but it checks first whether it may suspend, and throws
165
+ before calling `fn` if not.
166
+
167
+ ### `Fiber.inFiber(): boolean`
168
+
169
+ Whether the caller is running inside a fiber.
170
+
171
+ ### `Fiber.stats(): FiberStats`
172
+
173
+ Counters for the current JS thread:
174
+
175
+ | field | meaning |
176
+ | --------------- | ------------------------------------------------------------------------ |
177
+ | `live` | fibers started and not finished |
178
+ | `fibersCreated` | fibers created so far (finished ones are reused) |
179
+ | `pooled` | finished fibers that kept their stack memory, ready for reuse |
180
+ | `released` | finished fibers whose stack memory was released (beyond the pool size) |
181
+ | `poolSize` | the current pool size (see `setPoolSize`) |
182
+ | `switches` | switches between fibers since the addon loaded |
183
+
184
+ ### `Fiber.setStackSize(bytes: number): void`
185
+
186
+ Sets the stack size of fibers created afterwards. Default and minimum: 2 MiB. JS gets all but
187
+ 1 MiB, which is kept for C++ frames, so by default a fiber can recurse about as deep as the main
188
+ thread. Node's `--stack-size` does not apply to fibers. Call it before the first `Fiber.run` in
189
+ the process; afterwards it throws `ERR_FIBER_STACK_SIZE_LOCKED`.
190
+
191
+ ### `Fiber.setPoolSize(count: number): void`
192
+
193
+ How many finished fibers keep their stack memory for fast reuse. Default: 120. Finished fibers
194
+ beyond that release their stack's pages back to the OS. Set per JS thread; a worker starts with
195
+ the value of the thread that created it.
196
+
197
+ ### `Fiber.setRefusedAwaitHandler(handler?: (reason, refusal) => unknown): void`
198
+
199
+ When `Fiber.await` throws instead of suspending, nobody waits for its promise. If that promise
200
+ later rejects, `handler(reason, refusal)` receives the rejection and the error the refused await
201
+ threw, for example to log both. By default (or with `undefined`) the rejection is ignored, so it
202
+ can't crash the process as an unhandled rejection. The same goes for a promise that `fn` returns
203
+ to `Fiber.run` (`ERR_FIBER_RUN_RETURNED_PROMISE`): nobody waits for it either, and if it rejects
204
+ the handler gets that rejection, with an `ERR_FIBER_RUN_RETURNED_PROMISE` error as `refusal`.
205
+ Whatever the handler throws does become an unhandled rejection. Set per JS thread.
206
+
207
+ ```js
208
+ Fiber.setRefusedAwaitHandler((reason, refusal) => {
209
+ logger.warn({ reason, refusal }, "rejected promise of a refused Fiber.await");
210
+ });
211
+ ```
212
+
213
+ ## Where `Fiber.await` throws
214
+
215
+ Besides outside a fiber, `Fiber.await` (and every `Fiber.wrap`'d function) throws instead of
216
+ suspending in places where suspending would corrupt state shared with other fibers:
217
+
218
+ | where | `code` |
219
+ | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
220
+ | inside an `AsyncResource` scope the fiber entered itself (`runInAsyncScope`, `bind`, `EventEmitterAsyncResource`) | `ERR_FIBER_AWAIT_IN_ASYNC_SCOPE` |
221
+ | inside JS run by the inspector (`Session#post("Runtime.evaluate")`, the DevTools console) | `ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE` |
222
+ | inside code that `vm` evaluates (`vm.runIn*Context`, `vm.Script#runIn*Context`, `vm.SourceTextModule#evaluate`) | `ERR_FIBER_AWAIT_IN_VM` |
223
+ | inside JS that WebAssembly calls under JSPI (an import called from a `WebAssembly.promising` function, before the wasm first suspends) | `ERR_FIBER_AWAIT_IN_JSPI` |
224
+
225
+ What still works:
226
+
227
+ - **vm:** awaiting before or after the vm call, and in a fiber that the vm code starts itself
228
+ (`Fiber.run` inside the vm code), which has its own stack.
229
+ - **JSPI:** awaiting the promise of the `promising` function, making the import a
230
+ `WebAssembly.Suspending`, or starting a fiber inside the import.
231
+
232
+ <details>
233
+ <summary>How the vm and JSPI checks work, and what they don't cover</summary>
234
+
235
+ Loading the package wraps `vm.Script.prototype.runInContext` and `.runInThisContext` (every
236
+ `vm.runIn*` goes through them), `vm.Module.prototype.evaluate` (with
237
+ `--experimental-vm-modules`) and `WebAssembly.promising`. The wrappers count evaluations in
238
+ progress on the current fiber, and `Fiber.await` compares the count with 0, at no measurable
239
+ cost.
240
+
241
+ Not covered:
242
+
243
+ - references to those methods taken before the package was loaded;
244
+ - functions that belong to a vm context but are called outside a vm evaluation (from
245
+ `vm.compileFunction`, or created by vm code and called later). These run as plain calls of
246
+ the fiber.
247
+
248
+ Why vm is refused: a vm call is a synchronous step of its caller. With `timeout` or
249
+ `breakOnSigint`, Node's watchdog terminates whatever JS runs when it fires, and a fiber
250
+ suspended inside past the timeout aborted the process. Why JSPI is refused: V8 keeps the wasm
251
+ stack it switched to per isolate, not per fiber, so two fibers suspended there aborted the
252
+ process.
253
+
254
+ </details>
255
+
256
+ ## Error codes
257
+
258
+ Errors from this package carry a `code` and a stack trace that starts at your call of
259
+ `Fiber.run`, `Fiber.await`, a `Fiber.wrap`'d function or `Fiber.set*`. The exceptions are
260
+ `ERR_FIBER_RUN_RETURNED_PROMISE` when `fn` returns a promise only after it first suspended (that
261
+ error shows the async callers of `Fiber.run`), and the load-time codes, which are thrown by the
262
+ `import` or `require` of the package.
263
+
264
+ | code | thrown by | meaning |
265
+ | ------------------------------------- | --------------------------------- | ---------------------------------------------------------------------------- |
266
+ | `ERR_FIBER_RUN_RETURNED_PROMISE` | `Fiber.run` (rejection) | `fn` returned a promise; pass a synchronous function |
267
+ | `ERR_FIBER_AWAIT_IN_ASYNC_SCOPE` | `Fiber.await`, wrapped functions | see [Where `Fiber.await` throws](#where-fiberawait-throws) |
268
+ | `ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE` | `Fiber.await`, wrapped functions | same |
269
+ | `ERR_FIBER_AWAIT_IN_VM` | `Fiber.await`, wrapped functions | same |
270
+ | `ERR_FIBER_AWAIT_IN_JSPI` | `Fiber.await`, wrapped functions | same |
271
+ | `ERR_FIBER_REQUIRE_IN_PROGRESS` | `require()` | another fiber is still evaluating that module (see [Modules with top-level await](#modules-with-top-level-await)) |
272
+ | `ERR_FIBER_AWAIT_OUTSIDE_FIBER` | `Fiber.await`, wrapped functions | called outside `Fiber.run` |
273
+ | `ERR_FIBER_STACK_SIZE_LOCKED` | `Fiber.setStackSize` | called after the first `Fiber.run` in the process |
274
+ | `ERR_FIBER_STACK_ALLOC` | `Fiber.run` (`RangeError`) | no memory could be mapped for a fiber stack |
275
+ | `ERR_FIBER_ALREADY_LOADED` | `import` / `require` | another copy of the package is already loaded in this process |
276
+ | `ERR_FIBER_UNSUPPORTED_PLATFORM` | `import` / `require` | not x64 Linux |
277
+ | `ERR_FIBER_UNSUPPORTED_NODE` | `import` / `require` | this `node` binary can't be used: stripped, unknown thread-locals, or an unexpected layout; the message says which |
278
+
279
+ Errors for invalid arguments (`TypeError`, `RangeError`) have no code.
280
+
281
+ ## Limits
282
+
283
+ - **A fiber always runs to completion.** It can't be cancelled or restarted. A fiber that awaits
284
+ a promise that never settles stays suspended until its thread ends, with its stack and
285
+ everything it references; the garbage collector can't free it.
286
+ - **Memory per fiber.** Each live fiber reserves 2 MiB of virtual memory and 2 memory mappings.
287
+ With the default `vm.max_map_count` (65530), about 30,000 fibers can be suspended at once.
288
+ There is no concurrency cap; beyond that, `Fiber.run` rejects with a `RangeError`.
289
+ - **Stacks keep their address.** Beyond `poolSize`, finished fibers release their memory (RSS
290
+ and commit charge go back), but their address range and mappings stay until the thread ends,
291
+ so the mapping count stays at its peak. About 15 KB per peak-concurrent fiber also stays
292
+ inside V8. Stacks are kept because V8 stores per-thread data, including the stack limit, for
293
+ each fiber; moving a stack would require discarding that data, which breaks the CPU profiler.
294
+ - **Process exit.** Suspended fibers end without running their `finally` blocks.
295
+ - **CPU profiles** don't include samples taken while a fiber runs.
296
+ - **Wasm code memory is not reclaimed.** The addon turns on `--no-wasm-code-gc`, because V8
297
+ aborts once `fetch()` (which uses wasm) runs while fibers are suspended. See
298
+ `FIBERS_WASM_CODE_GC` below.
299
+ - **C++ state across a suspending callback.** When C++ calls JS that suspends (a `toJSON` or
300
+ getter that awaits, for example), other fibers run while that C++ frame waits. Suspending
301
+ inside `JSON.stringify`, `JSON.parse` revivers, `v8.serialize`, `structuredClone`, proxy traps
302
+ and `require(esm)` is tested with many fibers at once. While one fiber is suspended inside
303
+ `Error.prepareStackTrace`, other fibers get the default stack format.
304
+
305
+ ## Upgrading Node.js
306
+
307
+ The addon swaps V8's internal thread-local variables per fiber, and checks at load time that it
308
+ knows every thread-local of the running `node` binary. A new Node.js version can add some. The
309
+ addon then **refuses to load**, on purpose, with `ERR_FIBER_UNSUPPORTED_NODE` and a message
310
+ such as:
311
+
312
+ ```
313
+ refusing to load: this node binary has thread-local variables that fibers does not know: ...
314
+ ```
315
+
316
+ It needs a new release of this package that classifies them; test a Node.js upgrade before
317
+ deploying it. `node -e "import('@mrwinston/fibers').then(m => console.log(m.Fiber._tlsLayout()))"`
318
+ prints how the running binary's thread-locals are handled.
319
+
320
+ ## Environment variables
321
+
322
+ | variable | effect |
323
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
324
+ | `FIBERS_WASM_CODE_GC=1` | Keeps V8's wasm code GC on. Reclaims wasm code memory, but `fetch()` while fibers are suspended then aborts the process. |
325
+ | `FIBERS_ALLOW_UNKNOWN_TLS=1` | Loads despite unknown thread-locals. For diagnosis only; never in production. |
326
+ | `FIBERS_NO_CHECKS=1` | Skips the safety checks done at every switch. |
327
+
328
+ ## How it works
329
+
330
+ Every fiber runs on the JS thread's own OS thread, on its own stack (from
331
+ [libcoro](http://software.schmorp.de/pkg/libcoro.html), as in node-fibers). Switching fibers
332
+ releases V8 with `v8::Unlocker` and re-acquires it with `v8::Locker`, so V8 treats each fiber as
333
+ a separate thread.
334
+
335
+ V8 keeps the identity of the current thread (its thread id, stack start and a few scope
336
+ variables) in C++ `thread_local` variables, which no API reaches. The addon finds every
337
+ thread-local of the `node` executable through its ELF symbol table, classifies each one by name,
338
+ and saves and restores the per-fiber ones at every switch:
339
+
340
+ | class | variables | at a switch |
341
+ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
342
+ | swap | V8 `thread_id`, `thread_stack_start`, assert-scope bits, wasm code-ref scope, Node's `is_in_uncaught_exception` / `is_retrieving_js_stacktrace` | saved and restored per fiber |
343
+ | set by `Isolate::Enter` | `g_current_isolate_`, per-isolate thread data, marking barrier, local heap | must be empty after a full exit |
344
+ | must be zero | compiler, wasm trap handler, layout-change and `dlopen` scopes | checked |
345
+ | leave | OS-thread caches, certificate store, library state | untouched (same OS thread) |
346
+
347
+ Other details:
348
+
349
+ - Finished fibers are reused, never deleted. Each keeps the V8 thread id it got first, because
350
+ V8 hands ids out from a process-wide counter and aborts after 2^31.
351
+ - Each fiber's JS stack limit comes from its own stack, not from `--stack-size`.
352
+ - AsyncLocalStorage's context is saved per fiber, and `TerminateExecution` inside a fiber is
353
+ passed on to its caller. Suspended fibers are ended when the environment shuts down.
354
+
355
+ | file | contents |
356
+ | ------------------------- | -------------------------------------------------------------------------------- |
357
+ | `native/libcoro/` | libcoro, as vendored by node-fibers: stack allocation and the x86-64 switch |
358
+ | `native/coroutine.{h,cc}` | coroutines on libcoro stacks: pool, `transfer`, `finish` |
359
+ | `native/fibers.cc` | the native core: `start`, `suspend`, `resume`, Node/V8 integration |
360
+ | `native/tls.{h,cc}` | finds, checks and swaps V8's thread-locals; cites the V8 source behind each rule |
361
+ | `src/` | the `Fiber` API on top of the native core, and the vm/JSPI/`require` guards |
362
+
363
+ ## Performance
364
+
365
+ Node 26.13.1, 16 CPUs (`bench/bench.mjs`; results vary ±20% between runs):
366
+
367
+ | | fibers | async/await |
368
+ | --------------------------------------------------------- | ----------------- | ------------- |
369
+ | `Fiber.await` of a resolved value | 1.05–1.14 µs | 0.04 µs |
370
+ | `Fiber.run(() => 1)` | 1.5 µs | 0.1–0.2 µs |
371
+ | 1024 fibers awaiting `setImmediate`, per await | 2.7–2.9 µs | 0.3–0.5 µs |
372
+ | 500 workers (CPU + 1 ms timer + `setImmediate`), 2 s | 76–87k ops/s | 95–120k ops/s |
373
+ | same: event-loop lag p99 / 5 ms ping delay p95 | 8–10 / 6.6–7.8 ms | 5–8 / 3–7 ms |
374
+
375
+ The cost of a switch does not grow with the number of suspended fibers.
376
+
377
+ ## Development
378
+
379
+ Needs `g++`, `make`, `python3` and pnpm.
380
+
381
+ ```sh
382
+ pnpm install
383
+ pnpm run build # typecheck, dist/ (tsdown), build/Release/fibers.node
384
+ pnpm run prebuilds # prebuilds/linux-x64/node-{137,147}/ for Node 24 and 26 (via fnm)
385
+ pnpm test # the test suite (needs pnpm run build first)
386
+ pnpm run test:stress # the suite under 3 GC/JIT stress settings, as on release tags
387
+ node bench/bench.mjs # benchmark
388
+ ```
389
+
390
+ The tests are in `test/`. Each `<subject>.test.mjs` runs with `node --test` and imports
391
+ `helpers.mjs`, which fails the file if the build is older than its sources and checks after
392
+ every test that no fiber is left live and nothing the test registered with `track()` leaked.
393
+ Plain `node:assert` assertions check what this README promises; `observed.*` assertions check
394
+ details it doesn't (message text, exact counters), and say so when they fail. Anything that
395
+ needs its own Node flags, stack size, resource limit or environment variable, or that may crash
396
+ or exit, runs in a child process: `runChild("fixture-<subject>.mjs", { caseName, flags, env })`
397
+ starts `test/fixture-<subject>.mjs`, which sends its results back with `report()`.
398
+ `readme.test.mjs` checks that every error code in the source is in this README and tested, and
399
+ that every API heading has a test.
400
+
401
+ CI (Bitbucket Pipelines) runs the suite on Node 24 and 26 for every push, and the stress pass on
402
+ `v*` tags.
403
+ Pushing a `v*` tag that matches `package.json`'s version publishes to npm.
404
+
405
+ `prototypes/` holds earlier approaches (a V8 patch, an addon with an OS thread per fiber, and a
406
+ first version of this design). They are kept for reference and are not part of the package.
407
+
408
+ ## License
409
+
410
+ MIT; see [LICENSE](LICENSE). The native code is derived from
411
+ [node-fibers](https://github.com/laverdet/node-fibers) (MIT, Copyright 2011 Marcel Laverdet).
412
+ `native/libcoro/` is libcoro by Marc Alexander Lehmann, under the BSD 2-clause license or GPL 2+ (see
413
+ `native/libcoro/LICENSE`).
package/binding.gyp ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ 'targets': [{
3
+ 'target_name': 'fibers',
4
+ 'sources': ['native/fibers.cc', 'native/coroutine.cc', 'native/tls.cc', 'native/libcoro/coro.c'],
5
+ # libcoro's hand-written x86-64 switch, and a 64 KiB guard region under every stack
6
+ # (node-fibers: one page).
7
+ 'defines': ['CORO_ASM', 'CORO_GUARDPAGES=16'],
8
+ 'conditions': [
9
+ ['OS != "linux" or target_arch != "x64"', {'type': 'none', 'sources': []}],
10
+ ],
11
+ 'cflags': ['-fstack-protector-strong'],
12
+ 'cflags_c': ['-std=gnu11', '-O2'],
13
+ 'cflags_cc': ['-O2', '-Wall', '-Wno-unused-parameter', '-Wno-cast-function-type', '-std=gnu++20'],
14
+ 'ldflags': ['-Wl,-z,relro,-z,now', '-Wl,-z,noexecstack'],
15
+ }],
16
+ }