Repository navigation
Expand file tree
/
Copy pathEventLoop.mm
More file actions
776 lines (717 loc) · 24.3 KB
/
Copy pathEventLoop.mm
File metadata and controls
776 lines (717 loc) · 24.3 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
#include "EventLoop.h"
#include "ns/JsError.h"
#include <pthread.h>
#include <unistd.h>
#include <algorithm>
#include <atomic>
#include <cmath>
#include <ctime>
#include <limits>
#include "Caches.h"
#include "Helpers.h"
#include "NativeScriptException.h"
using namespace v8;
using nativescript::common::Deadline;
using nativescript::common::PumpMode;
using nativescript::common::PumpResult;
namespace {
// far enough that an "unarmed" repeating timer never fires; re-armed with
// CFRunLoopTimerSetNextFireDate when a real deadline exists
const CFTimeInterval kNeverFireInterval = 1.0e10;
// runs one unit of non-bare work without letting a C++ exception escape into
// a CFRunLoop callback frame. Deliberately no catch(...): on Darwin it would
// also swallow NSExceptions, and bare entries (which may @throw on purpose)
// never come through here anyway.
template <typename F>
void RunGuarded(F&& body) {
try {
body();
} catch (tns::NativeScriptException& ex) {
Log(@"NativeScript: uncaught NativeScriptException in event loop task: %s",
ex.getMessage().c_str());
} catch (nativescript::common::JsError& ex) {
Log(@"NativeScript: uncaught error in event loop task: %s", ex.what());
} catch (nativescript::common::Terminated&) {
// the isolate is terminating; there is nothing left to report to
} catch (std::exception& ex) {
Log(@"NativeScript: c++ exception in event loop task: %s", ex.what());
}
}
#if NS_EXACT_TIMER_ORDERING
// Context of one ordered token's CFRunLoopTimer. Refcounted through the
// context's retain/release so CF holds a reference across each callout:
// CFRunLoopTimerInvalidate releases the context immediately, and a token may
// be cancelled from another thread while its callout is being dispatched.
struct OrderedTokenInfo {
OrderedTokenInfo(tns::EventLoop* loop, double key) : loop(loop), key(key) {}
tns::EventLoop* const loop;
const double key;
std::atomic<int> refs{0};
};
const void* RetainOrderedTokenInfo(const void* info) {
auto token = const_cast<OrderedTokenInfo*>(static_cast<const OrderedTokenInfo*>(info));
token->refs.fetch_add(1, std::memory_order_relaxed);
return info;
}
void ReleaseOrderedTokenInfo(const void* info) {
auto token = const_cast<OrderedTokenInfo*>(static_cast<const OrderedTokenInfo*>(info));
if (token->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) {
delete token;
}
}
void DisposeTimer(CFRunLoopTimerRef timer) {
CFRunLoopTimerInvalidate(timer);
CFRelease(timer);
}
#endif
} // namespace
namespace tns {
double EventLoop::NowMs() {
struct timespec res;
#if NS_EXACT_TIMER_ORDERING
// mach_absolute_time's clock, the one CFRunLoopTimers fire on: a token's
// timer is armed once, so a key on a clock that keeps counting through
// sleep (CLOCK_MONOTONIC) would disagree with its timer after a wake and
// hand newer timers an older timer's far-off token
clock_gettime(CLOCK_UPTIME_RAW, &res);
#else
clock_gettime(CLOCK_MONOTONIC, &res);
#endif
return 1000.0 * res.tv_sec + (double)res.tv_nsec / 1e6;
}
// converts a NowMs() due time to a CFRunLoopTimer fire date. The two
// clocks can drift (CFAbsoluteTime is wall-based), so consumers must treat a
// fire as "check what is due now", never as proof a specific item is due.
static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) {
return CFAbsoluteTimeGetCurrent() + std::max(0.0, dueMs - nowMs) / 1000.0;
}
void EventLoop::BindToCurrentThread() {
std::lock_guard<std::mutex> lock(mutex_);
if (loop_ != nullptr || stopped_) {
return;
}
loop_ = CFRunLoopGetCurrent();
uint64_t threadId = 0;
pthread_threadid_np(nullptr, &threadId);
homeThreadId_.store(threadId, std::memory_order_release);
CFRunLoopSourceContext sourceContext = {
0, this, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr, &EventLoop::InternalSourcePerform};
internalSource_ = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &sourceContext);
CFRunLoopAddSource(loop_, internalSource_, kCFRunLoopCommonModes);
CFRunLoopTimerContext timerContext = {0, this, nullptr, nullptr, nullptr};
internalTimer_ =
CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + kNeverFireInterval,
kNeverFireInterval, 0, 0, &EventLoop::InternalTimerFired, &timerContext);
CFRunLoopAddTimer(loop_, internalTimer_, kCFRunLoopCommonModes);
#if !NS_EXACT_TIMER_ORDERING
orderedTimer_ =
CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + kNeverFireInterval,
kNeverFireInterval, 0, 0, &EventLoop::OrderedTimerFired, &timerContext);
CFRunLoopAddTimer(loop_, orderedTimer_, kCFRunLoopCommonModes);
#endif
// flush work buffered before the home thread was known
auto now = NowMs();
if (HasDueLocked(internal_, now)) {
SignalInternalLocked();
}
ArmInternalTimerLocked(now);
// replay buffered tokens under their original keys - PostOrderedToken
// already returned those to producers as the recall handle, so the flush
// must not re-clamp them (a past key simply fires on the next pass)
auto tokens = std::move(bufferedTokens_);
bufferedTokens_.clear();
for (double due : tokens) {
AddOrderedTokenLocked(due, now);
}
}
void EventLoop::Shutdown() {
// The dropped entries are moved out and destroyed only after the lock is
// released: an entry's destructor may post back into this very loop (a
// dropped message carrying a transferred port sentinels the port's sibling,
// and that sibling may live here), and mutex_ is not recursive.
std::deque<Entry> droppedInternal;
std::multimap<double, Entry> droppedInternalDelayed;
std::deque<Entry> droppedOrdered;
std::multimap<double, Entry> droppedOrderedDelayed;
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return;
}
stopped_ = true;
droppedInternal.swap(internal_.immediate);
droppedInternalDelayed.swap(internal_.delayed);
droppedOrdered.swap(ordered_.immediate);
droppedOrderedDelayed.swap(ordered_.delayed);
#if NS_EXACT_TIMER_ORDERING
for (auto& token : pendingTokens_) {
DisposeTimer(token.second);
}
parkedTokens_.clear();
#else
if (orderedTimer_ != nullptr) {
CFRunLoopTimerInvalidate(orderedTimer_);
CFRelease(orderedTimer_);
orderedTimer_ = nullptr;
}
#endif
pendingTokens_.clear();
bufferedTokens_.clear();
if (internalSource_ != nullptr) {
CFRunLoopSourceInvalidate(internalSource_);
CFRelease(internalSource_);
internalSource_ = nullptr;
}
if (internalTimer_ != nullptr) {
CFRunLoopTimerInvalidate(internalTimer_);
CFRelease(internalTimer_);
internalTimer_ = nullptr;
}
loop_ = nullptr;
}
EventLoop::~EventLoop() {
// Normally a no-op: ~Runtime already shut the loop down on the home thread.
// A transient shared_ptr taken on a foreign posting thread can be the last
// reference only after that shutdown, when this is just member cleanup.
Shutdown();
}
void EventLoop::PostInternalLocked(Entry entry, double delayMs) {
auto now = NowMs();
if (delayMs <= 0) {
entry.time = now;
internal_.immediate.push_back(std::move(entry));
SignalInternalLocked();
} else {
auto due = now + delayMs;
entry.time = due;
internal_.delayed.emplace(due, std::move(entry));
ArmInternalTimerLocked(now);
}
}
void EventLoop::PostOrderedLocked(Entry entry, double delayMs) {
auto now = NowMs();
if (delayMs <= 0) {
entry.time = now;
ordered_.immediate.push_back(std::move(entry));
PostOrderedTokenLocked(now, now);
} else {
auto due = now + delayMs;
entry.time = due;
ordered_.delayed.emplace(due, std::move(entry));
PostOrderedTokenLocked(due, now);
}
}
double EventLoop::PostOrderedTokenLocked(double dueTimeMs, double now) {
if (loop_ == nullptr) {
bufferedTokens_.push_back(dueTimeMs);
return dueTimeMs;
}
// every token rides the timer phase, even due-now ones (a past fire date
// fires on the next timer pass). Performed blocks would deliver sooner,
// but a self-rescheduling chain of them never lets the loop reach its
// before-waiting phase - starving CA rendering commits, the autorelease
// pool and the rejection drain.
double key = std::max(dueTimeMs, now);
AddOrderedTokenLocked(key, now);
CFRunLoopWakeUp(loop_);
return key;
}
#if !NS_EXACT_TIMER_ORDERING
void EventLoop::AddOrderedTokenLocked(double key, double now) {
pendingTokens_.insert(key);
ArmOrderedTimerLocked(now);
}
void EventLoop::ArmOrderedTimerLocked(double now) {
if (orderedTimer_ == nullptr) {
return;
}
// Left alone while the earliest token is unchanged: re-arming for a matured
// token clamps its fire date to now (CF does as well), which would move it
// behind every overdue foreign timer.
if (pendingTokens_.empty()) {
if (std::isnan(armedTokenKey_)) {
return;
}
armedTokenKey_ = std::numeric_limits<double>::quiet_NaN();
CFRunLoopTimerSetNextFireDate(orderedTimer_, CFAbsoluteTimeGetCurrent() + kNeverFireInterval);
return;
}
double head = *pendingTokens_.begin();
if (head == armedTokenKey_) {
return;
}
armedTokenKey_ = head;
CFRunLoopTimerSetNextFireDate(orderedTimer_, FireDateFor(head, now));
}
#else
void EventLoop::AddOrderedTokenLocked(double key, double now) {
CFRunLoopTimerContext context = {0, new OrderedTokenInfo(this, key), &RetainOrderedTokenInfo,
&ReleaseOrderedTokenInfo, nullptr};
// Not re-armed once it is due, except when parked by a nested runloop (see
// OrderedTokenFired): CF clamps a past fire date to now, which would move
// the token behind overdue foreign timers. Repeating with an unreachable
// interval only so its own callout can re-arm it - CF invalidates a
// one-shot timer after its callout.
CFRunLoopTimerRef timer =
CFRunLoopTimerCreate(kCFAllocatorDefault, FireDateFor(key, now), kNeverFireInterval, 0, 0,
&EventLoop::OrderedTokenFired, &context);
CFRunLoopAddTimer(loop_, timer, kCFRunLoopCommonModes);
pendingTokens_.emplace(key, timer);
}
#endif
bool EventLoop::PostInternal(std::function<void()> fn) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return false;
}
PostInternalLocked(Entry{nullptr, std::move(fn), true, false, 0}, 0);
return true;
}
bool EventLoop::PostInternalDelayed(std::function<void()> fn, double delayMs) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return false;
}
PostInternalLocked(Entry{nullptr, std::move(fn), true, false, 0}, delayMs);
return true;
}
bool EventLoop::PostInternalBare(std::function<void()> fn) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return false;
}
PostInternalLocked(Entry{nullptr, std::move(fn), true, true, 0}, 0);
return true;
}
bool EventLoop::PostOrdered(std::function<void()> fn) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return false;
}
PostOrderedLocked(Entry{nullptr, std::move(fn), true, false, 0}, 0);
return true;
}
bool EventLoop::PostOrderedDelayed(std::function<void()> fn, double delayMs) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return false;
}
PostOrderedLocked(Entry{nullptr, std::move(fn), true, false, 0}, delayMs);
return true;
}
double EventLoop::PostOrderedToken(double dueTimeMs) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return dueTimeMs;
}
return PostOrderedTokenLocked(dueTimeMs, NowMs());
}
bool EventLoop::TryCancelOrderedToken(double dueTimeMs) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return false;
}
auto bufferedIt = std::find(bufferedTokens_.begin(), bufferedTokens_.end(), dueTimeMs);
if (bufferedIt != bufferedTokens_.end()) {
bufferedTokens_.erase(bufferedIt);
return true;
}
auto pendingIt = pendingTokens_.find(dueTimeMs);
if (pendingIt == pendingTokens_.end()) {
return false;
}
#if NS_EXACT_TIMER_ORDERING
DisposeTimer(pendingIt->second);
pendingTokens_.erase(pendingIt);
#else
pendingTokens_.erase(pendingIt);
ArmOrderedTimerLocked(NowMs());
#endif
return true;
}
void EventLoop::SetTimerSource(OrderedTaskSource* source) {
// home thread only, like every consumer of timerSource_
timerSource_ = source;
}
bool EventLoop::PostV8Task(std::unique_ptr<Task> task, bool nestable, double delaySeconds) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return false;
}
PostInternalLocked(Entry{std::move(task), nullptr, nestable, false, 0}, delaySeconds * 1000.0);
return true;
}
bool EventLoop::IsStopped() {
std::lock_guard<std::mutex> lock(mutex_);
return stopped_;
}
std::unique_ptr<EventLoop::Entry> EventLoop::TakeDueLocked(Lane& lane, bool nestableOnly,
bool v8Only, double now) {
auto matches = [&](const Entry& e) {
return (!nestableOnly || e.nestable) && (!v8Only || e.task != nullptr);
};
auto imIt = lane.immediate.begin();
while (imIt != lane.immediate.end() && !matches(*imIt)) {
++imIt;
}
auto delIt = lane.delayed.begin();
while (delIt != lane.delayed.end() && !matches(delIt->second)) {
++delIt;
}
bool hasImmediate = imIt != lane.immediate.end();
bool hasDelayed = delIt != lane.delayed.end() && delIt->first <= now;
if (hasImmediate && (!hasDelayed || imIt->time <= delIt->first)) {
auto entry = std::make_unique<Entry>(std::move(*imIt));
lane.immediate.erase(imIt);
return entry;
}
if (hasDelayed) {
auto entry = std::make_unique<Entry>(std::move(delIt->second));
lane.delayed.erase(delIt);
return entry;
}
return nullptr;
}
double EventLoop::PeekDueLocked(Lane& lane, double now) {
// immediate entries are enqueued with monotonically increasing times, so
// the front is the earliest
double due = lane.immediate.empty() ? -1 : lane.immediate.front().time;
if (!lane.delayed.empty() && lane.delayed.begin()->first <= now &&
(due < 0 || lane.delayed.begin()->first < due)) {
due = lane.delayed.begin()->first;
}
return due;
}
bool EventLoop::HasDueLocked(Lane& lane, double now) {
return !lane.immediate.empty() || (!lane.delayed.empty() && lane.delayed.begin()->first <= now);
}
void EventLoop::SignalInternalLocked() {
if (internalSource_ != nullptr) {
CFRunLoopSourceSignal(internalSource_);
CFRunLoopWakeUp(loop_);
}
}
void EventLoop::ArmInternalTimerLocked(double now) {
if (internalTimer_ == nullptr) {
return;
}
// earliest not-yet-due delayed entry; already-due ones are the signal's job
double due = -1;
for (auto& pair : internal_.delayed) {
if (pair.first > now) {
due = pair.first;
break;
}
}
CFRunLoopTimerSetNextFireDate(
internalTimer_,
due >= 0 ? FireDateFor(due, now) : CFAbsoluteTimeGetCurrent() + kNeverFireInterval);
}
void EventLoop::RunEntry(Entry& entry) {
if (entry.bare) {
// the fn does its own ceremony - it may lock a different isolate, or
// deliberately @throw with no V8 scopes on the stack
entry.fn();
return;
}
v8::Locker locker(isolate_);
v8::Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handle_scope(isolate_);
auto run = [&]() {
if (entry.task != nullptr) {
entry.task->Run();
} else {
entry.fn();
}
// work may enqueue microtasks without entering JS (e.g. resolving the
// Atomics.waitAsync promise), which never reaches kAuto's depth-0 drain
isolate_->PerformMicrotaskCheckpoint();
};
auto cache = Caches::Get(isolate_);
if (cache != nullptr && !cache->IsTearingDown() && cache->HasContext()) {
Context::Scope context_scope(cache->GetContext());
run();
} else {
// v8 can post tasks before Runtime::Init creates the context
run();
}
}
void EventLoop::RunOneInternal() {
std::unique_ptr<Entry> entry;
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return;
}
auto now = NowMs();
entry = TakeDueLocked(internal_, false, false, now);
// re-signal BEFORE running: one entry per runloop pass keeps the lane
// fair with other runloop work, and a bare entry may @throw and never
// return control here
if (entry != nullptr && HasDueLocked(internal_, now)) {
SignalInternalLocked();
}
}
if (entry == nullptr) {
// leftover signal: the work it announced ran early from a nested drain
return;
}
if (entry->bare) {
RunEntry(*entry);
return;
}
RunGuarded([&] {
RunEntry(*entry);
PromiseRejectionTracker::DrainIfPending(isolate_);
});
}
void EventLoop::RunNestableV8Tasks() {
// bounded to the entries present at call time so a task that reposts can't
// wedge the inspector pause loop that called us
size_t budget;
{
std::lock_guard<std::mutex> lock(mutex_);
budget = internal_.immediate.size() + internal_.delayed.size();
}
while (budget-- > 0) {
std::unique_ptr<Entry> entry;
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return;
}
entry = TakeDueLocked(internal_, true, true, NowMs());
}
if (entry == nullptr) {
return;
}
// the pause loops call this from inside v8 inspector frames - a C++
// exception must not unwind through them
RunGuarded([&] { RunEntry(*entry); });
}
}
PumpResult EventLoop::PumpUntil(const Deadline& deadline, const std::function<bool()>& settled,
PumpMode mode, const std::function<void(int waitMs)>& idle) {
// Short, so a completion posted during a wait is picked up promptly. The
// kV8Tasks wait must stay within the 10 ms Loop.h allows.
constexpr int kNestableOnlyIdleMs = 2;
constexpr useconds_t kV8TasksIdleMicros = 1000;
constexpr CFTimeInterval kPlatformSliceSeconds = 0.01;
for (;;) {
if (TerminationRequested() || isolate_->IsExecutionTerminating() || IsStopped()) {
return PumpResult::kTerminated;
}
if (settled()) {
return PumpResult::kSettled;
}
if (nativescript::common::DeadlinePassed(deadline)) {
return PumpResult::kDeadline;
}
switch (mode) {
case PumpMode::kNestableOnly: {
{
v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate_);
RunNestableV8Tasks();
}
if (settled()) {
// back to the head, where termination outranks this settlement
continue;
}
if (idle != nullptr) {
idle(kNestableOnlyIdleMs);
} else {
usleep(kNestableOnlyIdleMs * 1000);
}
break;
}
case PumpMode::kV8Tasks: {
RunNestableV8Tasks();
isolate_->PerformMicrotaskCheckpoint();
if (settled()) {
continue;
}
usleep(kV8TasksIdleMicros);
break;
}
case PumpMode::kPlatformWork: {
RunNestableV8Tasks();
isolate_->PerformMicrotaskCheckpoint();
if (settled()) {
continue;
}
@autoreleasepool {
CFRunLoopRunInMode(kCFRunLoopDefaultMode, kPlatformSliceSeconds, true);
}
isolate_->PerformMicrotaskCheckpoint();
break;
}
}
}
}
void EventLoop::RequestTermination() {
terminationRequested_.store(true, std::memory_order_relaxed);
}
bool EventLoop::TerminationRequested() const {
return terminationRequested_.load(std::memory_order_relaxed);
}
bool EventLoop::IsOnHomeThread() const {
const uint64_t home = homeThreadId_.load(std::memory_order_acquire);
if (home == 0) {
return false;
}
uint64_t self = 0;
pthread_threadid_np(nullptr, &self);
return self == home;
}
void EventLoop::RunOrderedTask() {
// one anonymous token = one due slot across the whole ordered domain: pick
// the earliest due item among the ordered entries and the timer source,
// whichever it is. Timers and entries only ever run on this thread, so the
// peeked winner can't be taken by anyone else before we re-lock (a
// concurrent post can only add later work).
auto now = NowMs();
double entryDue;
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return;
}
entryDue = PeekDueLocked(ordered_, now);
}
if (timerSource_ != nullptr && timerSource_->RunIfEarliest(now, entryDue)) {
return;
}
if (entryDue < 0) {
// leftover token: nothing in the domain is due yet
return;
}
std::unique_ptr<Entry> entry;
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return;
}
entry = TakeDueLocked(ordered_, false, false, NowMs());
}
if (entry != nullptr) {
RunGuarded([&] { RunEntry(*entry); });
}
}
void EventLoop::InternalSourcePerform(void* info) {
static_cast<EventLoop*>(info)->RunOneInternal();
}
void EventLoop::InternalTimerFired(CFRunLoopTimerRef timer, void* info) {
auto self = static_cast<EventLoop*>(info);
std::lock_guard<std::mutex> lock(self->mutex_);
if (self->stopped_) {
return;
}
auto now = NowMs();
if (HasDueLocked(self->internal_, now)) {
self->SignalInternalLocked();
}
self->ArmInternalTimerLocked(now);
}
void EventLoop::DrainRejectionsAfterOrderedTask() {
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return;
}
}
RunGuarded([&] { PromiseRejectionTracker::DrainIfPending(isolate_); });
}
#if !NS_EXACT_TIMER_ORDERING
void EventLoop::OrderedTimerFired(CFRunLoopTimerRef timer, void* info) {
auto self = static_cast<EventLoop*>(info);
bool due = false;
{
std::lock_guard<std::mutex> lock(self->mutex_);
if (self->stopped_) {
return;
}
auto now = NowMs();
if (!self->pendingTokens_.empty() && *self->pendingTokens_.begin() <= now) {
self->pendingTokens_.erase(self->pendingTokens_.begin());
due = true;
}
// One matured token per fire: re-arming with an already-past due time
// fires again on the next runloop pass, so native work runs between two
// matured tokens instead of waiting out a batch. This fire spent the
// arming (CF moves a fired timer to its unreachable interval unless its
// callout re-arms it), so the re-arm is unconditional.
self->armedTokenKey_ = std::numeric_limits<double>::quiet_NaN();
self->ArmOrderedTimerLocked(now);
}
if (due) {
self->RunOrderedTask();
self->DrainRejectionsAfterOrderedTask();
}
}
#else
void EventLoop::OrderedTokenFired(CFRunLoopTimerRef timer, void* info) {
auto token = static_cast<OrderedTokenInfo*>(info);
auto self = token->loop;
{
std::lock_guard<std::mutex> lock(self->mutex_);
if (self->stopped_) {
return;
}
auto now = NowMs();
if (token->key > now) {
// fired ahead of its NowMs() due time; still in the future, so CF
// honors the new date
CFRunLoopTimerSetNextFireDate(timer, FireDateFor(token->key, now));
return;
}
auto range = self->pendingTokens_.equal_range(token->key);
auto it = std::find_if(range.first, range.second,
[timer](const auto& entry) { return entry.second == timer; });
if (it == range.second) {
// recalled by TryCancelOrderedToken while this fire was being dispatched
return;
}
if (self->runningOrderedTask_) {
// a runloop spun from inside an ordered task (a pumped require, app
// code): ordered tasks never nest, so the token waits for that task
CFRunLoopTimerSetNextFireDate(timer, CFAbsoluteTimeGetCurrent() + kNeverFireInterval);
self->parkedTokens_.emplace_back(token->key, timer);
return;
}
self->pendingTokens_.erase(it);
DisposeTimer(timer);
self->runningOrderedTask_ = true;
}
struct UnparkOnExit {
EventLoop* self;
~UnparkOnExit() {
std::lock_guard<std::mutex> lock(self->mutex_);
self->runningOrderedTask_ = false;
auto parked = std::move(self->parkedTokens_);
self->parkedTokens_.clear();
if (self->stopped_) {
return;
}
auto now = NowMs();
for (auto& [key, timer] : parked) {
// only timers still owned by pendingTokens_; a parked token may have
// been cancelled (and its timer freed) meanwhile
auto range = self->pendingTokens_.equal_range(key);
for (auto it = range.first; it != range.second; ++it) {
if (it->second == timer) {
CFRunLoopTimerSetNextFireDate(timer, FireDateFor(key, now));
break;
}
}
}
}
} unpark{self};
// Overdue tokens fire back to back within one CF timer pass, so the
// runloop's own pool would span the whole batch; each task gets its own.
@autoreleasepool {
self->RunOrderedTask();
self->DrainRejectionsAfterOrderedTask();
}
}
#endif
} // namespace tns