wasmer-napi 0.702.0

NAPI library for Wasmer WebAssembly runtime
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
#include "edge_v8_platform.h"

#include <atomic>
#include <condition_variable>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <memory>
#include <mutex>
#include <utility>
#include <vector>

#include <libplatform/libplatform.h>
#include <v8.h>

namespace {

struct WorkerWarmupState {
  std::mutex mutex;
  std::condition_variable cv;
  size_t pending = 0;
};

class WorkerWarmupTask final : public v8::Task {
 public:
  explicit WorkerWarmupTask(WorkerWarmupState* state) : state_(state) {}

  void Run() override {
    if (state_ == nullptr) return;
    std::lock_guard<std::mutex> lock(state_->mutex);
    if (state_->pending > 0) {
      state_->pending -= 1;
    }
    if (state_->pending == 0) {
      state_->cv.notify_all();
    }
  }

 private:
  WorkerWarmupState* state_ = nullptr;
};

void WarmUpFallbackWorkerThreads(v8::Platform* fallback) {
  if (fallback == nullptr) return;

  const int worker_threads = fallback->NumberOfWorkerThreads();
  if (worker_threads <= 0) return;

  WorkerWarmupState state;
  {
    std::lock_guard<std::mutex> lock(state.mutex);
    state.pending = static_cast<size_t>(worker_threads) + 1;
  }

  for (int i = 0; i < worker_threads; ++i) {
    fallback->PostTaskOnWorkerThread(
        v8::TaskPriority::kUserVisible,
        std::make_unique<WorkerWarmupTask>(&state));
  }
  fallback->PostDelayedTaskOnWorkerThread(
      v8::TaskPriority::kUserVisible,
      std::make_unique<WorkerWarmupTask>(&state),
      0);

  std::unique_lock<std::mutex> lock(state.mutex);
  while (state.pending != 0) {
    state.cv.wait(lock);
  }
}

struct ForegroundTaskRecord {
  std::shared_ptr<EdgeV8Platform::IsolateState> isolate_state;
  std::unique_ptr<v8::Task> task;
};

void RunForegroundTaskRecord(napi_env /*env*/, void* data);
void CleanupForegroundTaskRecord(napi_env /*env*/, void* data);

}  // namespace

struct EdgeV8Platform::FinishedCallback {
  void (*callback)(void*) = nullptr;
  void* data = nullptr;
};

struct EdgeV8Platform::IsolateState {
  IsolateState(EdgeV8Platform* platform_in,
               v8::Isolate* isolate_in,
               std::shared_ptr<ForegroundTaskRunner> runner_in)
      : platform(platform_in),
        isolate(isolate_in),
        runner(std::move(runner_in)) {}

  EdgeV8Platform* platform = nullptr;
  v8::Isolate* isolate = nullptr;
  std::shared_ptr<ForegroundTaskRunner> runner;
  std::mutex mutex;
  size_t pending_foreground_tasks = 0;
  bool shutdown_started = false;
  bool finished = false;
  std::vector<FinishedCallback> finished_callbacks;
};

namespace {

class CountedForegroundTask final : public v8::Task {
 public:
  CountedForegroundTask(std::shared_ptr<EdgeV8Platform::IsolateState> isolate_state,
                        std::unique_ptr<v8::Task> task)
      : isolate_state_(std::move(isolate_state)),
        task_(std::move(task)) {}

  ~CountedForegroundTask() override { Finish(); }

  void Run() override {
    if (task_) {
      task_->Run();
      task_.reset();
    }
    Finish();
  }

 private:
  void Finish() {
    if (finished_.exchange(true, std::memory_order_acq_rel)) return;
    std::shared_ptr<EdgeV8Platform::IsolateState> isolate_state =
        std::move(isolate_state_);
    task_.reset();
    if (isolate_state && isolate_state->platform != nullptr) {
      isolate_state->platform->CompletePendingForegroundTask(isolate_state);
    }
  }

