Repository navigation
Expand file tree
/
Copy pathGraphLoad.cpp
More file actions
1471 lines (1383 loc) · 55.2 KB
/
Copy pathGraphLoad.cpp
File metadata and controls
1471 lines (1383 loc) · 55.2 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
#include "ns/loader/GraphLoad.h"
#include <v8-external-memory-accounter.h>
#include <algorithm>
#include <chrono>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <unordered_set>
#include <utility>
#include "loader/CompilePool.h"
#include "loader/GraphLoadInternal.h"
#include "loader/LoaderStateInternal.h"
#include "ns/AppFiles.h"
#include "ns/Deadline.h"
#include "ns/JsError.h"
#include "ns/Loop.h"
#include "ns/Platform.h"
#include "ns/RuntimeAccess.h"
#include "ns/Trace.h"
#include "ns/V8Flags.h"
#include "ns/V8Helpers.h"
#include "ns/loader/CodeCacheQueue.h"
#include "ns/loader/FileCompile.h"
#include "ns/loader/LoaderState.h"
#include "ns/loader/ModuleIdentity.h"
#include "ns/loader/ModuleRegistry.h"
// Threads and handoffs. Every arrow names who owns what across it and how
// loader::Quiesce cancels it.
//
// 1. Transport -> isolate: an HTTP fetch completion. The transport thread
// holds the walk, the ticket and the token; none owns V8 state. It posts
// through the token, which refuses once closed and drops a task it ran
// after closing.
// 2. Transport -> pool: a large HTTP body. Enter() before the pool post,
// Leave() after the job released everything; the ticket's raw pointers
// into GraphLoaderState are used only in between. Quiesce discards queued
// jobs and waits for running ones before destroying the V8 tasks.
// 3. Pool -> isolate: the stream or file completion, posted through the token
// from inside the section, so the loop cannot have been released yet.
// 4. Isolate -> pool: a file job, under the same section rule as 2.
// 5. Parked walks: isolate -> isolate through the token, when the outermost
// SyncModuleLoadScope closes.
//
// Quiesce first stops the walks on the isolate's thread (contexts reset, jobs
// superseded, parked walks dropped), and only then closes the token. So a
// task the token refuses, wherever it is destroyed, never holds the last
// reference to anything with a V8 handle.
namespace nativescript::common::loader {
namespace {
using platform::TraceCategory;
using Clock = std::chrono::steady_clock;
// Smaller bodies compile on the isolate's thread: for them the hop to the
// pool costs more than the compile it moves.
constexpr size_t kOffThreadCompileThresholdBytes = 32 * 1024;
// A file with a fresh code cache moves off the isolate's thread only from
// this size: deserializing costs about 1 to 2.5 ms per MB there, so below it
// the hop costs the walk more latency than the isolate's thread saves.
constexpr size_t kOffThreadCacheConsumeThresholdBytes = 256 * 1024;
constexpr double kDefaultPumpedTimeoutSeconds = 60.0;
// How long Quiesce waits for background compiles once the loop that would
// serve their GC requests has stopped.
constexpr std::chrono::seconds kUnservedDrainLimit{10};
constexpr std::chrono::milliseconds kUnservedCollectionInterval{100};
std::atomic<int> g_walksRunning{0};
struct Counters {
std::atomic<uint64_t> finalized{0};
std::atomic<uint64_t> discarded{0};
std::atomic<uint64_t> fellBack{0};
std::atomic<int64_t> running{0};
std::atomic<uint64_t> teardownWaits{0};
};
Counters g_counters;
} // namespace
// Thread discipline: everything but the constant fields is read and written
// on the isolate's thread only. The walk owns no V8 state (its context is in
// GraphLoaderState::walkContexts), so its last reference may drop anywhere.
struct AsyncGraphLoad {
v8::Isolate* isolate = nullptr;
uint64_t seq = 0;
std::string rootKey;
std::unordered_set<std::string> visited;
int pendingFetches = 0;
// Part of pendingFetches.
int pendingHttpFetches = 0;
bool failed = false;
bool completed = false;
// Set by Quiesce.
bool killed = false;
std::string failureMessage;
size_t fetchedCount = 0;
size_t compiledCount = 0;
Clock::time_point start;
http::ModuleFetchDeadline fetchDeadline;
GraphLoadCompletion onComplete;
// Counted in g_walksRunning, from its start until it completes or is
// killed (or, for a runtime that never quiesced, is freed).
bool running = false;
~AsyncGraphLoad() {
if (running) {
g_walksRunning.fetch_sub(1, std::memory_order_acq_rel);
}
}
};
namespace {
bool IsAscii(const std::string& bytes) {
const auto* p = reinterpret_cast<const unsigned char*>(bytes.data());
const size_t n = bytes.size();
size_t i = 0;
for (; i + sizeof(uint64_t) <= n; i += sizeof(uint64_t)) {
uint64_t word;
std::memcpy(&word, p + i, sizeof(word));
if ((word & 0x8080808080808080ull) != 0) {
return false;
}
}
for (; i < n; i++) {
if ((p[i] & 0x80) != 0) {
return false;
}
}
return true;
}
// A V8 stream skips a leading UTF-8 BOM that the full source string keeps,
// which would shift every position the finalized module reports.
bool StartsWithBom(const std::string& body) {
return body.size() >= 3 && body.compare(0, 3, "\xEF\xBB\xBF") == 0;
}
bool EndsWith(const std::string& s, std::string_view suffix) {
return s.size() >= suffix.size() &&
s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
}
double MsSince(Clock::time_point start) {
return std::chrono::duration<double, std::milli>(Clock::now() - start)
.count();
}
// "message (line L:C)" for a caught exception, or empty.
std::string DescribeCaughtError(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const v8::TryCatch& tc) {
if (!tc.HasCaught()) {
return std::string();
}
v8::Local<v8::Message> message = tc.Message();
if (message.IsEmpty()) {
return std::string();
}
std::string described = ToString(isolate, message->Get());
const int line = message->GetLineNumber(context).FromMaybe(0);
if (line > 0) {
described += " (line " + std::to_string(line) + ":" +
std::to_string(message->GetStartColumn()) + ")";
}
return described;
}
// A pure-ASCII module body the isolate keeps as an external one-byte string:
// Latin-1 matches the UTF-8 bytes a stream parsed only below 0x80. The bytes
// live outside the V8 heap, so they are charged as external memory for as
// long as the string holds them.
class OwnedAsciiSource : public v8::String::ExternalOneByteStringResource {
public:
explicit OwnedAsciiSource(std::string body) : body_(std::move(body)) {}
const char* data() const override { return body_.data(); }
size_t length() const override { return body_.size(); }
// Isolate thread, with the string held by a handle: the increase can run a
// collection before it returns.
void Charge(v8::Isolate* isolate) {
accounter_.Increase(isolate, body_.size());
charged_ = true;
}
// V8 calls it right before Dispose(), possibly on a GC thread or during
// heap teardown; the decrease is a single atomic update.
void Unaccount(v8::Isolate* isolate) override {
if (charged_) {
accounter_.Decrease(isolate, body_.size());
charged_ = false;
}
}
private:
std::string body_;
v8::ExternalMemoryAccounter accounter_;
bool charged_ = false;
};
v8::MaybeLocal<v8::String> SourceString(v8::Isolate* isolate, std::string body,
bool ascii) {
if (body.size() > static_cast<size_t>(v8::String::kMaxLength)) {
return v8::MaybeLocal<v8::String>();
}
if (ascii) {
auto* resource = new OwnedAsciiSource(std::move(body));
v8::Local<v8::String> text;
if (!v8::String::NewExternalOneByte(isolate, resource).ToLocal(&text)) {
delete resource;
return v8::MaybeLocal<v8::String>();
}
resource->Charge(isolate);
return text;
}
return v8::String::NewFromUtf8(isolate, body.data(),
v8::NewStringType::kNormal,
static_cast<int>(body.size()));
}
v8::ScriptOrigin ModuleScriptOrigin(v8::Local<v8::String> name) {
return v8::ScriptOrigin(name, 0, 0, false, -1, v8::Local<v8::Value>(), false,
false, /*is_module=*/true);
}
void ReadCompileOptions(GraphLoaderState& graph, v8::Isolate* isolate) {
if (graph.compileOptionsRead) {
return;
}
const std::string& flags = LoaderConfigFor(isolate).v8Flags;
// Streaming follows --lazy-streaming, not --lazy, so --no-lazy has to be
// passed to it explicitly.
graph.eagerCompile = V8FlagsDisableLazyCompile(flags);
graph.compileStackBytes = BackgroundCompileStackBytes(flags);
graph.compileOptionsRead = true;
}
v8::ScriptCompiler::CompileOptions StreamOptions(const GraphLoaderState& g) {
return g.eagerCompile ? v8::ScriptCompiler::kEagerCompile
: v8::ScriptCompiler::kNoCompileOptions;
}
std::string HttpKey(v8::Isolate* isolate, const std::string& url) {
return http::CanonicalizeNormalizedHttpUrlKey(
url, CanonicalizationConfigFor(isolate));
}
// A registered module that is not errored; empty otherwise.
v8::Local<v8::Module> LiveRegistered(v8::Isolate* isolate,
const std::string& key) {
v8::Local<v8::Module> existing = FindRegisteredModule(isolate, key);
if (!existing.IsEmpty() && existing->GetStatus() != v8::Module::kErrored) {
return existing;
}
return v8::Local<v8::Module>();
}
// Compiles an HTTP module body and registers it under `key`, never
// instantiating it. With `streamed`, finalizes that compile, which ran on
// exactly `body`. A registered key is returned as it is, without compiling.
// On failure V8's exception is left pending for the caller's TryCatch.
v8::MaybeLocal<v8::Module> CompileHttpModule(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const std::string& key,
std::string body, bool ascii,
StreamedModuleCompile* streamed) {
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::Module> existing = FindRegisteredModule(isolate, key);
if (!existing.IsEmpty()) {
if (streamed != nullptr) {
g_counters.discarded.fetch_add(1, std::memory_order_relaxed);
}
return scope.Escape(existing);
}
v8::Local<v8::String> name;
v8::Local<v8::String> text;
if (!v8::String::NewFromUtf8(isolate, key.data(), v8::NewStringType::kNormal,
static_cast<int>(key.size()))
.ToLocal(&name) ||
!SourceString(isolate, std::move(body), ascii).ToLocal(&text)) {
isolate->ThrowException(v8::Exception::RangeError(
ToV8String(isolate, "Module too large: " + key)));
return v8::MaybeLocal<v8::Module>();
}
v8::ScriptOrigin origin = ModuleScriptOrigin(name);
v8::Local<v8::Module> mod;
bool compiled;
if (streamed != nullptr) {
g_counters.finalized.fetch_add(1, std::memory_order_relaxed);
compiled = v8::ScriptCompiler::CompileModule(
context, streamed->source.get(), text, origin)
.ToLocal(&mod);
} else {
v8::ScriptCompiler::Source source(text, origin);
compiled =
v8::ScriptCompiler::CompileModule(isolate, &source).ToLocal(&mod);
}
if (!compiled) {
return v8::MaybeLocal<v8::Module>();
}
SetRegisteredModule(isolate, key, mod);
return scope.Escape(mod);
}
// ── Streamed HTTP compiles ───────────────────────────────────────────────────
// Isolate thread, when the fetch is issued. Null when V8 declines to stream;
// otherwise the compile waits in the state, its stream empty until the
// transport feeds it.
std::shared_ptr<StreamTicket> BeginStreamedCompile(v8::Isolate* isolate,
GraphLoaderState& graph) {
ReadCompileOptions(graph, isolate);
auto compile = std::make_unique<StreamedModuleCompile>();
auto stream = std::make_unique<BodySourceStream>();
compile->stream = stream.get();
compile->source = std::make_unique<v8::ScriptCompiler::StreamedSource>(
std::move(stream), v8::ScriptCompiler::StreamedSource::UTF8);
compile->task.reset(v8::ScriptCompiler::StartStreaming(
isolate, compile->source.get(), v8::ScriptType::kModule,
StreamOptions(graph)));
if (compile->task == nullptr) {
return nullptr;
}
auto ticket = std::make_shared<StreamTicket>();
ticket->id = graph.nextStreamedCompileId++;
ticket->stackBytes = graph.compileStackBytes;
ticket->stream = compile->stream;
ticket->task = compile->task.get();
graph.streamedCompiles.emplace(ticket->id, std::move(compile));
return ticket;
}
// Isolate thread: the ticket's compile, now the caller's.
std::unique_ptr<StreamedModuleCompile> TakeStreamedCompile(
GraphLoaderState& graph, const StreamTicket* ticket) {
if (ticket == nullptr) {
return nullptr;
}
auto it = graph.streamedCompiles.find(ticket->id);
if (it == graph.streamedCompiles.end()) {
return nullptr;
}
std::unique_ptr<StreamedModuleCompile> compile = std::move(it->second);
graph.streamedCompiles.erase(it);
return compile;
}
bool IsStreamableBody(const http::ModuleFetchResult& result) {
return result.ok && result.kind == http::ModuleResponseKind::kJavaScript &&
result.body.size() >= kOffThreadCompileThresholdBytes &&
!StartsWithBom(result.body);
}
// Transport thread. Runs the ticket's compile on the pool, which then posts
// `completion`. False, having run nothing, when the body is not to be
// streamed; the caller then posts `completion` itself.
bool DispatchStreamedCompile(
const std::shared_ptr<RuntimeLiveness>& liveness,
const std::shared_ptr<StreamTicket>& ticket,
const std::shared_ptr<http::ModuleFetchResult>& result,
const std::function<void()>& completion) {
if (!IsStreamableBody(*result) || !liveness->Enter()) {
return false;
}
const bool posted = CompilePool::Shared().Post(
liveness.get(), ticket->stackBytes,
[liveness = liveness, ticket = ticket, result = result,
completion = completion](bool run) mutable {
if (run && liveness->IsAlive()) {
const std::string& body = result->body;
std::unique_ptr<uint8_t[]> chunk(new uint8_t[body.size()]);
std::memcpy(chunk.get(), body.data(), body.size());
ticket->ascii = IsAscii(body);
ticket->stream->Feed(std::move(chunk), body.size());
g_counters.running.fetch_add(1, std::memory_order_relaxed);
ticket->task->Run();
g_counters.running.fetch_sub(1, std::memory_order_relaxed);
ticket->ran = true;
liveness->Post(std::move(completion));
}
completion = nullptr;
ticket.reset();
result.reset();
const std::shared_ptr<RuntimeLiveness> token = std::move(liveness);
token->Leave();
});
if (!posted) {
liveness->Leave();
return false;
}
return true;
}
// ── File jobs ────────────────────────────────────────────────────────────────
// Pool thread, inside the section. Reads the file, then consumes the code
// cache or runs the streamed compile. Leaves `ran` false when neither
// happened, and the isolate's thread then compiles `body` itself.
void RunFileModuleJob(FileModuleJob& job) {
job.readOk = platform::ReadFile(job.path, job.body);
if (!job.readOk) {
return;
}
job.ascii = IsAscii(job.body);
FileModuleCompile& compile = *job.compile;
if (job.mode == FileModuleJob::Mode::kConsume) {
job.cacheMatchesBody = SourceUnchanged(job.path, job.cache->source);
if (!job.cacheMatchesBody) {
return;
}
std::optional<CodeCacheBytes> bytes = LoadCodeCache(*job.cache);
if (!bytes) {
return;
}
// The isolate is used only to find its heap; the task runs here.
compile.consumeTask.reset(
v8::ScriptCompiler::StartConsumingCodeCacheOnBackground(
job.liveness->isolate(), ToCachedData(std::move(*bytes))));
if (compile.consumeTask != nullptr) {
compile.consumeTask->Run();
job.ran = true;
}
return;
}
if (compile.streamTask == nullptr || StartsWithBom(job.body)) {
return;
}
std::unique_ptr<uint8_t[]> chunk(new uint8_t[job.body.size()]);
std::memcpy(chunk.get(), job.body.data(), job.body.size());
compile.stream->Feed(std::move(chunk), job.body.size());
compile.streamTask->Run();
job.ran = true;
}
void OnFileModuleJobCompleted(const std::shared_ptr<FileModuleJob>& job);
// Whether a walk on the calling thread may wait for a file job. Without a
// loop the completion could not be delivered, and off the home thread
// (multithreaded JavaScript) a synchronous wait would hold the Locker the
// loop needs to deliver it.
bool CanWaitForFileJobs(v8::Isolate* isolate) {
const std::shared_ptr<RuntimeLiveness> liveness = LivenessFor(isolate);
if (liveness == nullptr) {
return false;
}
std::shared_ptr<Loop> loop = liveness->LockLoop();
return loop != nullptr && loop->IsOnHomeThread();
}
// Isolate thread. Starts loading the file `resolution` names on the pool and
// records the job under its key, or returns null when the file is to be
// compiled inline: not .mjs (a .js file needs CompileFileModule's
// detection), too small to be worth the hop, or the pool refused it. Callers
// check CanWaitForFileJobs.
std::shared_ptr<FileModuleJob> DispatchFileModuleJob(
v8::Isolate* isolate, GraphLoaderState& graph,
const ModuleResolution& resolution) {
const std::string& path = resolution.path;
if (!EndsWith(path, ".mjs")) {
return nullptr;
}
const std::optional<FileInfo> info = platform::Stat(path);
if (!info || !info->isFile || info->size < kOffThreadCompileThresholdBytes) {
return nullptr;
}
std::optional<CodeCacheEntry> cache = CodeCacheEntryFor(
path, CodeCacheKind::kEsModule, *info, LoaderConfigFor(isolate));
const bool freshCache = cache && HasFreshCodeCache(*cache);
if (freshCache && info->size < kOffThreadCacheConsumeThresholdBytes) {
return nullptr;
}
ReadCompileOptions(graph, isolate);
auto job = std::make_shared<FileModuleJob>();
job->liveness = LivenessFor(isolate);
job->signal = graph.fileJobSignal;
job->path = path;
job->key = resolution.key;
job->query = resolution.query;
job->cache = std::move(cache);
auto compile = std::make_unique<FileModuleCompile>();
if (freshCache) {
job->mode = FileModuleJob::Mode::kConsume;
} else {
auto stream = std::make_unique<BodySourceStream>();
compile->stream = stream.get();
compile->source = std::make_unique<v8::ScriptCompiler::StreamedSource>(
std::move(stream), v8::ScriptCompiler::StreamedSource::UTF8);
// Null when V8 declines to stream; the read still moves off-thread.
compile->streamTask.reset(v8::ScriptCompiler::StartStreaming(
isolate, compile->source.get(), v8::ScriptType::kModule,
StreamOptions(graph)));
}
job->compile = compile.get();
if (!job->liveness->Enter()) {
return nullptr;
}
job->id = graph.nextFileJobId++;
graph.fileCompiles.emplace(job->id, std::move(compile));
const bool posted = CompilePool::Shared().Post(
job->liveness.get(), graph.compileStackBytes, [job](bool run) mutable {
const std::shared_ptr<RuntimeLiveness> liveness = job->liveness;
{
const std::shared_ptr<FileModuleJob> ref = std::move(job);
if (run && liveness->IsAlive()) {
RunFileModuleJob(*ref);
ref->ready.store(true, std::memory_order_release);
liveness->Post([ref] { OnFileModuleJobCompleted(ref); });
ref->signal->Notify();
}
}
liveness->Leave();
});
if (!posted) {
graph.fileCompiles.erase(job->id);
job->liveness->Leave();
return nullptr;
}
graph.fileJobs[job->key] = job;
return job;
}
// Isolate thread, isolate and `context` entered; the job has finished on the
// pool (`ready`). Compiles and registers its module unless the key was
// invalidated meanwhile or something else registered it first. A compile
// failure is swallowed, as the inline walk's is: the resolver (or the root's
// own load) compiles again and owns the error. Idempotent.
void FinalizeFileModuleJob(v8::Isolate* isolate, v8::Local<v8::Context> context,
ModuleLoaderState& state, FileModuleJob& job) {
if (job.finalized) {
return;
}
job.finalized = true;
GraphLoaderState& graph = state.graph;
std::unique_ptr<FileModuleCompile> compile;
auto compileIt = graph.fileCompiles.find(job.id);
if (compileIt != graph.fileCompiles.end()) {
compile = std::move(compileIt->second);
graph.fileCompiles.erase(compileIt);
}
auto jobIt = graph.fileJobs.find(job.key);
if (jobIt != graph.fileJobs.end() && jobIt->second.get() == &job) {
graph.fileJobs.erase(jobIt);
}
if (job.superseded || compile == nullptr || !job.readOk ||
!LiveRegistered(isolate, job.key).IsEmpty()) {
return;
}
v8::HandleScope handleScope(isolate);
v8::TryCatch tc(isolate);
const std::string url =
ModuleOrigin(job.path, job.query, LoaderConfigFor(isolate));
v8::Local<v8::String> name;
v8::Local<v8::String> text;
if (!v8::String::NewFromUtf8(isolate, url.data(), v8::NewStringType::kNormal,
static_cast<int>(url.size()))
.ToLocal(&name) ||
!SourceString(isolate, std::move(job.body), job.ascii).ToLocal(&text)) {
return;
}
job.body = std::string();
v8::ScriptOrigin origin = ModuleScriptOrigin(name);
v8::Local<v8::Module> mod;
bool compiled = false;
bool cacheConsumed = false;
if (job.ran && job.mode == FileModuleJob::Mode::kStream) {
compiled = v8::ScriptCompiler::CompileModule(context, compile->source.get(),
text, origin)
.ToLocal(&mod);
} else if (job.ran) {
// V8 records its verdict in the Source's CachedData, so one is required
// even though the task carries the bytes. A rejected cache falls back to
// a full compile inside this call.
v8::ScriptCompiler::Source source(text, origin,
new v8::ScriptCompiler::CachedData(),
compile->consumeTask.release());
compiled = v8::ScriptCompiler::CompileModule(
isolate, &source, v8::ScriptCompiler::kConsumeCodeCache)
.ToLocal(&mod);
cacheConsumed = compiled && !source.GetCachedData()->rejected;
} else {
// A consume that did not run on the pool still uses the fresh cache: a
// consume is several times cheaper than a compile (DESIGN, Q14).
std::unique_ptr<v8::ScriptCompiler::CachedData> cached;
if (job.mode == FileModuleJob::Mode::kConsume && job.cacheMatchesBody) {
if (std::optional<CodeCacheBytes> bytes = LoadCodeCache(*job.cache)) {
cached = ToCachedData(std::move(*bytes));
}
}
const bool consume = cached != nullptr;
// The Source owns the cached data.
v8::ScriptCompiler::Source source(text, origin, cached.release());
compiled = v8::ScriptCompiler::CompileModule(
isolate, &source,
consume ? v8::ScriptCompiler::kConsumeCodeCache
: v8::ScriptCompiler::kNoCompileOptions)
.ToLocal(&mod);
cacheConsumed = compiled && consume && !source.GetCachedData()->rejected;
}
if (!compiled) {
NS_TRACE(TraceCategory::kEsm,
"[graph][file-job-compile-fail] %s %s (left to the resolver)",
job.path.c_str(),
DescribeCaughtError(isolate, context, tc).c_str());
return;
}
SetRegisteredModule(isolate, job.key, mod, job.path);
if (!cacheConsumed && job.cache && !state.closing) {
QueueCodeCache(isolate, mod->GetUnboundModuleScript(),
std::move(*job.cache));
}
}
// ── The walk ─────────────────────────────────────────────────────────────────
void Enqueue(const std::shared_ptr<AsyncGraphLoad>& load,
ModuleLoaderState& state, const ModuleResolution& resolution);
// The walk's context; empty once it completed or was killed.
v8::Local<v8::Context> WalkContext(v8::Isolate* isolate,
const GraphLoaderState& graph,
const AsyncGraphLoad& load) {
auto it = graph.walkContexts.find(load.seq);
return it != graph.walkContexts.end() ? it->second.Get(isolate)
: v8::Local<v8::Context>();
}
bool ShouldParkWalk(const GraphLoaderState& graph, const AsyncGraphLoad& load) {
return graph.syncLoadDepth > 0 && load.seq < graph.parkWalksBefore;
}
// Enqueues every edge of `mod` the walk can load. `moduleKey` is the key it is
// registered under, which relative specifiers resolve against.
void WalkModuleRequests(const std::shared_ptr<AsyncGraphLoad>& load,
ModuleLoaderState& state, v8::Local<v8::Module> mod,
const std::string& moduleKey) {
v8::Isolate* isolate = load->isolate;
v8::Local<v8::FixedArray> requests = mod->GetModuleRequests();
const int length = requests->Length();
for (int i = 0; i < length; i++) {
v8::Local<v8::ModuleRequest> request =
requests->Get(i).As<v8::ModuleRequest>();
if (request.IsEmpty()) {
continue;
}
v8::String::Utf8Value utf8(isolate, request->GetSpecifier());
if (*utf8 == nullptr) {
continue;
}
const std::string_view spec(*utf8, static_cast<size_t>(utf8.length()));
// A specifier holding U+0000 is left for the resolver to refuse.
if (spec.find('\0') != std::string_view::npos) {
continue;
}
const ModuleResolution resolution =
ResolveModuleSpecifier(isolate, spec, moduleKey);
if (resolution.kind == ModuleResolution::Kind::kHttp ||
resolution.kind == ModuleResolution::Kind::kFile) {
Enqueue(load, state, resolution);
}
}
}
void StopCountingWalk(AsyncGraphLoad& load) {
if (load.running) {
load.running = false;
g_walksRunning.fetch_sub(1, std::memory_order_acq_rel);
}
}
// Runs onComplete exactly once, when nothing is pending.
void MaybeComplete(const std::shared_ptr<AsyncGraphLoad>& load,
GraphLoaderState& graph, v8::Local<v8::Context> context) {
if (load->completed || load->pendingFetches > 0) {
return;
}
load->completed = true;
StopCountingWalk(*load);
graph.walkContexts.erase(load->seq);
v8::Local<v8::Value> exception;
auto exceptionIt = graph.rootExceptions.find(load->seq);
if (exceptionIt != graph.rootExceptions.end()) {
exception = exceptionIt->second.Get(load->isolate);
graph.rootExceptions.erase(exceptionIt);
}
NS_TRACE(TraceCategory::kEsm,
"[graph][done] root=%s urls=%zu fetched=%zu compiled=%zu ms=%.1f "
"ok=%d",
load->rootKey.c_str(), load->visited.size(), load->fetchedCount,
load->compiledCount, MsSince(load->start), load->failed ? 0 : 1);
GraphLoadCompletion onComplete = std::move(load->onComplete);
load->onComplete = nullptr;
if (onComplete) {
// Failures already surface through the caller's own channel.
v8::TryCatch tc(load->isolate);
onComplete(!load->failed, load->failureMessage, exception, context);
}
}
void FailRoot(AsyncGraphLoad& load, std::string message,
const std::string& detail) {
load.failed = true;
load.failureMessage = std::move(message);
if (!detail.empty()) {
load.failureMessage += " — " + detail;
}
}
// A fetch verdict, delivered through the token. Compiles and registers the
// module, then walks its requests.
void OnFetchCompleted(const std::shared_ptr<AsyncGraphLoad>& load,
const std::string& url,
const std::shared_ptr<http::ModuleFetchResult>& fetched,
const std::shared_ptr<StreamTicket>& ticket) {
v8::Isolate* isolate = load->isolate;
v8::Locker locker(isolate);
v8::Isolate::Scope isolateScope(isolate);
v8::HandleScope handleScope(isolate);
ModuleLoaderState* state = LoaderStateFor(isolate);
if (state == nullptr || load->killed) {
return;
}
GraphLoaderState& graph = state->graph;
if (ShouldParkWalk(graph, *load)) {
graph.parkedWalks.emplace_back([load, url, fetched, ticket] {
OnFetchCompleted(load, url, fetched, ticket);
});
return;
}
std::unique_ptr<StreamedModuleCompile> streamed =
TakeStreamedCompile(graph, ticket.get());
const bool streamedRan = streamed != nullptr && ticket->ran;
v8::Local<v8::Context> context = WalkContext(isolate, graph, *load);
if (context.IsEmpty()) {
return;
}
v8::Context::Scope contextScope(context);
load->pendingFetches--;
load->pendingHttpFetches--;
const std::string key = HttpKey(isolate, url);
const bool isRoot = key == load->rootKey;
if (!load->failed) {
if (!fetched->ok) {
if (isRoot) {
FailRoot(*load, fetched->failureReason, std::string());
} else {
NS_TRACE(TraceCategory::kEsm,
"[graph][dep-fetch-fail] %s (left to the resolver)",
fetched->failureReason.c_str());
}
} else if (fetched->kind == http::ModuleResponseKind::kJson) {
load->fetchedCount++;
v8::TryCatch tc(isolate);
if (CreateJsonModule(isolate, context, std::move(fetched->body), key, url,
std::string())
.IsEmpty()) {
const std::string reason = DescribeCaughtError(isolate, context, tc);
if (isRoot) {
FailRoot(*load, "JSON module failed to compile: " + url, reason);
if (tc.HasCaught()) {
graph.rootExceptions[load->seq].Reset(isolate, tc.Exception());
}
} else {
NS_TRACE(TraceCategory::kEsm,
"[graph][dep-json-fail] %s %s (left to the resolver)",
url.c_str(), reason.c_str());
}
} else {
load->compiledCount++;
}
} else {
load->fetchedCount++;
if (!streamedRan && IsStreamableBody(*fetched)) {
g_counters.fellBack.fetch_add(1, std::memory_order_relaxed);
}
v8::Local<v8::Module> mod;
std::string compileError;
{
// Consumed here: this task runs on to a microtask checkpoint, and the
// text belongs in the walk's own failure channel.
v8::TryCatch tc(isolate);
if (!CompileHttpModule(isolate, context, key, std::move(fetched->body),
streamedRan && ticket->ascii,
streamedRan ? streamed.get() : nullptr)
.ToLocal(&mod)) {
compileError = DescribeCaughtError(isolate, context, tc);
}
streamed.reset();
}
if (mod.IsEmpty()) {
if (isRoot) {
FailRoot(*load, "HTTP import compile failed: " + url, compileError);
} else {
NS_TRACE(TraceCategory::kEsm,
"[graph][dep-compile-fail] %s %s (left to the resolver)",
url.c_str(), compileError.c_str());
}
} else {
load->compiledCount++;
WalkModuleRequests(load, *state, mod, key);
}
}
}
MaybeComplete(load, graph, context);
// Promise jobs onComplete queued (waiters, top-level await) run now, as the
// synchronous loader's pump would run them.
isolate->PerformMicrotaskCheckpoint();
}
// A file below the off-thread thresholds, or one the pool cannot take: read,
// compile and register it inline, then keep walking. A failure is swallowed:
// the walk only discovers, and the resolver (or the root's own load) owns the
// error for a module that will not compile.
void CompileLocalModule(const std::shared_ptr<AsyncGraphLoad>& load,
ModuleLoaderState& state,
v8::Local<v8::Context> context,
const ModuleResolution& resolution) {
v8::Isolate* isolate = load->isolate;
const std::string& path = resolution.path;
v8::Local<v8::Module> mod;
{
v8::TryCatch tc(isolate);
bool compiled = false;
try {
compiled = CompileFileModule(isolate, context, path,
ModuleOrigin(path, resolution.query,
LoaderConfigFor(isolate)))
.ToLocal(&mod);
} catch (JsError& error) {
NS_TRACE(TraceCategory::kEsm,
"[graph][local-compile-fail] %s %s (left to the resolver)",
path.c_str(), error.what());
return;
} catch (Terminated&) {
return;
}
if (!compiled) {
NS_TRACE(TraceCategory::kEsm,
"[graph][local-compile-fail] %s %s (left to the resolver)",
path.c_str(), DescribeCaughtError(isolate, context, tc).c_str());
return;
}
}
SetRegisteredModule(isolate, resolution.key, mod, path);
load->compiledCount++;
WalkModuleRequests(load, state, mod, resolution.key);
}
// The file module `key` that `load` waited for has been finalized: continue
// the walk through it.
void ContinueWalkAfterFileJob(const std::shared_ptr<AsyncGraphLoad>& load,
const std::string& key) {
v8::Isolate* isolate = load->isolate;
v8::Locker locker(isolate);
v8::Isolate::Scope isolateScope(isolate);
v8::HandleScope handleScope(isolate);
ModuleLoaderState* state = LoaderStateFor(isolate);
if (state == nullptr || load->killed || load->completed) {
return;
}
v8::Local<v8::Context> context = WalkContext(isolate, state->graph, *load);
if (context.IsEmpty()) {
return;
}
v8::Context::Scope contextScope(context);
load->pendingFetches--;
if (!load->failed) {
v8::Local<v8::Module> mod = FindRegisteredModule(isolate, key);
// Anything past kUninstantiated was linked by someone else, its closure
// already resolved.
if (!mod.IsEmpty() && mod->GetStatus() == v8::Module::kUninstantiated) {
load->compiledCount++;
WalkModuleRequests(load, *state, mod, key);
}
}
MaybeComplete(load, state->graph, context);
}
// Delivered through the token, from the loop or a synchronous wait's pump.
void OnFileModuleJobCompleted(const std::shared_ptr<FileModuleJob>& job) {
v8::Isolate* isolate = job->liveness->isolate();
v8::Locker locker(isolate);
v8::Isolate::Scope isolateScope(isolate);
v8::HandleScope handleScope(isolate);
ModuleLoaderState* state = LoaderStateFor(isolate);
if (state == nullptr) {
return;
}
// Without a main context the result stays with the job, for the resolver's
// FinalizeFinishedFileModule; the walks still go on in their own contexts.
v8::Local<v8::Context> context = platform::MainContext(isolate);
if (!context.IsEmpty()) {
v8::Context::Scope contextScope(context);
FinalizeFileModuleJob(isolate, context, *state, *job);
} else {
job->delivered = true;
}
std::vector<std::shared_ptr<AsyncGraphLoad>> waiters =
std::move(job->waiters);
job->waiters.clear();
for (const std::shared_ptr<AsyncGraphLoad>& load : waiters) {
if (ShouldParkWalk(state->graph, *load)) {
state->graph.parkedWalks.emplace_back(
[load, key = job->key] { ContinueWalkAfterFileJob(load, key); });
continue;
}
ContinueWalkAfterFileJob(load, job->key);
}
}
// As the outermost SyncModuleLoadScope closes: hands the walks parked inside
// it back to the loop, as nestable tasks like the completions they came from.
void ReleaseParkedWalks(v8::Isolate* isolate, GraphLoaderState& graph) {
if (graph.parkedWalks.empty()) {
return;
}
std::vector<std::function<void()>> parked = std::move(graph.parkedWalks);
graph.parkedWalks.clear();
const std::shared_ptr<RuntimeLiveness> liveness = LivenessFor(isolate);
if (liveness == nullptr) {
return;
}
for (std::function<void()>& walk : parked) {
liveness->Post([isolate, walk = std::move(walk)] {
v8::Locker locker(isolate);
v8::Isolate::Scope isolateScope(isolate);
ModuleLoaderState* state = LoaderStateFor(isolate);
if (state == nullptr) {
return;
}
// A scope opened since then started after every parked walk.
if (state->graph.syncLoadDepth > 0) {
state->graph.parkedWalks.push_back(walk);
return;
}
walk();
});
}
}
// Adds one resolved edge to the walk's frontier.
void Enqueue(const std::shared_ptr<AsyncGraphLoad>& load,
ModuleLoaderState& state, const ModuleResolution& resolution) {
v8::Isolate* isolate = load->isolate;
GraphLoaderState& graph = state.graph;
const bool isHttp = resolution.kind == ModuleResolution::Kind::kHttp;
// The key the resolver looks the module up by.
const std::string key =
isHttp ? HttpKey(isolate, resolution.url) : resolution.key;
if (!load->visited.insert(key).second) {
return;
}
v8::Local<v8::Module> existing = FindRegisteredModule(isolate, key);
if (!existing.IsEmpty()) {
if (existing->GetStatus() != v8::Module::kErrored) {
// Compiled but never linked (an earlier partial walk): its own
// requests may not be registered yet.
if (existing->GetStatus() == v8::Module::kUninstantiated) {
WalkModuleRequests(load, state, existing, key);
}
return;
}
RemoveModuleFromRegistry(isolate, key);
}
if (!isHttp) {
// JSON has no imports to discover, and is parsed, not compiled.
if (EndsWith(resolution.path, ".json")) {
return;
}
// A job is not waited for off the home thread either: the inline compile
// registers first, and the job's finalize then defers to it.
v8::Local<v8::Context> context = WalkContext(isolate, graph, *load);
std::shared_ptr<FileModuleJob> job;
auto jobIt = graph.fileJobs.find(key);
if (jobIt != graph.fileJobs.end() && jobIt->second->delivered) {
if (!context.IsEmpty()) {
const std::shared_ptr<FileModuleJob> delivered = jobIt->second;
FinalizeFileModuleJob(isolate, context, state, *delivered);
v8::Local<v8::Module> mod = LiveRegistered(isolate, key);
if (!mod.IsEmpty()) {
load->compiledCount++;
WalkModuleRequests(load, state, mod, key);
return;
}
}
} else if (CanWaitForFileJobs(isolate)) {