-
Notifications
You must be signed in to change notification settings - Fork 249
/
worker.c++
3404 lines (2904 loc) · 131 KB
/
worker.c++
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
// Copyright (c) 2017-2022 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0
#include "worker.h"
#include "promise-wrapper.h"
#include "actor-cache.h"
#include <workerd/util/thread-scopes.h>
#include <workerd/api/global-scope.h>
#include <workerd/api/system-streams.h> // for api::StreamEncoding
#include <workerd/jsg/jsg.h>
#include <workerd/jsg/modules.h>
#include <workerd/jsg/util.h>
#include <workerd/jsg/setup.h>
#include <workerd/io/cdp.capnp.h>
#include <workerd/io/compatibility-date.h>
#include <workerd/util/wait-list.h>
#include <capnp/compat/json.h>
#include <capnp/schema-loader.h>
#include <kj/compat/gzip.h>
#include <kj/encoding.h>
#include <kj/filesystem.h>
#include <kj/map.h>
#include <v8-inspector.h>
#include <v8-profiler.h>
#include <map>
#include <time.h>
#include <sys/syscall.h>
#include <numeric>
namespace v8_inspector {
kj::String KJ_STRINGIFY(const v8_inspector::StringView& view) {
if (view.is8Bit()) {
auto bytes = kj::arrayPtr(view.characters8(), view.length());
for (auto b: bytes) {
if (b & 0x80) {
// Ugh, the bytes aren't just ASCII. We need to re-encode.
auto utf16 = kj::heapArray<char16_t>(bytes.size());
for (auto i: kj::indices(bytes)) {
utf16[i] = bytes[i];
}
return kj::decodeUtf16(utf16);
}
}
// Looks like it's all ASCII.
return kj::str(bytes.asChars());
} else {
return kj::decodeUtf16(kj::arrayPtr(
reinterpret_cast<const char16_t*>(view.characters16()), view.length()));
}
}
}
namespace workerd {
namespace {
class StringViewWithScratch: public v8_inspector::StringView {
public:
StringViewWithScratch(v8_inspector::StringView text, kj::Array<char16_t>&& scratch)
: v8_inspector::StringView(text), scratch(kj::mv(scratch)) {}
private:
kj::Array<char16_t> scratch;
};
StringViewWithScratch toStringView(kj::StringPtr text) {
bool isAscii = true;
for (char c: text) {
if (c & 0x80) {
isAscii = false;
break;
}
}
if (isAscii) {
return { v8_inspector::StringView(text.asBytes().begin(), text.size()), nullptr };
} else {
kj::Array<char16_t> scratch = kj::encodeUtf16(text);
return {
v8_inspector::StringView(reinterpret_cast<uint16_t*>(scratch.begin()), scratch.size()),
kj::mv(scratch)
};
}
}
void headersToCDP(const kj::HttpHeaders& in, capnp::JsonValue::Builder out) {
std::map<kj::StringPtr, kj::Vector<kj::StringPtr>> inMap;
in.forEach([&](kj::StringPtr name, kj::StringPtr value) {
inMap.try_emplace(name, 1).first->second.add(value);
});
auto outObj = out.initObject(inMap.size());
auto headersPos = 0;
for (auto& entry: inMap) {
auto field = outObj[headersPos++];
field.setName(entry.first);
// CDP uses strange header representation where headers with multiple
// values are merged into one newline-delimited string
field.initValue().setString(kj::strArray(entry.second, "\n"));
}
}
void stackTraceToCDP(v8::Isolate* isolate, cdp::Runtime::StackTrace::Builder builder) {
// TODO(cleanup): Maybe use V8Inspector::captureStackTrace() which does this for us. However, it
// produces protocol objects in its own format which want to handle their whole serialization
// to JSON. Also, those protocol objects are defined in generated code which we currently don't
// include in our cached V8 build artifacts; we'd need to fix that. But maybe we should really
// be using the V8-generated protocol objects rather than our parallel capnp versions!
auto stackTrace = v8::StackTrace::CurrentStackTrace(isolate, 10);
auto frameCount = stackTrace->GetFrameCount();
auto callFrames = builder.initCallFrames(frameCount);
for (int i = 0; i < frameCount; i++) {
auto src = stackTrace->GetFrame(isolate, i);
auto dest = callFrames[i];
auto url = src->GetScriptNameOrSourceURL();
if (!url.IsEmpty()) {
dest.setUrl(kj::str(url));
} else {
dest.setUrl(""_kj);
}
dest.setScriptId(kj::str(src->GetScriptId()));
auto func = src->GetFunctionName();
if (!func.IsEmpty()) {
dest.setFunctionName(kj::str(func));
} else {
dest.setFunctionName(""_kj);
}
// V8 locations are 1-based, but CDP locations are 0-based... oh, well
dest.setLineNumber(src->GetLineNumber() - 1);
dest.setColumnNumber(src->GetColumn() - 1);
}
}
kj::Own<capnp::JsonCodec> makeCdpJsonCodec() {
auto codec = kj::heap<capnp::JsonCodec>();
codec->handleByAnnotation<cdp::Command>();
codec->handleByAnnotation<cdp::Event>();
return codec;
}
const capnp::JsonCodec& getCdpJsonCodec() {
static const kj::Own<capnp::JsonCodec> codec = makeCdpJsonCodec();
return *codec;
}
} // namespace
// =======================================================================================
kj::StringPtr KJ_STRINGIFY(UncaughtExceptionSource value) {
switch (value) {
case UncaughtExceptionSource::INTERNAL: return "Uncaught"_kj;
case UncaughtExceptionSource::INTERNAL_ASYNC: return "Uncaught (in promise)"_kj;
case UncaughtExceptionSource::ASYNC_TASK: return "Uncaught (async)"_kj;
case UncaughtExceptionSource::REQUEST_HANDLER: return "Uncaught (in response)"_kj;
case UncaughtExceptionSource::TRACE_HANDLER: return "Uncaught (in trace)"_kj;
};
KJ_UNREACHABLE;
}
namespace {
void addJsStackTrace(v8::Local<v8::Context> context,
kj::Vector<kj::String>& lines, v8::Local<v8::Message> message) {
// TODO(someday): Relying on v8::Message to pass around source locations means
// we can't provide the module name for errors like compiling wasm modules. We
// should have our own type, but it requires a refactor of how we pass around errors
// for script startup.
auto addLineCol = [](kj::StringTree str, int line, int col) {
if (line != v8::Message::kNoLineNumberInfo) {
str = kj::strTree(kj::mv(str), ":", line);
if (col != v8::Message::kNoColumnInfo) {
str = kj::strTree(kj::mv(str), ":", col);
}
}
return str;
};
if (!message.IsEmpty()) {
auto trace = message->GetStackTrace();
if (trace.IsEmpty() || trace->GetFrameCount() == 0) {
kj::StringTree locationStr;
auto resourceNameVal = message->GetScriptResourceName();
if (resourceNameVal->IsString()) {
auto resourceName = resourceNameVal.As<v8::String>();
if (!resourceName.IsEmpty() && resourceName->Length() != 0) {
locationStr = kj::strTree(" at ", resourceName);
}
}
auto lineNumber = jsg::check(message->GetLineNumber(context));
auto columnNumber = jsg::check(message->GetStartColumn(context));
locationStr = addLineCol(kj::mv(locationStr), lineNumber, columnNumber);
if (locationStr.size() > 0) {
lines.add(locationStr.flatten());
}
} else {
for (auto i: kj::zeroTo(trace->GetFrameCount())) {
auto frame = trace->GetFrame(context->GetIsolate(), i);
kj::StringTree locationStr;
auto scriptName = frame->GetScriptName();
if (!scriptName.IsEmpty() && scriptName->Length() != 0) {
locationStr = kj::strTree(" at ", scriptName);
} else {
locationStr = kj::strTree(" at worker.js");
}
auto lineNumber = frame->GetLineNumber();
auto columnNumber = frame->GetColumn();
locationStr = addLineCol(kj::mv(locationStr), lineNumber, columnNumber);
auto func = frame->GetFunctionName();
if (!func.IsEmpty() && func->Length() != 0) {
locationStr = kj::strTree(kj::mv(locationStr), " in ", func);
}
lines.add(locationStr.flatten());
}
}
}
}
void sendExceptionToInspector(v8_inspector::V8Inspector& inspector, v8::Local<v8::Context> context,
kj::StringPtr description) {
// Inform the inspector of a problem not associated with any particular exception object.
//
// Passes `description` as the exception's detailed message, dummy values for everything else.
inspector.exceptionThrown(context, v8_inspector::StringView(), v8::Local<v8::Value>(),
toStringView(description), v8_inspector::StringView(),
0, 0, nullptr, 0);
}
void sendExceptionToInspector(v8_inspector::V8Inspector& inspector, v8::Local<v8::Context> context,
UncaughtExceptionSource source, v8::Local<v8::Value> exception,
v8::Local<v8::Message> message) {
// Inform the inspector of an exception thrown.
//
// Passes `source` as the exception's short message. Reconstructs `message` from `exception` if
// `message` is empty.
if (message.IsEmpty()) {
// This exception didn't come with a Message. This can happen for exceptions delivered via
// v8::Promise::Catch(), or for exceptions which were tunneled through C++ promises. In the
// latter case, V8 will create a Message based on the current stack trace, but it won't be
// super meaningful.
message = v8::Exception::CreateMessage(context->GetIsolate(), exception);
KJ_ASSERT(!message.IsEmpty());
}
auto stackTrace = message->GetStackTrace();
// The resource name is whatever we set in the Script ctor, e.g. "worker.js".
auto scriptResourceName = message->GetScriptResourceName();
auto lineNumber = message->GetLineNumber(context).FromMaybe(0);
auto startColumn = message->GetStartColumn(context).FromMaybe(0);
// TODO(soon): EW-2636 Pass a real "script ID" as the last parameter instead of 0. I suspect this
// has something to do with the incorrect links in the console when it logs uncaught exceptions.
inspector.exceptionThrown(context, toStringView(kj::str(source)), exception,
toStringView(kj::str(message->Get())), toStringView(kj::str(scriptResourceName)),
lineNumber, startColumn, inspector.createStackTrace(stackTrace), 0);
}
void addExceptionToTrace(jsg::Lock& js, IoContext &ioContext, WorkerTracer& tracer,
v8::Local<v8::Context> context, UncaughtExceptionSource source,
v8::Local<v8::Value> exception,
const jsg::TypeHandler<Worker::ApiIsolate::ErrorInterface>&
errorTypeHandler) {
if (source == UncaughtExceptionSource::INTERNAL ||
source == UncaughtExceptionSource::INTERNAL_ASYNC) {
// Skip redundant intermediate JS->C++ exception reporting. See: IoContext::runImpl(),
// PromiseWrapper::tryUnwrap()
//
// TODO(someday): Arguably it could make sense to store these exceptions off to the side and
// report them only if they don't end up being duplicates of a later exception that has a more
// specific context. This would cover cases where the C++ code that eventually received the
// exception never ended up reporting it.
return;
}
auto timestamp = ioContext.now();
auto error = KJ_REQUIRE_NONNULL(errorTypeHandler.tryUnwrap(js, exception),
"Should always be possible to unwrap error interface from an object.");
kj::String name;
KJ_IF_MAYBE(n, error.name) {
name = kj::str(*n);
} else {
name = kj::str("Error");
}
kj::String message;
KJ_IF_MAYBE(m, error.message) {
message = kj::str(*m);
}
// TODO(someday): Limit size of exception content?
tracer.addException(timestamp, kj::mv(name), kj::mv(message));
}
void reportStartupError(
kj::StringPtr id,
jsg::Lock& lock,
const kj::Maybe<std::unique_ptr<v8_inspector::V8Inspector>>& inspector,
v8::Local<v8::Context> context,
const IsolateLimitEnforcer& limitEnforcer,
kj::Maybe<kj::Exception> maybeLimitError,
v8::TryCatch& catcher,
kj::Maybe<Worker::ValidationErrorReporter&> errorReporter,
kj::Maybe<kj::Exception>& permanentException) {
v8::TryCatch catcher2(lock.v8Isolate);
kj::Maybe<kj::Exception> maybeLimitError2;
try {
KJ_IF_MAYBE(limitError, maybeLimitError) {
auto description = jsg::extractTunneledExceptionDescription(limitError->getDescription());
auto& ex = permanentException.emplace(kj::mv(*limitError));
KJ_IF_MAYBE(e, errorReporter) {
e->addError(kj::mv(description));
} else KJ_IF_MAYBE(i, inspector) {
// We want to extend just enough cpu time as is necessary to report the exception
// to the inspector here. 10 milliseconds should be more than enough.
auto limitScope = limitEnforcer.enterLoggingJs(lock, maybeLimitError2);
sendExceptionToInspector(*i->get(), context, description);
// When the inspector is active, we don't want to throw here because then the inspector
// won't be able to connect and the developer will never know what happened.
} else {
// We should never get here in production if we've validated scripts before deployment.
KJ_LOG(ERROR, "script startup exceeded resource limits", id, ex);
kj::throwFatalException(kj::cp(ex));
}
} else if (catcher.HasCaught()) {
v8::HandleScope handleScope(lock.v8Isolate);
auto exception = catcher.Exception();
permanentException = lock.exceptionToKj(jsg::Value(lock.v8Isolate, exception));
KJ_IF_MAYBE(e, errorReporter) {
auto limitScope = limitEnforcer.enterLoggingJs(lock, maybeLimitError2);
kj::Vector<kj::String> lines;
lines.add(kj::str("Uncaught ", jsg::extractTunneledExceptionDescription(
KJ_ASSERT_NONNULL(permanentException).getDescription())));
addJsStackTrace(context, lines, catcher.Message());
e->addError(kj::strArray(lines, "\n"));
} else KJ_IF_MAYBE(i, inspector) {
auto limitScope = limitEnforcer.enterLoggingJs(lock, maybeLimitError2);
sendExceptionToInspector(*i->get(), context, UncaughtExceptionSource::INTERNAL,
exception, catcher.Message());
// When the inspector is active, we don't want to throw here because then the inspector
// won't be able to connect and the developer will never know what happened.
} else {
// We should never get here in production if we've validated scripts before deployment.
kj::Vector<kj::String> lines;
addJsStackTrace(context, lines, catcher.Message());
auto trace = kj::strArray(lines, "; ");
auto description = KJ_ASSERT_NONNULL(permanentException).getDescription();
if (description == "jsg.SyntaxError: \\8 and \\9 are not allowed in template strings.") {
// HACK: There are two scripts in production that throw this at startup and we can't get
// in contact with the owners to fix them. It should be impossible to upload new
// scripts with this problem as the validator will block it. We'll return normally
// here, which means that script startup will appear to succeed, but all requests to
// the isolate will throw the original exception, via `permanentException`. This avoids
// log spam and avoids reloading the script from scratch on every request.
//
// TODO(soon): We add logging here to see if this hack is still necessary or if it can be
// removed. Adding this additional logging should be temporary! If we hit this log in
// sentry even once, then we'll keep the hack, otherwise we can likely safely remove it.
static bool logOnce KJ_UNUSED = ([] {
KJ_LOG(WARNING, "reportStartupError() customer-specific SyntaxError hack "
"is still relevant.");
return true;
})();
} else {
KJ_LOG(ERROR, "script startup threw exception", id, description, trace);
KJ_FAIL_REQUIRE("script startup threw exception");
}
}
} else {
kj::throwFatalException(kj::cp(permanentException.emplace(
KJ_EXCEPTION(FAILED, "returned empty handle but didn't throw exception?", id))));
}
} catch (const jsg::JsExceptionThrown&) {
#define LOG_AND_SET_PERM_EXCEPTION(...) \
KJ_LOG(ERROR, __VA_ARGS__); \
if (permanentException == nullptr) { \
permanentException = KJ_EXCEPTION(FAILED, __VA_ARGS__); \
}
KJ_IF_MAYBE(limitError2, maybeLimitError2) {
// TODO(cleanup): If we see this error show up in production, stop logging it, because I
// guess it's not necessarily an error? The other two cases below are more worrying though.
KJ_LOG(ERROR, *limitError2);
if (permanentException == nullptr) {
permanentException = kj::mv(*limitError2);
}
} else if (catcher2.HasTerminated()) {
LOG_AND_SET_PERM_EXCEPTION(
"script startup threw exception; during our attempt to stringify the exception, "
"the script apparently was terminated for non-resource-limit reasons.", id);
} else {
LOG_AND_SET_PERM_EXCEPTION(
"script startup threw exception; furthermore, an attempt to stringify the exception "
"threw another exception, which shouldn't be possible?", id);
}
#undef LOG_AND_SET_PERM_EXCEPTION
}
}
uint64_t getCurrentThreadId() {
#if __linux__
return syscall(SYS_gettid);
#else
// Assume MacOS or BSD
uint64_t tid;
pthread_threadid_np(NULL, &tid);
return tid;
#endif
}
} // namespace
class Worker::InspectorClient: public v8_inspector::V8InspectorClient {
public:
double currentTimeMS() override {
// Wall time in milliseconds with millisecond precision. console.time() and friends rely on this
// function to implement timers.
auto timePoint = kj::UNIX_EPOCH;
if (IoContext::hasCurrent()) {
// We're on a request-serving thread.
auto& ioContext = IoContext::current();
timePoint = ioContext.now();
} else KJ_IF_MAYBE(info, inspectorTimerInfo) {
if (info->threadId == getCurrentThreadId()) {
// We're on an inspector-serving thread.
timePoint = info->timer.now() + info->timerOffset
- kj::origin<kj::TimePoint>() + kj::UNIX_EPOCH;
}
}
// If we're on neither a request- nor inspector-serving thread, then we're at script startup
// time -- just return the Epoch.
return (timePoint - kj::UNIX_EPOCH) / kj::MILLISECONDS;
}
// Nothing else. We ignore everything the inspector tells us, because we only care about the
// devtools inspector protocol, which is handled separately.
void setInspectorTimerInfo(kj::Timer& timer, kj::Duration timerOffset) {
// Helper for attachInspector().
inspectorTimerInfo = InspectorTimerInfo { timer, timerOffset, getCurrentThreadId() };
}
private:
struct InspectorTimerInfo {
kj::Timer& timer;
kj::Duration timerOffset;
uint64_t threadId;
};
kj::Maybe<InspectorTimerInfo> inspectorTimerInfo;
// The timer and offset for the inspector-serving thread.
};
void setWebAssemblyModuleHasInstance(jsg::Lock& lock, v8::Local<v8::Context> context);
// Defined later in this file.
static thread_local uint warnAboutIsolateLockScopeCount = 0;
static thread_local const Worker::ApiIsolate* currentApiIsolate = nullptr;
const Worker::ApiIsolate& Worker::ApiIsolate::current() {
KJ_REQUIRE(currentApiIsolate != nullptr, "not running JavaScript");
return *currentApiIsolate;
}
Worker::WarnAboutIsolateLockScope::WarnAboutIsolateLockScope() {
++warnAboutIsolateLockScopeCount;
}
void Worker::WarnAboutIsolateLockScope::release() {
if (!released) {
--warnAboutIsolateLockScopeCount;
released = true;
}
}
struct Worker::Impl {
kj::Maybe<jsg::JsContext<api::ServiceWorkerGlobalScope>> context;
kj::Maybe<jsg::Value> env;
// The environment blob to pass to handlers.
kj::Maybe<api::ExportedHandler> defaultHandler;
kj::HashMap<kj::String, api::ExportedHandler> namedHandlers;
kj::HashMap<kj::String, DurableObjectConstructor> actorClasses;
kj::Maybe<kj::Exception> permanentException;
// If set, then any attempt to use this worker shall throw this exception.
};
struct Worker::Isolate::Impl {
// Note that Isolate mutable state is protected by locking the JsgWorkerIsolate unless otherwise
// noted.
IsolateObserver& metrics;
InspectorClient inspectorClient;
kj::Maybe<std::unique_ptr<v8_inspector::V8Inspector>> inspector;
kj::Maybe<kj::Own<v8::CpuProfiler>> profiler;
ActorCache::SharedLru actorCacheLru;
kj::Vector<kj::String> queuedNotifications;
// Notification messages to deliver to the next inspector client when it connects.
kj::HashSet<kj::String> warningOnceDescriptions;
// Set of warning log lines that should not be logged to the inspector again.
kj::HashSet<kj::String> errorOnceDescriptions;
// Set of error log lines that should not be logged again.
mutable uint lockAttemptGauge = 0;
// Instantaneous count of how many threads are trying to or have successfully obtained an
// AsyncLock on this isolate, used to implement getCurrentLoad().
mutable uint64_t lockSuccessCount = 0;
// Atomically incremented upon every successful lock. The ThreadProgressCounter in Impl::Lock
// registers a reference to `lockSuccessCounter` as the thread's progress counter during a lock
// attempt. This allows watchdogs to see evidence of forward progress in other threads, even if
// their own thread has blocked waiting for the lock for a long time.
class Lock {
// Wrapper around JsgWorkerIsolate::Lock and various RAII objects which help us report metrics,
// measure instantaneous load, avoid spurious watchdog kills, and defer context destruction.
//
// Always use this wrapper in code which may face lock contention (that's mostly everywhere).
public:
explicit Lock(const Worker::Isolate& isolate, Worker::LockType lockType)
: impl(*isolate.impl),
metrics([&isolate, &lockType]()
-> kj::Maybe<kj::Own<IsolateObserver::LockTiming>> {
KJ_SWITCH_ONEOF(lockType.origin) {
KJ_CASE_ONEOF(sync, Worker::Lock::TakeSynchronously) {
// TODO(perf): We could do some tracking here to discover overly harmful synchronous
// locks.
return isolate.getMetrics().tryCreateLockTiming(sync.getRequest());
}
KJ_CASE_ONEOF(async, AsyncLock*) {
KJ_REQUIRE(async->waiter->isolate.get() == &isolate,
"async lock was taken against a different isolate than the synchronous lock");
return kj::mv(async->lockTiming);
}
}
KJ_UNREACHABLE;
}()),
progressCounter(impl.lockSuccessCount),
oldCurrentApiIsolate(currentApiIsolate),
limitEnforcer(isolate.getLimitEnforcer()),
lock(isolate.apiIsolate->lock()) {
if (warnAboutIsolateLockScopeCount > 0) {
KJ_LOG(WARNING, "taking isolate lock at a bad time", kj::getStackTrace());
}
// Increment the success count to expose forward progress to all threads.
__atomic_add_fetch(&impl.lockSuccessCount, 1, __ATOMIC_RELAXED);
metrics.locked();
// We record the current lock so our GC prologue/epilogue callbacks can report GC time via
// Jaeger tracing.
KJ_DASSERT(impl.currentLock == nullptr, "Isolate lock taken recursively");
impl.currentLock = *this;
// Now's a good time to destroy any workers queued up for destruction.
auto workersToDestroy = impl.workerDestructionQueue.lockExclusive()->pop();
for (auto& workerImpl: workersToDestroy.asArrayPtr()) {
KJ_IF_MAYBE(c, workerImpl->context) {
disposeContext(kj::mv(*c));
}
workerImpl = nullptr;
}
currentApiIsolate = isolate.apiIsolate.get();
}
~Lock() noexcept(false) {
currentApiIsolate = oldCurrentApiIsolate;
#ifdef KJ_DEBUG
// We lack a KJ_DASSERT_NONNULL because it would have to look a lot like KJ_IF_MAYBE, thus
// we use a pragma around KJ_DEBUG here.
auto& implCurrentLock = KJ_ASSERT_NONNULL(impl.currentLock, "Isolate lock released twice");
KJ_ASSERT(&implCurrentLock == this, "Isolate lock released recursively");
#endif
if (shouldReportIsolateMetrics) {
// The isolate asked this lock to report the stats when it released. Let's do it.
limitEnforcer.reportMetrics(impl.metrics);
}
impl.currentLock = nullptr;
}
KJ_DISALLOW_COPY(Lock);
void setupContext(v8::Local<v8::Context> context) {
// Set WebAssembly.Module @@HasInstance
setWebAssemblyModuleHasInstance(*lock, context);
// The V8Inspector implements the `console` object.
KJ_IF_MAYBE(i, impl.inspector) {
i->get()->contextCreated(v8_inspector::V8ContextInfo(context, 1, toStringView("Worker")));
}
if (impl.inspector == nullptr) {
// When not running in preview mode, we replace the default V8 console.log(), etc. methods,
// to give the worker access to logged content.
auto global = context->Global();
auto consoleStr = jsg::v8StrIntern(lock->v8Isolate, "console");
auto console = jsg::check(global->Get(context, consoleStr));
auto setHandler = [&](const char* method, LogLevel level) {
auto methodStr = jsg::v8StrIntern(lock->v8Isolate, method);
auto f = lock->wrapSimpleFunction(context,
[level](jsg::Lock& js, const v8::FunctionCallbackInfo<v8::Value>& info) {
handleLog(js, level, info);
});
jsg::check(console.As<v8::Object>()->Set(context, methodStr, f));
};
setHandler("debug", LogLevel::DEBUG_);
setHandler("error", LogLevel::ERROR);
setHandler("info", LogLevel::INFO);
setHandler("log", LogLevel::LOG);
setHandler("warn", LogLevel::WARN);
}
}
void disposeContext(jsg::JsContext<api::ServiceWorkerGlobalScope> context) {
v8::HandleScope handleScope(lock->v8Isolate);
context->clear();
KJ_IF_MAYBE(i, impl.inspector) {
i->get()->contextDestroyed(context.getHandle(lock->v8Isolate));
}
{ auto drop = kj::mv(context); }
lock->v8Isolate->ContextDisposedNotification(false);
}
void gcPrologue() {
metrics.gcPrologue();
}
void gcEpilogue() {
metrics.gcEpilogue();
}
bool checkInWithLimitEnforcer(Worker::Isolate& isolate);
// Call limitEnforcer->exitJs(), and also schedule to call limitEnforcer->reportMetrics()
// later. Returns true if condemned. We take a mutable reference to it to make sure the caller
// believes it has exclusive access.
private:
const Impl& impl;
IsolateObserver::LockRecord metrics;
ThreadProgressCounter progressCounter;
bool shouldReportIsolateMetrics = false;
const ApiIsolate* oldCurrentApiIsolate;
const IsolateLimitEnforcer& limitEnforcer; // only so we can call getIsolateStats()
public:
kj::Own<jsg::Lock> lock;
};
mutable kj::Maybe<Lock&> currentLock;
// Protected by v8::Locker -- if v8::Locker::IsLocked(isolate) is true, then it is safe to access
// this variable.
static constexpr auto WORKER_DESTRUCTION_QUEUE_INITIAL_SIZE = 8;
static constexpr auto WORKER_DESTRUCTION_QUEUE_MAX_CAPACITY = 100;
const kj::MutexGuarded<BatchQueue<kj::Own<Worker::Impl>>> workerDestructionQueue {
WORKER_DESTRUCTION_QUEUE_INITIAL_SIZE,
WORKER_DESTRUCTION_QUEUE_MAX_CAPACITY
};
// Similar in spirit to the deferred destruction queue in jsg::IsolateBase. When a Worker is
// destroyed, it puts its Impl, which contains objects that need to be destroyed under the isolate
// lock, into this queue. Our own Isolate::Impl::Lock implementation then clears this queue the
// next time the isolate is locked, whether that be by a connection thread, or the Worker's own
// destructor if it owns the last `kj::Own<const Script>` reference.
//
// Fairly obviously, this member is protected by its own mutex, not the isolate lock.
//
// TODO(cleanup): The only reason this exists and we can't just rely on the isolate's regular
// deferred destruction queue to lazily destroy the various V8 objects in Worker::Impl is
// because our GlobalScope object needs to have a function called on it, and any attached
// inspector needs to be notified. JSG doesn't know about these things.
Impl(const ApiIsolate& apiIsolate, IsolateObserver& metrics,
IsolateLimitEnforcer& limitEnforcer, bool allowInspector)
: metrics(metrics),
actorCacheLru(limitEnforcer.getActorCacheLruOptions()) {
auto lock = apiIsolate.lock();
limitEnforcer.customizeIsolate(lock->v8Isolate);
if (allowInspector) {
// We just created our isolate, so we don't need to use Isolate::Impl::Lock.
KJ_ASSERT(!isMultiTenantProcess(), "inspector is not safe in multi-tenant processes");
inspector = v8_inspector::V8Inspector::create(lock->v8Isolate, &inspectorClient);
}
}
};
namespace {
class CpuProfilerDisposer final: public kj::Disposer {
public:
virtual void disposeImpl(void* pointer) const override {
reinterpret_cast<v8::CpuProfiler*>(pointer)->Dispose();
}
static const CpuProfilerDisposer instance;
};
const CpuProfilerDisposer CpuProfilerDisposer::instance {};
static constexpr kj::StringPtr PROFILE_NAME = "Default Profile"_kj;
static void setSamplingInterval(v8::CpuProfiler& profiler, int interval) {
profiler.SetSamplingInterval(interval);
}
static void startProfiling(v8::CpuProfiler& profiler, v8::Isolate* isolate) {
v8::HandleScope handleScope(isolate);
v8::CpuProfilingOptions options(
v8::kLeafNodeLineNumbers,
v8::CpuProfilingOptions::kNoSampleLimit
);
profiler.StartProfiling(jsg::v8Str(isolate, PROFILE_NAME.cStr()), kj::mv(options));
}
static void stopProfiling(v8::CpuProfiler& profiler,v8::Isolate* isolate,
cdp::Command::Builder& cmd) {
v8::HandleScope handleScope(isolate);
auto cpuProfile = profiler.StopProfiling(jsg::v8Str(isolate, PROFILE_NAME.cStr()));
if (cpuProfile == nullptr) return; // profiling never started
kj::Vector<const v8::CpuProfileNode*> allNodes;
kj::Vector<const v8::CpuProfileNode*> unvisited;
unvisited.add(cpuProfile->GetTopDownRoot());
while (!unvisited.empty()) {
auto next = unvisited.back();
allNodes.add(next);
unvisited.removeLast();
for (int i=0; i < next->GetChildrenCount(); i++) {
unvisited.add(next->GetChild(i));
}
}
auto res = cmd.getProfilerStop().initResult();
auto profile = res.initProfile();
profile.setStartTime(cpuProfile->GetStartTime());
profile.setEndTime(cpuProfile->GetEndTime());
auto nodes = profile.initNodes(allNodes.size());
for (int i=0; i < allNodes.size(); i++) {
auto nodeBuilder = nodes[i];
nodeBuilder.setId(allNodes[i]->GetNodeId());
auto callFrame = nodeBuilder.initCallFrame();
callFrame.setFunctionName(allNodes[i]->GetFunctionNameStr());
callFrame.setScriptId(kj::str(allNodes[i]->GetScriptId()));
callFrame.setUrl(allNodes[i]->GetScriptResourceNameStr());
// V8 locations are 1-based, but CDP locations are 0-based...
callFrame.setLineNumber(allNodes[i]->GetLineNumber() - 1);
callFrame.setColumnNumber(allNodes[i]->GetColumnNumber() - 1);
nodeBuilder.setHitCount(allNodes[i]->GetHitCount());
auto children = nodeBuilder.initChildren(allNodes[i]->GetChildrenCount());
for (int j=0; j < allNodes[i]->GetChildrenCount(); j++) {
children.set(j, allNodes[i]->GetChild(j)->GetNodeId());
}
auto hitLineCount = allNodes[i]->GetHitLineCount();
v8::CpuProfileNode::LineTick* lineBuffer =
(v8::CpuProfileNode::LineTick*)malloc(
hitLineCount * sizeof(v8::CpuProfileNode::LineTick));
KJ_DEFER(free(lineBuffer));
allNodes[i]->GetLineTicks(lineBuffer, hitLineCount);
auto positionTicks = nodeBuilder.initPositionTicks(hitLineCount);
for (int j=0; j < hitLineCount; j++) {
auto positionTick = positionTicks[j];
positionTick.setLine(lineBuffer[j].line);
positionTick.setTicks(lineBuffer[j].hit_count);
}
}
auto sampleCount = cpuProfile->GetSamplesCount();
auto samples = profile.initSamples(sampleCount);
auto timeDeltas = profile.initTimeDeltas(sampleCount);
auto lastTimestamp = cpuProfile->GetStartTime();
for (int i=0; i < sampleCount; i++) {
samples.set(i, cpuProfile->GetSample(i)->GetNodeId());
auto sampleTime = cpuProfile->GetSampleTimestamp(i);
timeDeltas.set(i, sampleTime - lastTimestamp);
lastTimestamp = sampleTime;
}
}
} // anonymous namespace
struct Worker::Script::Impl {
kj::OneOf<jsg::NonModuleScript, kj::Path> unboundScriptOrMainModule;
kj::Array<CompiledGlobal> globals;
kj::Maybe<jsg::JsContext<api::ServiceWorkerGlobalScope>> moduleContext;
kj::Maybe<kj::Exception> permanentException;
// If set, then any attempt to use this script shall throw this exception.
kj::Maybe<const jsg::ModuleRegistry&> getModuleRegistry() const {
return moduleRegistry;
}
kj::Maybe<jsg::ModuleRegistry&> getModuleRegistry() {
return moduleRegistry;
}
void setModuleRegistry(jsg::Lock& lock, kj::Own<jsg::ModuleRegistry> modules) {
struct DynamicImportResult {
jsg::Value value;
bool isException = false;
};
modules->setDynamicImportCallback([](v8::Isolate* isolate, auto handler) mutable {
if (IoContext::hasCurrent()) {
// If we are within the scope of a IoContext, then we are going to pop
// out of it to perform the actual module instantiation.
auto& ioContext = IoContext::current();
auto& worker = ioContext.getWorker();
return ioContext.awaitIo(
kj::evalLater([&worker, handler = kj::mv(handler)]() mutable {
return worker.takeAsyncLockWithoutRequest(nullptr)
.then([&worker, handler = kj::mv(handler)]
(Worker::AsyncLock asyncLock) mutable -> DynamicImportResult {
Worker::Lock lock(worker, asyncLock);
auto isolate = lock.getIsolate();
v8::HandleScope scope(isolate);
v8::Context::Scope contextScope(lock.getContext());
auto& workerIsolate = worker.getIsolate();
// We have to wrap the call to handler in a try catch here because
// we have to tunnel any jsg::JsExceptionThrowns back.
v8::TryCatch tryCatch(isolate);
kj::Maybe<kj::Exception> maybeLimitError;
try {
auto limitScope = workerIsolate.getLimitEnforcer()
.enterDynamicImportJs(lock, maybeLimitError);
return { .value = handler() };
} catch (jsg::JsExceptionThrown&) {
// Handled below...
} catch (kj::Exception& ex) {
kj::throwFatalException(kj::mv(ex));
}
KJ_ASSERT(tryCatch.HasCaught());
if (!tryCatch.CanContinue()) {
// There's nothing else we can do here but throw a generic fatal exception.
KJ_IF_MAYBE(limitError, maybeLimitError) {
kj::throwFatalException(kj::mv(*limitError));
} else {
kj::throwFatalException(JSG_KJ_EXCEPTION(FAILED, Error,
"Failed to load dynamic module."));
}
}
return { .value = jsg::Value(isolate, tryCatch.Exception()), .isException = true };
});
}).attach(kj::atomicAddRef(worker)), [isolate](auto result) {
if (result.isException) {
return jsg::rejectedPromise<jsg::Value>(isolate, kj::mv(result.value));
}
return jsg::resolvedPromise(isolate, kj::mv(result.value));
});
}
// If we got here, there is no current IoContext. We're going to perform the
// module resolution synchronously and we do not have to worry about blocking any
// i/o. We get here, for instance, when dynamic import is used at the top level of
// a script (which is weird, but allowed).
//
// We do not need to use limitEnforcer.enterDynamicImportJs() here because this should
// already be covered by the startup resource limiter.
return jsg::resolvedPromise(isolate, handler());
});
moduleRegistry = kj::mv(modules);
}
private:
kj::Maybe<kj::Own<jsg::ModuleRegistry>> moduleRegistry;
};
namespace {
kj::Maybe<kj::String> makeCompatJson(kj::ArrayPtr<kj::StringPtr> enableFlags) {
// Given an array of strings, return a valid serialized JSON string like:
// {"flags":["minimal_subrequests",...]}
//
// Return null if the array is empty.
if (enableFlags.size() == 0) {
return nullptr;
}
// Calculate the size of the string we're going to generate.
constexpr auto PREFIX = "{\"flags\":["_kj;
constexpr auto SUFFIX = "]}"_kj;
uint size = std::accumulate(enableFlags.begin(), enableFlags.end(),
// We need two quotes and one comma for each enable-flag past the first, plus a NUL char.
PREFIX.size() + SUFFIX.size() + 3 * enableFlags.size(),
[](uint z, kj::StringPtr s) { return z + s.size(); });
kj::Vector<char> json(size);
json.addAll(PREFIX);
bool first = true;
for (auto flag: enableFlags) {
if (first) {
first = false;
} else {
json.add(',');
}
json.add('"');
for (auto& c: flag.asArray()) {
// TODO(cleanup): Copied from simpleJsonStringCheck(). Hopefully this will
// go away forever soon.
KJ_REQUIRE(c != '\"');
KJ_REQUIRE(c != '\\');
KJ_REQUIRE(c >= 0x20);
}
json.addAll(flag);
json.add('"');
}
json.addAll(SUFFIX);
json.add('\0');
return kj::String(json.releaseAsArray());
}
} // namespace
Worker::Isolate::Isolate(kj::Own<ApiIsolate> apiIsolateParam,
kj::Own<IsolateObserver>&& metricsParam,
kj::StringPtr id,
kj::Own<IsolateLimitEnforcer> limitEnforcerParam,
bool allowInspector)
: id(kj::str(id)),
limitEnforcer(kj::mv(limitEnforcerParam)),
apiIsolate(kj::mv(apiIsolateParam)),
featureFlagsForFl(makeCompatJson(decompileCompatibilityFlagsForFl(apiIsolate->getFeatureFlags()))),
metrics(kj::mv(metricsParam)),
impl(kj::heap<Impl>(*apiIsolate, *metrics, *limitEnforcer, allowInspector)),
weakIsolateRef(kj::atomicRefcounted<WeakIsolateRef>(this)) {
// We just created our isolate, so we don't need to use Isolate::Impl::Lock (nor an async lock).
auto lock = apiIsolate->lock();
auto features = apiIsolate->getFeatureFlags();
lock->setCaptureThrowsAsRejections(features.getCaptureThrowsAsRejections());
lock->setCommonJsExportDefault(features.getExportCommonJsDefaultNamespace());
if (impl->inspector != nullptr || ::kj::_::Debug::shouldLog(::kj::LogSeverity::INFO)) {
lock->setLoggerCallback([this](jsg::Lock& js, kj::StringPtr message) {
if (impl->inspector != nullptr) {
// TODO(cleanup): The logger will only ever be called while the isolate lock is
// held. However, can we also safely assume there's already a v8::HandleScope
// on the stack? Once logMessage is updated to take a jsg::Lock reference we
// can remove the v8::HandleScope here.
v8::HandleScope scope(js.v8Isolate);
logMessage(js.v8Isolate->GetCurrentContext(),
static_cast<uint16_t>(cdp::LogType::WARNING), message);
}
KJ_LOG(INFO, "console warning", message);
});
}