  std::shared_ptr<EdgeV8Platform::IsolateState> isolate_state_;
  std::unique_ptr<v8::Task> task_;
  std::atomic<bool> finished_ {false};
};

void RunForegroundTaskRecord(napi_env /*env*/, void* data) {
  auto* record = static_cast<ForegroundTaskRecord*>(data);
  if (record != nullptr && record->task) {
    record->task->Run();
  }
}

void CleanupForegroundTaskRecord(napi_env /*env*/, void* data) {
  auto* record = static_cast<ForegroundTaskRecord*>(data);
  if (record == nullptr) {
    delete record;
    return;
  }
  record->task.reset();
  std::shared_ptr<EdgeV8Platform::IsolateState> isolate_state =
      std::move(record->isolate_state);
  if (isolate_state && isolate_state->platform != nullptr) {
    isolate_state->platform->CompletePendingForegroundTask(isolate_state);
  }
  delete record;
}

}  // namespace

class EdgeV8Platform::ForegroundTaskRunner final : public v8::TaskRunner {
 public:
  ForegroundTaskRunner(std::shared_ptr<IsolateState> isolate_state,
                       v8::Isolate* isolate,
                       v8::Platform* fallback)
      : isolate_state_(std::move(isolate_state)),
        isolate_(isolate),
        fallback_(fallback) {}

  bool IdleTasksEnabled() override { return false; }
  bool NonNestableTasksEnabled() const override { return true; }
  bool NonNestableDelayedTasksEnabled() const override { return true; }

 protected:
  void PostTaskImpl(std::unique_ptr<v8::Task> task,
                    const v8::SourceLocation& location) override {
    PostTaskCommon(std::move(task), 0, location);
  }

  void PostNonNestableTaskImpl(std::unique_ptr<v8::Task> task,
                               const v8::SourceLocation& location) override {
    PostTaskCommon(std::move(task), 0, location);
  }

  void PostDelayedTaskImpl(std::unique_ptr<v8::Task> task,
                           double delay_in_seconds,
                           const v8::SourceLocation& location) override {
    uint64_t delay_ms = 0;
    if (delay_in_seconds > 0) {
      delay_ms = static_cast<uint64_t>(std::llround(delay_in_seconds * 1000.0));
    }
    PostTaskCommon(std::move(task), delay_ms, location);
  }

  void PostNonNestableDelayedTaskImpl(
      std::unique_ptr<v8::Task> task,
      double delay_in_seconds,
      const v8::SourceLocation& location) override {
    PostDelayedTaskImpl(std::move(task), delay_in_seconds, location);
  }

  void PostIdleTaskImpl(std::unique_ptr<v8::IdleTask> /*task*/,
                        const v8::SourceLocation& /*location*/) override {}

 private:
  void PostTaskCommon(std::unique_ptr<v8::Task> task,
                      uint64_t delay_ms,
                      const v8::SourceLocation& location) {
    if (!task) return;
    if (shutting_down_.load(std::memory_order_acquire)) {
      return;
    }
    std::shared_ptr<IsolateState> isolate_state = isolate_state_.lock();

    unofficial_napi_enqueue_foreground_task_callback enqueue =
        target_enqueue_.load(std::memory_order_acquire);
    void* target = target_data_.load(std::memory_order_acquire);
    if (enqueue != nullptr && target != nullptr) {
      ForegroundTaskRecord* record = new (std::nothrow) ForegroundTaskRecord();
      if (record != nullptr) {
        record->isolate_state.reset();
        record->task = std::move(task);
        if (enqueue(target,
                    RunForegroundTaskRecord,
                    record,
                    CleanupForegroundTaskRecord,
                    delay_ms) == napi_ok) {
          if (isolate_state != nullptr &&
              isolate_state->platform != nullptr) {
            isolate_state->platform->AddPendingForegroundTask(isolate_state);
            record->isolate_state = isolate_state;
          }
          return;
        }
        task = std::move(record->task);
        record->isolate_state.reset();
        delete record;
      }
    }

    auto runner = fallback_ != nullptr ? fallback_->GetForegroundTaskRunner(isolate_) : nullptr;
    if (runner) {
      used_fallback_runner_.store(true, std::memory_order_release);
      std::unique_ptr<v8::Task> counted_task = std::move(task);
      if (isolate_state != nullptr && isolate_state->platform != nullptr) {
        isolate_state->platform->AddPendingForegroundTask(isolate_state);
        counted_task =
            std::make_unique<CountedForegroundTask>(isolate_state, std::move(counted_task));
      }
      if (delay_ms == 0) {
        runner->PostTask(std::move(counted_task), location);
      } else {
        runner->PostDelayedTask(std::move(counted_task), delay_ms / 1000.0, location);
      }
    }
  }

