@mrwinston/fibers 0.0.0-stage → 0.2.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 +26 -0
- package/README.md +418 -2
- package/binding.gyp +16 -0
- package/dist/index.cjs +286 -0
- package/dist/index.d.cts +81 -0
- package/dist/index.js +1 -0
- package/native/coroutine.cc +251 -0
- package/native/coroutine.h +133 -0
- package/native/fibers.cc +524 -0
- package/native/libcoro/LICENSE +26 -0
- package/native/libcoro/README +6 -0
- package/native/libcoro/UPSTREAM +1 -0
- package/native/libcoro/coro.c +713 -0
- package/native/libcoro/coro.h +420 -0
- package/native/tls.cc +516 -0
- package/native/tls.h +102 -0
- package/package.json +61 -5
- package/prebuilds/linux-x64/node-137/fibers.node +0 -0
- package/prebuilds/linux-x64/node-147/fibers.node +0 -0
- package/scripts/install.mjs +47 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Coroutines on libcoro stacks, one pool per JS thread (main thread, each worker).
|
|
2
|
+
// fls_data holds the coroutine's V8 thread-locals (tls.h), swapped on every transfer.
|
|
3
|
+
// Derived from node-fibers' src/coroutine.h (laverdet/node-fibers, MIT, see LICENSE).
|
|
4
|
+
#pragma once
|
|
5
|
+
|
|
6
|
+
#include <node.h>
|
|
7
|
+
#include <stdlib.h>
|
|
8
|
+
#include <string>
|
|
9
|
+
#include "libcoro/coro.h"
|
|
10
|
+
#include "tls.h"
|
|
11
|
+
|
|
12
|
+
class Coroutine {
|
|
13
|
+
public:
|
|
14
|
+
typedef void(entry_t)(void*);
|
|
15
|
+
|
|
16
|
+
private:
|
|
17
|
+
coro_context context;
|
|
18
|
+
coro_stack stack;
|
|
19
|
+
fibers::TlsImage fls_data;
|
|
20
|
+
entry_t* entry;
|
|
21
|
+
void* arg;
|
|
22
|
+
|
|
23
|
+
~Coroutine();
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Constructor for currently running "fiber". This is really just original thread, but we
|
|
27
|
+
* need a way to get back into the main thread after yielding to a fiber. Basically this
|
|
28
|
+
* shouldn't be called from anywhere.
|
|
29
|
+
*/
|
|
30
|
+
Coroutine();
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* This constructor will actually create a new fiber context. Execution does not begin
|
|
34
|
+
* until you call run() for the first time.
|
|
35
|
+
*/
|
|
36
|
+
Coroutine(entry_t& entry, void* arg);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Resets the context of this coroutine from the start. Used to recyle old coroutines.
|
|
40
|
+
*/
|
|
41
|
+
void reset(entry_t* entry, void* arg);
|
|
42
|
+
|
|
43
|
+
static void trampoline(void* that);
|
|
44
|
+
void transfer(Coroutine& next);
|
|
45
|
+
bool allocate_stack();
|
|
46
|
+
void start_context();
|
|
47
|
+
void release_stack();
|
|
48
|
+
bool reacquire_stack();
|
|
49
|
+
|
|
50
|
+
public:
|
|
51
|
+
// Per JS thread. src/index.ts gives a new worker the value of the thread that created it.
|
|
52
|
+
static thread_local size_t pool_size;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Returns the currently-running fiber.
|
|
56
|
+
*/
|
|
57
|
+
static Coroutine& current();
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Create a new fiber.
|
|
61
|
+
*/
|
|
62
|
+
static Coroutine* create_fiber(entry_t* entry, void* arg = NULL);
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Initialize the library on this JS thread. Returns an error message, or "" when fibers
|
|
66
|
+
* can run here.
|
|
67
|
+
*/
|
|
68
|
+
static std::string init(v8::Isolate* isolate);
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Frees this JS thread's pooled coroutines (environment teardown, all fibers finished).
|
|
72
|
+
*/
|
|
73
|
+
static void shutdown();
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Set the size of coroutines created by this library. Since coroutines are pooled the stack
|
|
77
|
+
* size is global instead of per-coroutine. Stack is measured in sizeof(void*), so
|
|
78
|
+
* set_stack_size(128) -> 512 bytes or 1kb. Returns false (and changes nothing) once a
|
|
79
|
+
* coroutine was created in this process: pooled stacks keep their size.
|
|
80
|
+
*/
|
|
81
|
+
static bool set_stack_size(unsigned int size);
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The stack size of coroutines created by this library, in bytes (process-wide).
|
|
85
|
+
*/
|
|
86
|
+
static size_t stack_size_bytes();
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Get the number of coroutines that have been created (on this JS thread).
|
|
90
|
+
*/
|
|
91
|
+
static size_t coroutines_created();
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Number of finished coroutines waiting for reuse (on this JS thread).
|
|
95
|
+
*/
|
|
96
|
+
static size_t pooled();
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Start or resume execution in this fiber. Note there is no explicit yield() function,
|
|
100
|
+
* you must manually run another fiber.
|
|
101
|
+
*/
|
|
102
|
+
void run();
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Whether the coroutine that finishes next releases its stack's pages (the pool of
|
|
106
|
+
* finished coroutines that keep their pages is full). Its stack keeps its address.
|
|
107
|
+
*/
|
|
108
|
+
static bool finishing_releases_stack();
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Number of finished coroutines whose stack pages were released, waiting for reuse (on
|
|
112
|
+
* this JS thread).
|
|
113
|
+
*/
|
|
114
|
+
static size_t released();
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Finish this coroutine.. This will halt execution of this coroutine and resume execution
|
|
118
|
+
* of `next`. If you do not call this function, and instead just return from `entry` the
|
|
119
|
+
* application will exit. This function may or may not actually return. `release_stack`
|
|
120
|
+
* (finishing_releases_stack()) releases its stack's pages once control is on `next`.
|
|
121
|
+
*/
|
|
122
|
+
void finish(Coroutine& next, bool release_stack);
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Returns address of the lowest usable byte in this Coroutine's stack.
|
|
126
|
+
*/
|
|
127
|
+
void* bottom() const;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Returns the address just above this Coroutine's stack (where it starts).
|
|
131
|
+
*/
|
|
132
|
+
void* top() const;
|
|
133
|
+
};
|
package/native/fibers.cc
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
// The native core that src/index.ts builds Fiber.run / Fiber.await on:
|
|
2
|
+
// start(fn) runs fn in a new fiber now, until it suspends or ends
|
|
3
|
+
// suspend(register) checks that this fiber may suspend, calls register(id, generation) and
|
|
4
|
+
// suspends; resume(id, generation) (once, from anywhere) continues it
|
|
5
|
+
// inFiber()
|
|
6
|
+
// A fiber starts once, runs until fn returns or throws, and is never cancelled or restarted.
|
|
7
|
+
// Switch() runs a fiber's coroutine, Suspend() runs the coroutine that started or resumed it,
|
|
8
|
+
// RunFiber() is the entry point of a new fiber and finishes its coroutine (which goes back to the
|
|
9
|
+
// pool).
|
|
10
|
+
//
|
|
11
|
+
// "Modern V8 / Node" below: the switch exits the isolate completely, each fiber has its own
|
|
12
|
+
// AsyncLocalStorage context, suspending is refused where Node's shared state would break,
|
|
13
|
+
// TerminateExecution in a fiber reaches its caller, and suspended fibers are ended when the
|
|
14
|
+
// environment shuts down.
|
|
15
|
+
//
|
|
16
|
+
// Derived from node-fibers' src/fibers.cc (laverdet/node-fibers, MIT, see LICENSE).
|
|
17
|
+
#include <node.h>
|
|
18
|
+
#include <v8.h>
|
|
19
|
+
|
|
20
|
+
#include <cstring>
|
|
21
|
+
#include <unordered_map>
|
|
22
|
+
#include <vector>
|
|
23
|
+
|
|
24
|
+
#include "coroutine.h"
|
|
25
|
+
#include "tls.h"
|
|
26
|
+
|
|
27
|
+
using namespace v8;
|
|
28
|
+
|
|
29
|
+
namespace {
|
|
30
|
+
|
|
31
|
+
// --- Modern V8 / Node --------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
#if V8_MAJOR_VERSION >= 14
|
|
34
|
+
using CpedType = Data;
|
|
35
|
+
Local<CpedType> GetCped(Isolate* isolate) { return isolate->GetContinuationPreservedEmbedderDataV2(); }
|
|
36
|
+
void SetCped(Isolate* isolate, Local<CpedType> v) { isolate->SetContinuationPreservedEmbedderDataV2(v); }
|
|
37
|
+
#else
|
|
38
|
+
using CpedType = Value;
|
|
39
|
+
Local<CpedType> GetCped(Isolate* isolate) { return isolate->GetContinuationPreservedEmbedderData(); }
|
|
40
|
+
void SetCped(Isolate* isolate, Local<CpedType> v) { isolate->SetContinuationPreservedEmbedderData(v); }
|
|
41
|
+
#endif
|
|
42
|
+
|
|
43
|
+
Local<String> NewLatin1String(Isolate* isolate, const char* string) {
|
|
44
|
+
return String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(string)).ToLocalChecked();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
using ErrorConstructor = Local<Value> (*)(Local<String>, Local<Value>);
|
|
48
|
+
|
|
49
|
+
void ThrowCoded(Isolate* isolate, Local<String> message, const char* code,
|
|
50
|
+
ErrorConstructor make = Exception::Error) {
|
|
51
|
+
Local<Object> error = make(message, Local<Value>()).As<Object>();
|
|
52
|
+
error->Set(isolate->GetCurrentContext(), NewLatin1String(isolate, "code"), NewLatin1String(isolate, code)).Check();
|
|
53
|
+
isolate->ThrowException(error);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
void ThrowCoded(Isolate* isolate, const char* message, const char* code,
|
|
57
|
+
ErrorConstructor make = Exception::Error) {
|
|
58
|
+
ThrowCoded(isolate, NewLatin1String(isolate, message), code, make);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Also in src/errors.ts (OUTSIDE_FIBER_MESSAGE): both "outside a fiber" errors are the same.
|
|
62
|
+
constexpr const char* kOutsideFiberMessage =
|
|
63
|
+
"Fiber.await and Fiber.wrap'd functions can only be called inside Fiber.run";
|
|
64
|
+
|
|
65
|
+
#define THROW(x, m) return (void)isolate->ThrowException(x(NewLatin1String(isolate, m)))
|
|
66
|
+
|
|
67
|
+
// The part of every fiber stack that JS may not use, for the C++ frames below it (V8 runtime
|
|
68
|
+
// functions, RegExp compilation, Node bindings). The JS stack limit of each fiber is its stack's
|
|
69
|
+
// bottom plus this, independent of --stack-size.
|
|
70
|
+
constexpr size_t kCppStackReserve = 1024 * 1024;
|
|
71
|
+
|
|
72
|
+
constexpr size_t kCentralStackSize = size_t{1} << 36;
|
|
73
|
+
|
|
74
|
+
void SetFiberStackLimit(Isolate* isolate, uintptr_t limit) {
|
|
75
|
+
void* stack_start = fibers::ExchangeStackStart(reinterpret_cast<void*>(limit + kCentralStackSize));
|
|
76
|
+
isolate->SetStackLimit(limit);
|
|
77
|
+
fibers::ExchangeStackStart(stack_start);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Set by a fiber that was ended by TerminateExecution (process.exit(), worker.terminate()) for
|
|
81
|
+
// the coroutine it finishes into, which then re-raises the termination.
|
|
82
|
+
thread_local bool tl_terminate_pending = false;
|
|
83
|
+
thread_local double tl_switches = 0;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Hands control to `target` and returns when someone hands it back. Node enters the isolate
|
|
87
|
+
* more than once, and V8 keeps the entered isolate in thread-locals that tls.cc must find empty,
|
|
88
|
+
* so exit it completely before the Unlocker. AsyncLocalStorage's context (V8's "continuation
|
|
89
|
+
* preserved embedder data") is one slot per isolate: keep ours on this stack while we are
|
|
90
|
+
* suspended.
|
|
91
|
+
*/
|
|
92
|
+
void ReleaseAndRun(Isolate* isolate, Coroutine& target) {
|
|
93
|
+
HandleScope scope(isolate);
|
|
94
|
+
Global<CpedType> cped(isolate, GetCped(isolate));
|
|
95
|
+
int depth = 0;
|
|
96
|
+
while (isolate->IsCurrent()) {
|
|
97
|
+
isolate->Exit();
|
|
98
|
+
++depth;
|
|
99
|
+
}
|
|
100
|
+
fibers::CheckTlsAfterExit();
|
|
101
|
+
++tl_switches;
|
|
102
|
+
{
|
|
103
|
+
Unlocker unlocker(isolate); // archives this V8 "thread" (handle scopes, JS frames, ...)
|
|
104
|
+
target.run();
|
|
105
|
+
}
|
|
106
|
+
for (int ii = 0; ii < depth; ++ii) {
|
|
107
|
+
isolate->Enter();
|
|
108
|
+
}
|
|
109
|
+
SetCped(isolate, cped.Get(isolate));
|
|
110
|
+
if (tl_terminate_pending) {
|
|
111
|
+
tl_terminate_pending = false;
|
|
112
|
+
isolate->TerminateExecution();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// V8's Isolate::Iterate visits the isolate-wide AsyncLocalStorage slot once per archived thread
|
|
117
|
+
// (each suspended fiber is one) and corrupts it. Hold the value aside during every GC.
|
|
118
|
+
struct CpedGcGuard {
|
|
119
|
+
Global<CpedType> saved;
|
|
120
|
+
bool active = false;
|
|
121
|
+
static void Prologue(Isolate* isolate, GCType, GCCallbackFlags, void* data) {
|
|
122
|
+
CpedGcGuard* guard = static_cast<CpedGcGuard*>(data);
|
|
123
|
+
if (guard->active) return;
|
|
124
|
+
HandleScope scope(isolate);
|
|
125
|
+
guard->saved.Reset(isolate, GetCped(isolate));
|
|
126
|
+
SetCped(isolate, Undefined(isolate));
|
|
127
|
+
guard->active = true;
|
|
128
|
+
}
|
|
129
|
+
static void Epilogue(Isolate* isolate, GCType, GCCallbackFlags, void* data) {
|
|
130
|
+
CpedGcGuard* guard = static_cast<CpedGcGuard*>(data);
|
|
131
|
+
if (!guard->active) return;
|
|
132
|
+
HandleScope scope(isolate);
|
|
133
|
+
SetCped(isolate, guard->saved.Get(isolate));
|
|
134
|
+
guard->saved.Reset();
|
|
135
|
+
guard->active = false;
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// --- Fiber ------------------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
struct Fiber {
|
|
142
|
+
Isolate* isolate;
|
|
143
|
+
double id;
|
|
144
|
+
Global<Function> fn;
|
|
145
|
+
Global<Context> context;
|
|
146
|
+
Global<CpedType> initial_cped; // AsyncLocalStorage context of the start() caller
|
|
147
|
+
Coroutine* coroutine = nullptr;
|
|
148
|
+
Coroutine* entry = nullptr; // who started or last resumed it: control goes back there
|
|
149
|
+
bool suspended = false;
|
|
150
|
+
double generation = 0; // which suspend() a resume function belongs to
|
|
151
|
+
bool aborting = false; // environment teardown: end it with TerminateExecution
|
|
152
|
+
// Node's async ids and V8's microtasks-scope depth when the fiber last got control.
|
|
153
|
+
double base_async_id = 0;
|
|
154
|
+
double base_trigger_id = 0;
|
|
155
|
+
int base_microtasks_depth = 0;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
// Per JS thread.
|
|
159
|
+
struct ThreadData {
|
|
160
|
+
Isolate* isolate = nullptr;
|
|
161
|
+
Fiber* current = nullptr;
|
|
162
|
+
std::unordered_map<double, Fiber*> fibers; // started, not finished
|
|
163
|
+
double next_id = 1;
|
|
164
|
+
CpedGcGuard* cped_guard = nullptr;
|
|
165
|
+
};
|
|
166
|
+
thread_local ThreadData* tl_data = nullptr;
|
|
167
|
+
// What the function of a fiber that just ended threw, for whoever switched to it.
|
|
168
|
+
thread_local Global<Value> tl_exception;
|
|
169
|
+
|
|
170
|
+
void RecordScopeBase(Fiber& fiber) {
|
|
171
|
+
fiber.base_async_id = node::AsyncHooksGetExecutionAsyncId(fiber.isolate);
|
|
172
|
+
fiber.base_trigger_id = node::AsyncHooksGetTriggerAsyncId(fiber.isolate);
|
|
173
|
+
fiber.base_microtasks_depth = MicrotasksScope::GetCurrentDepth(fiber.isolate);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Suspending must not leave state behind that is shared with whoever runs next: Node's async-id
|
|
178
|
+
* stack, and V8's microtasks scope while the inspector runs code.
|
|
179
|
+
*/
|
|
180
|
+
bool CheckCanSuspend(Fiber& fiber) {
|
|
181
|
+
Isolate* isolate = fiber.isolate;
|
|
182
|
+
if (node::AsyncHooksGetExecutionAsyncId(isolate) != fiber.base_async_id ||
|
|
183
|
+
node::AsyncHooksGetTriggerAsyncId(isolate) != fiber.base_trigger_id) {
|
|
184
|
+
ThrowCoded(isolate,
|
|
185
|
+
"Fiber.await cannot suspend a fiber inside an async_hooks scope "
|
|
186
|
+
"(AsyncResource.runInAsyncScope, AsyncResource.bind, EventEmitterAsyncResource): "
|
|
187
|
+
"Node's async-id stack is shared by all fibers and the process would abort. Call "
|
|
188
|
+
"Fiber.await outside the scope.",
|
|
189
|
+
"ERR_FIBER_AWAIT_IN_ASYNC_SCOPE");
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
if (MicrotasksScope::GetCurrentDepth(isolate) > fiber.base_microtasks_depth) {
|
|
193
|
+
ThrowCoded(isolate,
|
|
194
|
+
"Fiber.await cannot suspend inside code run by the inspector (inspector.Session#post "
|
|
195
|
+
"'Runtime.evaluate' or 'Runtime.callFunctionOn', DevTools console): V8 runs no promise "
|
|
196
|
+
"reactions until that code returns, so the fiber could never resume",
|
|
197
|
+
"ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE");
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Runs `fiber` (from the start or where it suspended) until it suspends or ends, then rethrows
|
|
205
|
+
* what its function threw if it ended that way. `fiber` may be gone afterwards.
|
|
206
|
+
*/
|
|
207
|
+
void Switch(Isolate* isolate, Fiber* fiber) {
|
|
208
|
+
fiber->entry = &Coroutine::current();
|
|
209
|
+
Fiber* last = tl_data->current;
|
|
210
|
+
tl_data->current = fiber;
|
|
211
|
+
ReleaseAndRun(isolate, *fiber->coroutine);
|
|
212
|
+
tl_data->current = last;
|
|
213
|
+
if (!tl_exception.IsEmpty()) {
|
|
214
|
+
Local<Value> exception = tl_exception.Get(isolate);
|
|
215
|
+
tl_exception.Reset();
|
|
216
|
+
isolate->ThrowException(exception);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* The entry point of a new fiber, on its own stack.
|
|
222
|
+
*/
|
|
223
|
+
void RunFiber(void* data) {
|
|
224
|
+
Fiber* fiber = static_cast<Fiber*>(data);
|
|
225
|
+
Isolate* isolate = fiber->isolate;
|
|
226
|
+
Coroutine* entry;
|
|
227
|
+
Coroutine* coroutine;
|
|
228
|
+
|
|
229
|
+
// New C scope so that the stack-allocated objects are destroyed before Coroutine::finish,
|
|
230
|
+
// which does not return until the coroutine is reused for another fiber.
|
|
231
|
+
{
|
|
232
|
+
// A new V8 "thread", or the one this pooled coroutine had before.
|
|
233
|
+
Locker locker(isolate);
|
|
234
|
+
Isolate::Scope isolate_scope(isolate);
|
|
235
|
+
// Its JS stack limit comes from its own stack. V8 archives and restores it with the rest of
|
|
236
|
+
// the thread's state at every switch.
|
|
237
|
+
SetFiberStackLimit(isolate, reinterpret_cast<uintptr_t>(Coroutine::current().bottom()) + kCppStackReserve);
|
|
238
|
+
HandleScope scope(isolate);
|
|
239
|
+
SetCped(isolate, fiber->initial_cped.Get(isolate));
|
|
240
|
+
fiber->initial_cped.Reset();
|
|
241
|
+
|
|
242
|
+
TryCatch try_catch(isolate);
|
|
243
|
+
Local<Context> context = fiber->context.Get(isolate);
|
|
244
|
+
Context::Scope context_scope(context);
|
|
245
|
+
RecordScopeBase(*fiber);
|
|
246
|
+
// Its result is ignored; src/index.ts passes values through the promise of Fiber.run.
|
|
247
|
+
MaybeLocal<Value> result = fiber->fn.Get(isolate)->Call(context, Undefined(isolate), 0, nullptr);
|
|
248
|
+
(void)result;
|
|
249
|
+
|
|
250
|
+
if (try_catch.HasTerminated()) {
|
|
251
|
+
// process.exit(), worker.terminate(), a vm timeout, or the environment shutting down.
|
|
252
|
+
if (fiber->aborting) {
|
|
253
|
+
isolate->CancelTerminateExecution();
|
|
254
|
+
} else {
|
|
255
|
+
tl_terminate_pending = true;
|
|
256
|
+
}
|
|
257
|
+
} else if (try_catch.HasCaught()) {
|
|
258
|
+
tl_exception.Reset(isolate, try_catch.Exception());
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
entry = fiber->entry;
|
|
262
|
+
coroutine = fiber->coroutine;
|
|
263
|
+
tl_data->fibers.erase(fiber->id);
|
|
264
|
+
delete fiber;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Beyond the pool size the coroutine releases its stack's pages (coroutine.cc). V8's data for
|
|
268
|
+
// this thread stays: the stack keeps its address, so the stack limit V8 stored for the thread
|
|
269
|
+
// id still fits it when the coroutine is reused.
|
|
270
|
+
coroutine->finish(*entry, Coroutine::finishing_releases_stack());
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* start(fn): runs `fn` in a new fiber until it suspends or ends. Throws what `fn` throws before
|
|
275
|
+
* its first suspend.
|
|
276
|
+
*/
|
|
277
|
+
void Start(const FunctionCallbackInfo<Value>& args) {
|
|
278
|
+
Isolate* isolate = args.GetIsolate();
|
|
279
|
+
if (args.Length() != 1 || !args[0]->IsFunction()) {
|
|
280
|
+
THROW(Exception::TypeError, "start() expects a function");
|
|
281
|
+
}
|
|
282
|
+
if (tl_data == nullptr) {
|
|
283
|
+
THROW(Exception::Error, "fibers: this thread's environment has shut down");
|
|
284
|
+
}
|
|
285
|
+
Fiber* fiber = new Fiber();
|
|
286
|
+
fiber->isolate = isolate;
|
|
287
|
+
fiber->coroutine = Coroutine::create_fiber(RunFiber, fiber);
|
|
288
|
+
if (fiber->coroutine == nullptr) {
|
|
289
|
+
delete fiber;
|
|
290
|
+
return ThrowCoded(isolate, "fibers: could not allocate a fiber stack", "ERR_FIBER_STACK_ALLOC",
|
|
291
|
+
Exception::RangeError);
|
|
292
|
+
}
|
|
293
|
+
fiber->id = tl_data->next_id++;
|
|
294
|
+
fiber->fn.Reset(isolate, args[0].As<Function>());
|
|
295
|
+
fiber->context.Reset(isolate, isolate->GetCurrentContext());
|
|
296
|
+
fiber->initial_cped.Reset(isolate, GetCped(isolate));
|
|
297
|
+
tl_data->fibers.emplace(fiber->id, fiber);
|
|
298
|
+
Switch(isolate, fiber);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* resume(id, generation): continues the fiber at the suspend() that passed these numbers to its
|
|
303
|
+
* register function. Throws if the fiber is not suspended there (resumed already, or ended).
|
|
304
|
+
*/
|
|
305
|
+
void Resume(const FunctionCallbackInfo<Value>& args) {
|
|
306
|
+
Isolate* isolate = args.GetIsolate();
|
|
307
|
+
if (args.Length() != 2 || !args[0]->IsNumber() || !args[1]->IsNumber()) {
|
|
308
|
+
THROW(Exception::TypeError, "resume() expects an id and a generation");
|
|
309
|
+
}
|
|
310
|
+
double id = args[0].As<Number>()->Value();
|
|
311
|
+
double generation = args[1].As<Number>()->Value();
|
|
312
|
+
Fiber* fiber = nullptr;
|
|
313
|
+
if (tl_data != nullptr) {
|
|
314
|
+
auto it = tl_data->fibers.find(id);
|
|
315
|
+
if (it != tl_data->fibers.end()) fiber = it->second;
|
|
316
|
+
}
|
|
317
|
+
if (fiber == nullptr || !fiber->suspended || fiber->generation != generation) {
|
|
318
|
+
THROW(Exception::Error, "fibers: resume() called for a fiber that is not waiting for it");
|
|
319
|
+
}
|
|
320
|
+
Switch(isolate, fiber);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
void EndFiber(const FunctionCallbackInfo<Value>& args) {
|
|
324
|
+
args.GetIsolate()->TerminateExecution();
|
|
325
|
+
args.GetReturnValue().Set(true);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* suspend(register): suspends the current fiber after calling register(id, generation). Returns
|
|
330
|
+
* when resume(id, generation) is called. Creates no objects: Fiber.await calls it a lot. Throws
|
|
331
|
+
* (without suspending) outside a fiber, where suspending is refused, or when register throws.
|
|
332
|
+
* Returns true when the fiber is being ended instead (see EndFiber), nothing otherwise.
|
|
333
|
+
*/
|
|
334
|
+
void Suspend(const FunctionCallbackInfo<Value>& args) {
|
|
335
|
+
Isolate* isolate = args.GetIsolate();
|
|
336
|
+
if (tl_data == nullptr || tl_data->current == nullptr) {
|
|
337
|
+
return ThrowCoded(isolate, kOutsideFiberMessage, "ERR_FIBER_AWAIT_OUTSIDE_FIBER");
|
|
338
|
+
}
|
|
339
|
+
Fiber& fiber = *tl_data->current;
|
|
340
|
+
if (fiber.aborting) {
|
|
341
|
+
return EndFiber(args);
|
|
342
|
+
} else if (args.Length() != 1 || !args[0]->IsFunction()) {
|
|
343
|
+
THROW(Exception::TypeError, "suspend() expects a function");
|
|
344
|
+
} else if (!CheckCanSuspend(fiber)) {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
Local<Context> context = isolate->GetCurrentContext();
|
|
349
|
+
fiber.generation += 1;
|
|
350
|
+
Local<Value> argv[2] = {Number::New(isolate, fiber.id), Number::New(isolate, fiber.generation)};
|
|
351
|
+
if (args[0].As<Function>()->Call(context, Undefined(isolate), 2, argv).IsEmpty()) {
|
|
352
|
+
return; // register threw: don't suspend
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Back to whoever started or last resumed this fiber.
|
|
356
|
+
fiber.suspended = true;
|
|
357
|
+
ReleaseAndRun(isolate, *fiber.entry);
|
|
358
|
+
fiber.suspended = false;
|
|
359
|
+
|
|
360
|
+
if (fiber.aborting) {
|
|
361
|
+
return EndFiber(args);
|
|
362
|
+
}
|
|
363
|
+
RecordScopeBase(fiber);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* checkSuspend(): throws what suspend() would throw where suspending is refused, without
|
|
368
|
+
* suspending. Outside a fiber it does nothing (src/index.ts checks that). Fiber.wrap calls it
|
|
369
|
+
* before the wrapped function starts its work. Returns true when the fiber is being ended (see
|
|
370
|
+
* EndFiber), nothing otherwise.
|
|
371
|
+
*/
|
|
372
|
+
void CheckSuspend(const FunctionCallbackInfo<Value>& args) {
|
|
373
|
+
if (tl_data == nullptr || tl_data->current == nullptr) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
Fiber& fiber = *tl_data->current;
|
|
377
|
+
if (fiber.aborting) {
|
|
378
|
+
return EndFiber(args);
|
|
379
|
+
}
|
|
380
|
+
CheckCanSuspend(fiber);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
void InFiber(const FunctionCallbackInfo<Value>& args) {
|
|
384
|
+
args.GetReturnValue().Set(tl_data != nullptr && tl_data->current != nullptr);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Environment teardown (process exit, worker end): end the suspended fibers with
|
|
389
|
+
* TerminateExecution (their finally blocks don't run) so that V8 releases their threads, then
|
|
390
|
+
* free the coroutines.
|
|
391
|
+
*/
|
|
392
|
+
void Teardown(void* arg) {
|
|
393
|
+
ThreadData* data = static_cast<ThreadData*>(arg);
|
|
394
|
+
Isolate* isolate = data->isolate;
|
|
395
|
+
if (!data->fibers.empty()) {
|
|
396
|
+
Locker locker(isolate);
|
|
397
|
+
Isolate::Scope isolate_scope(isolate);
|
|
398
|
+
HandleScope scope(isolate);
|
|
399
|
+
std::vector<Fiber*> parked;
|
|
400
|
+
for (auto& entry : data->fibers) {
|
|
401
|
+
if (entry.second->suspended) parked.push_back(entry.second);
|
|
402
|
+
}
|
|
403
|
+
for (Fiber* fiber : parked) {
|
|
404
|
+
fiber->aborting = true;
|
|
405
|
+
Switch(isolate, fiber);
|
|
406
|
+
}
|
|
407
|
+
tl_exception.Reset();
|
|
408
|
+
}
|
|
409
|
+
Coroutine::shutdown();
|
|
410
|
+
if (data->cped_guard != nullptr) {
|
|
411
|
+
isolate->RemoveGCPrologueCallback(CpedGcGuard::Prologue, data->cped_guard);
|
|
412
|
+
isolate->RemoveGCEpilogueCallback(CpedGcGuard::Epilogue, data->cped_guard);
|
|
413
|
+
delete data->cped_guard;
|
|
414
|
+
}
|
|
415
|
+
if (tl_data == data) {
|
|
416
|
+
tl_data = nullptr;
|
|
417
|
+
}
|
|
418
|
+
delete data;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Sets up this JS thread.
|
|
423
|
+
*/
|
|
424
|
+
void Init(Isolate* isolate) {
|
|
425
|
+
if (tl_data != nullptr) {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
ThreadData* data = new ThreadData();
|
|
429
|
+
data->isolate = isolate;
|
|
430
|
+
|
|
431
|
+
// V8's wasm code GC aborts with archived threads ("archived threads in combination with wasm
|
|
432
|
+
// not supported"), and every suspended fiber is one: fetch() (undici runs its parser in wasm)
|
|
433
|
+
// with suspended fibers aborted. Wasm code memory is then not reclaimed.
|
|
434
|
+
const char* wasm_gc = getenv("FIBERS_WASM_CODE_GC");
|
|
435
|
+
if (wasm_gc == nullptr || strcmp(wasm_gc, "1") != 0) {
|
|
436
|
+
V8::SetFlagsFromString("--no-wasm-code-gc");
|
|
437
|
+
}
|
|
438
|
+
data->cped_guard = new CpedGcGuard();
|
|
439
|
+
isolate->AddGCPrologueCallback(CpedGcGuard::Prologue, data->cped_guard);
|
|
440
|
+
isolate->AddGCEpilogueCallback(CpedGcGuard::Epilogue, data->cped_guard);
|
|
441
|
+
|
|
442
|
+
node::AddEnvironmentCleanupHook(isolate, Teardown, data);
|
|
443
|
+
tl_data = data;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// --- Configuration and diagnostics -------------------------------------------------------------
|
|
447
|
+
|
|
448
|
+
constexpr double kMinStackSize = 2.0 * kCppStackReserve;
|
|
449
|
+
constexpr double kMaxStackSize = 1024.0 * 1024 * 1024;
|
|
450
|
+
|
|
451
|
+
void SetStackSize(const FunctionCallbackInfo<Value>& args) {
|
|
452
|
+
Isolate* isolate = args.GetIsolate();
|
|
453
|
+
double bytes = args[0]->NumberValue(isolate->GetCurrentContext()).FromMaybe(0);
|
|
454
|
+
if (!(bytes >= kMinStackSize && bytes <= kMaxStackSize)) {
|
|
455
|
+
THROW(Exception::RangeError, "Fiber.setStackSize: must be between 2 MiB and 1 GiB");
|
|
456
|
+
}
|
|
457
|
+
if (!Coroutine::set_stack_size(static_cast<unsigned int>(bytes / sizeof(void*)))) {
|
|
458
|
+
return ThrowCoded(isolate, "Fiber.setStackSize: call it before the first Fiber.run",
|
|
459
|
+
"ERR_FIBER_STACK_SIZE_LOCKED");
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
void SetPoolSize(const FunctionCallbackInfo<Value>& args) {
|
|
464
|
+
Isolate* isolate = args.GetIsolate();
|
|
465
|
+
double size = args[0]->NumberValue(isolate->GetCurrentContext()).FromMaybe(-1);
|
|
466
|
+
if (!(size >= 0)) {
|
|
467
|
+
THROW(Exception::RangeError, "Fiber.setPoolSize: expects a number >= 0");
|
|
468
|
+
}
|
|
469
|
+
Coroutine::pool_size = size > 1e9 ? 1000000000 : static_cast<size_t>(size);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
void Stats(const FunctionCallbackInfo<Value>& args) {
|
|
473
|
+
Isolate* isolate = args.GetIsolate();
|
|
474
|
+
Local<Context> context = isolate->GetCurrentContext();
|
|
475
|
+
Local<Object> out = Object::New(isolate);
|
|
476
|
+
auto set = [&](const char* key, double value) {
|
|
477
|
+
out->Set(context, NewLatin1String(isolate, key), Number::New(isolate, value)).Check();
|
|
478
|
+
};
|
|
479
|
+
set("live", tl_data ? static_cast<double>(tl_data->fibers.size()) : 0);
|
|
480
|
+
set("fibersCreated", static_cast<double>(Coroutine::coroutines_created()));
|
|
481
|
+
set("pooled", static_cast<double>(Coroutine::pooled()));
|
|
482
|
+
set("released", static_cast<double>(Coroutine::released()));
|
|
483
|
+
set("poolSize", static_cast<double>(Coroutine::pool_size));
|
|
484
|
+
set("stackSize", static_cast<double>(Coroutine::stack_size_bytes()));
|
|
485
|
+
set("switches", tl_switches);
|
|
486
|
+
args.GetReturnValue().Set(out);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
void TlsLayout(const FunctionCallbackInfo<Value>& args) {
|
|
490
|
+
const std::string& report = fibers::TlsReport();
|
|
491
|
+
args.GetReturnValue().Set(String::NewFromUtf8(args.GetIsolate(), report.data(),
|
|
492
|
+
NewStringType::kNormal, static_cast<int>(report.size())).ToLocalChecked());
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
} // namespace
|
|
496
|
+
|
|
497
|
+
NODE_MODULE_INIT(/* exports, module, context */) {
|
|
498
|
+
Isolate* isolate = Isolate::GetCurrent();
|
|
499
|
+
if (!Locker::IsLocked(isolate)) {
|
|
500
|
+
return ThrowCoded(isolate, "fibers: the isolate is not locked with v8::Locker (unexpected embedder)",
|
|
501
|
+
"ERR_FIBER_UNSUPPORTED_NODE");
|
|
502
|
+
}
|
|
503
|
+
// Unknown thread-locals, a stripped binary, an unexpected TLS layout, a failed self-check: all
|
|
504
|
+
// mean this node binary can't be used, so they share one code; the message says which.
|
|
505
|
+
std::string error = Coroutine::init(isolate);
|
|
506
|
+
if (!error.empty()) {
|
|
507
|
+
error = "fibers: " + error;
|
|
508
|
+
return ThrowCoded(isolate, String::NewFromUtf8(isolate, error.c_str()).ToLocalChecked(),
|
|
509
|
+
"ERR_FIBER_UNSUPPORTED_NODE");
|
|
510
|
+
}
|
|
511
|
+
Init(isolate);
|
|
512
|
+
auto set = [&](const char* name, FunctionCallback fn) {
|
|
513
|
+
exports->Set(context, NewLatin1String(isolate, name), Function::New(context, fn).ToLocalChecked()).Check();
|
|
514
|
+
};
|
|
515
|
+
set("start", Start);
|
|
516
|
+
set("suspend", Suspend);
|
|
517
|
+
set("resume", Resume);
|
|
518
|
+
set("checkSuspend", CheckSuspend);
|
|
519
|
+
set("inFiber", InFiber);
|
|
520
|
+
set("setStackSize", SetStackSize);
|
|
521
|
+
set("setPoolSize", SetPoolSize);
|
|
522
|
+
set("stats", Stats);
|
|
523
|
+
set("tlsLayout", TlsLayout);
|
|
524
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Copyright (c) 2000-2009 Marc Alexander Lehmann <schmorp@schmorp.de>
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without modifica-
|
|
4
|
+
tion, are permitted provided that the following conditions are met:
|
|
5
|
+
|
|
6
|
+
1. Redistributions of source code must retain the above copyright notice,
|
|
7
|
+
this list of conditions and the following disclaimer.
|
|
8
|
+
|
|
9
|
+
2. Redistributions in binary form must reproduce the above copyright
|
|
10
|
+
notice, this list of conditions and the following disclaimer in the
|
|
11
|
+
documentation and/or other materials provided with the distribution.
|
|
12
|
+
|
|
13
|
+
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
|
|
14
|
+
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
|
|
15
|
+
CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
|
|
16
|
+
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
|
|
17
|
+
CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
|
18
|
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
|
|
19
|
+
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
|
20
|
+
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
|
|
21
|
+
ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
|
|
22
|
+
OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
23
|
+
|
|
24
|
+
Alternatively, the following files carry an additional notice that
|
|
25
|
+
explicitly allows relicensing under the GPLv2: coro.c, coro.h.
|
|
26
|
+
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
Configuration, documentation etc. is provided in the coro.h file. Please
|
|
2
|
+
note that the file conftest.c in this distribution is under the GPL. It is
|
|
3
|
+
not needed for proper operation of this library though, for that, coro.h
|
|
4
|
+
and coro.c suffice.
|
|
5
|
+
|
|
6
|
+
Marc Lehmann <schmorp@schmorp.de>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
libcoro as vendored by laverdet/node-fibers at commit 4c9e83ee329a24e635845382940e1c3066714082 (src/libcoro). Changed in coro.c coro_stack_alloc, marked "fibers:": MAP_STACK | MAP_NORESERVE on Linux, and a failed guard-page mprotect fails the allocation.
|