  std::weak_ptr<IsolateState> isolate_state_;
  v8::Isolate* isolate_ = nullptr;
  v8::Platform* fallback_ = nullptr;
  std::atomic<napi_env> target_env_ {nullptr};
  std::atomic<unofficial_napi_enqueue_foreground_task_callback> target_enqueue_ {nullptr};
  std::atomic<void*> target_data_ {nullptr};
  std::atomic<bool> shutting_down_ {false};
  std::atomic<bool> used_fallback_runner_ {false};

 public:
  ~ForegroundTaskRunner() override = default;

  void BindTarget(napi_env env,
                  unofficial_napi_enqueue_foreground_task_callback callback,
                  void* target) {
    target_data_.store(target, std::memory_order_release);
    target_enqueue_.store(callback, std::memory_order_release);
    target_env_.store(env, std::memory_order_release);
  }

  void ClearTarget(napi_env env) {
    if (target_env_.load(std::memory_order_acquire) != env) return;
    target_env_.store(nullptr, std::memory_order_release);
    target_enqueue_.store(nullptr, std::memory_order_release);
    target_data_.store(nullptr, std::memory_order_release);
  }

  void NotifyIsolateShutdown() {
    shutting_down_.store(true, std::memory_order_release);
    target_env_.store(nullptr, std::memory_order_release);
    target_enqueue_.store(nullptr, std::memory_order_release);
    target_data_.store(nullptr, std::memory_order_release);
  }

  bool used_fallback_runner() const {
    return used_fallback_runner_.load(std::memory_order_acquire);
  }
};

std::unique_ptr<EdgeV8Platform> EdgeV8Platform::Create() {
  std::unique_ptr<v8::Platform> fallback = v8::platform::NewDefaultPlatform();
  if (!fallback) return nullptr;
  WarmUpFallbackWorkerThreads(fallback.get());
  return std::unique_ptr<EdgeV8Platform>(new EdgeV8Platform(std::move(fallback)));
}

EdgeV8Platform::EdgeV8Platform(std::unique_ptr<v8::Platform> fallback)
    : fallback_(std::move(fallback)) {}

EdgeV8Platform::~EdgeV8Platform() = default;

std::shared_ptr<EdgeV8Platform::IsolateState> EdgeV8Platform::GetState(v8::Isolate* isolate) {
  if (isolate == nullptr) return nullptr;
  std::lock_guard<std::mutex> lock(mutex_);
  auto it = isolates_.find(isolate);
  return it != isolates_.end() ? it->second : nullptr;
}

std::shared_ptr<EdgeV8Platform::IsolateState> EdgeV8Platform::EnsureState(v8::Isolate* isolate) {
  if (isolate == nullptr) return nullptr;
  std::lock_guard<std::mutex> lock(mutex_);
  auto it = isolates_.find(isolate);
  if (it != isolates_.end()) return it->second;
  if (fallback_ != nullptr) {
    // libplatform's NotifyIsolateShutdown() assumes a foreground runner entry
    // exists for every isolate it tears down.
    (void)fallback_->GetForegroundTaskRunner(isolate);
  }
  auto state = std::make_shared<IsolateState>(this, isolate, nullptr);
  state->runner = std::make_shared<ForegroundTaskRunner>(state, isolate, fallback_.get());
  isolates_.emplace(isolate, state);
  return state;
}

std::shared_ptr<EdgeV8Platform::ForegroundTaskRunner> EdgeV8Platform::EnsureRunner(v8::Isolate* isolate) {
  std::shared_ptr<IsolateState> state = EnsureState(isolate);
  return state != nullptr ? state->runner : nullptr;
}

bool EdgeV8Platform::RegisterIsolate(v8::Isolate* isolate) { return EnsureRunner(isolate) != nullptr; }

void EdgeV8Platform::AddPendingForegroundTask(const std::shared_ptr<IsolateState>& state) {
  if (!state) return;
  std::lock_guard<std::mutex> lock(state->mutex);
  if (state->finished) return;
  state->pending_foreground_tasks += 1;
}

void EdgeV8Platform::CompletePendingForegroundTask(const std::shared_ptr<IsolateState>& state) {
  if (!state) return;
  {
    std::lock_guard<std::mutex> lock(state->mutex);
    if (state->pending_foreground_tasks > 0) {
      state->pending_foreground_tasks -= 1;
    }
  }
  MaybeFinishIsolate(state, false);
}

void EdgeV8Platform::BeginShutdown(const std::shared_ptr<IsolateState>& state) {
  if (!state) return;
  std::lock_guard<std::mutex> lock(state->mutex);
  state->shutdown_started = true;
}

void EdgeV8Platform::MaybeFinishIsolate(const std::shared_ptr<IsolateState>& state,
                                        bool begin_shutdown) {
  if (!state) return;

  std::vector<FinishedCallback> callbacks;
  {
    std::lock_guard<std::mutex> lock(state->mutex);
    if (begin_shutdown) {
      state->shutdown_started = true;
    }
    if (state->finished ||
        !state->shutdown_started ||
        state->pending_foreground_tasks != 0) {
      return;
    }
    state->finished = true;
    callbacks.swap(state->finished_callbacks);
  }

  {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = isolates_.find(state->isolate);
    if (it != isolates_.end() && it->second.get() == state.get()) {
      isolates_.erase(it);
    }
  }

  for (const FinishedCallback& callback : callbacks) {
    if (callback.callback != nullptr) {
      callback.callback(callback.data);
    }
  }
}

void EdgeV8Platform::AddIsolateFinishedCallback(v8::Isolate* isolate,
                                                void (*callback)(void*),
                                                void* data) {
  if (callback == nullptr) return;
  std::shared_ptr<IsolateState> state;
  {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = isolates_.find(isolate);
    if (it != isolates_.end()) {
      state = it->second;
    }
  }
  if (!state) {
    callback(data);
    return;
  }

  bool run_now = false;
  {
    std::lock_guard<std::mutex> lock(state->mutex);
    if (state->finished) {
      run_now = true;
    } else {
      state->finished_callbacks.push_back(FinishedCallback{callback, data});
      run_now = state->shutdown_started && state->pending_foreground_tasks == 0;
    }
  }

  if (run_now) {
    MaybeFinishIsolate(state, false);
  }
}

void EdgeV8Platform::NotifyIsolateShutdown(v8::Isolate* isolate) {
  if (isolate == nullptr) return;

  std::shared_ptr<IsolateState> state = GetState(isolate);
  std::shared_ptr<ForegroundTaskRunner> runner = state != nullptr ? state->runner : nullptr;
  if (runner) {
    runner->NotifyIsolateShutdown();
  }
  // The fallback platform owns all background V8 work for these isolates,
  // even when foreground tasks stayed on the Edge-specific runner.
  if (fallback_ != nullptr) {
    v8::platform::NotifyIsolateShutdown(fallback_.get(), isolate);
  }
  BeginShutdown(state);
  MaybeFinishIsolate(state, false);
}

void EdgeV8Platform::DisposeIsolate(v8::Isolate* isolate) {
  if (isolate == nullptr) return;

  std::shared_ptr<IsolateState> state = GetState(isolate);
  NotifyIsolateShutdown(isolate);

  // Keep the isolate registered while it is being disposed because V8 may
  // still post tasks during teardown, then drop the map entry before the
  // address can be reused for a new isolate.
  isolate->Dispose();
  UnregisterIsolate(isolate);
  MaybeFinishIsolate(state, false);
}

void EdgeV8Platform::UnregisterIsolate(v8::Isolate* isolate) {
  if (isolate == nullptr) return;
  std::lock_guard<std::mutex> lock(mutex_);
  isolates_.erase(isolate);
}

bool EdgeV8Platform::BindForegroundTaskTarget(
    v8::Isolate* isolate,
    napi_env env,
    unofficial_napi_enqueue_foreground_task_callback callback,
    void* target) {
  std::shared_ptr<ForegroundTaskRunner> runner = EnsureRunner(isolate);
  if (!runner) return false;
  runner->BindTarget(env, callback, target);
  return true;
}

void EdgeV8Platform::ClearForegroundTaskTarget(v8::Isolate* isolate, napi_env env) {
  std::shared_ptr<IsolateState> state;
  {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = isolates_.find(isolate);
    if (it == isolates_.end()) return;
    state = it->second;
  }
  if (!state || !state->runner) return;
  state->runner->ClearTarget(env);
}

int EdgeV8Platform::NumberOfWorkerThreads() {
  return fallback_ != nullptr ? fallback_->NumberOfWorkerThreads() : 0;
}

std::shared_ptr<v8::TaskRunner> EdgeV8Platform::GetForegroundTaskRunner(
    v8::Isolate* isolate,
    v8::TaskPriority /*priority*/) {
  return EnsureRunner(isolate);
}

bool EdgeV8Platform::IdleTasksEnabled(v8::Isolate* isolate) {
  (void)isolate;
  return false;
}

double EdgeV8Platform::MonotonicallyIncreasingTime() {
  if (fallback_ != nullptr) return fallback_->MonotonicallyIncreasingTime();
  using clock = std::chrono::steady_clock;
  const auto now = clock::now().time_since_epoch();
  return std::chrono::duration<double>(now).count();
}

double EdgeV8Platform::CurrentClockTimeMillis() {
  return fallback_ != nullptr ? fallback_->CurrentClockTimeMillis()
                              : v8::Platform::SystemClockTimeMillis();
}

v8::TracingController* EdgeV8Platform::GetTracingController() {
  return fallback_ != nullptr ? fallback_->GetTracingController() : nullptr;
}

v8::PageAllocator* EdgeV8Platform::GetPageAllocator() {
  return fallback_ != nullptr ? fallback_->GetPageAllocator() : nullptr;
}

v8::ThreadIsolatedAllocator* EdgeV8Platform::GetThreadIsolatedAllocator() {
  return fallback_ != nullptr ? fallback_->GetThreadIsolatedAllocator() : nullptr;
}

void EdgeV8Platform::OnCriticalMemoryPressure() {
  if (fallback_ != nullptr) fallback_->OnCriticalMemoryPressure();
}

void EdgeV8Platform::DumpWithoutCrashing() {
  if (fallback_ != nullptr) fallback_->DumpWithoutCrashing();
}

v8::HighAllocationThroughputObserver* EdgeV8Platform::GetHighAllocationThroughputObserver() {
  if (fallback_ != nullptr) return fallback_->GetHighAllocationThroughputObserver();
  static v8::HighAllocationThroughputObserver observer;
  return &observer;
}

v8::Platform::StackTracePrinter EdgeV8Platform::GetStackTracePrinter() {
  return fallback_ != nullptr ? fallback_->GetStackTracePrinter() : nullptr;
}

std::unique_ptr<v8::ScopedBlockingCall> EdgeV8Platform::CreateBlockingScope(
    v8::BlockingType blocking_type) {
  return fallback_ != nullptr ? fallback_->CreateBlockingScope(blocking_type) : nullptr;
}

std::unique_ptr<v8::JobHandle> EdgeV8Platform::CreateJobImpl(
    v8::TaskPriority priority,
    std::unique_ptr<v8::JobTask> job_task,
    const v8::SourceLocation& location) {
  (void)location;
  return v8::platform::NewDefaultJobHandle(this, priority, std::move(job_task),
                                           static_cast<size_t>(std::max(1, NumberOfWorkerThreads())));
}

void EdgeV8Platform::PostTaskOnWorkerThreadImpl(v8::TaskPriority priority,
                                               std::unique_ptr<v8::Task> task,
                                               const v8::SourceLocation& location) {
  if (fallback_ != nullptr) {
    fallback_->PostTaskOnWorkerThread(priority, std::move(task), location);
  }
}

void EdgeV8Platform::PostDelayedTaskOnWorkerThreadImpl(
    v8::TaskPriority priority,
    std::unique_ptr<v8::Task> task,
    double delay_in_seconds,
    const v8::SourceLocation& location) {
  if (fallback_ != nullptr) {
    fallback_->PostDelayedTaskOnWorkerThread(priority, std::move(task), delay_in_seconds, location);
  }
}