diff --git a/NativeScript/runtime/EventLoop.h b/NativeScript/runtime/EventLoop.h index 3dd7598f..fc36a026 100644 --- a/NativeScript/runtime/EventLoop.h +++ b/NativeScript/runtime/EventLoop.h @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -14,6 +15,13 @@ #include "Common.h" #include "v8-platform.h" +// 1: JS timers keep exact fire-date order with foreign runloop timers at the +// cost of O(pending timers) per timer operation and no yielding between +// matured timers (see EventLoop's ordered lane). +#ifndef NS_EXACT_TIMER_ORDERING +#define NS_EXACT_TIMER_ORDERING 0 +#endif + namespace tns { /** @@ -45,14 +53,29 @@ class OrderedTaskSource { * * Ordered lane - work whose ordering is observable against other app-level * runloop work (spec'd macrotasks, JS timers). Every post is an anonymous - * "task due" token on ONE CFRunLoopTimer armed at the earliest pending due - * time (a due-now token gets a past fire date and fires on the next pass), so - * tokens stay in fire-date order with foreign NSTimers and each fire yields a - * full runloop pass - performed-block delivery would be sooner but a + * "task due" token; each token runs the earliest due item across the + * ordered entries and the OrderedTaskSource (Timers) - one due-ordered + * domain, and a leftover token is a cheap no-op. A due-now token still waits + * for the timer phase rather than riding a performed block: a * self-rescheduling chain of blocks starves the before-waiting phase (CA - * rendering, autorelease pool, the rejection drain). Each token runs the - * earliest due item across the ordered entries and the OrderedTaskSource - * (Timers) - one due-ordered domain, and a leftover token is a cheap no-op. + * rendering, autorelease pool, the rejection drain). Ordered tasks never + * nest, and every task is followed by an unhandled-rejection drain. + * + * By default every token rides ONE CFRunLoopTimer armed at the earliest + * pending token, and each fire consumes one token, so every matured token + * yields a full runloop pass to native work - setTimeout(fn, 0) is how apps + * yield to native. The timer is left alone while the earliest token is + * unchanged. Once it is re-armed for a matured token, CF clamps the fire + * date to now: the first matured token keeps its fire-date position against + * foreign NSTimers, later ones fall behind any that are already overdue. + * + * With NS_EXACT_TIMER_ORDERING each token owns a CFRunLoopTimer at its due + * time instead, never re-armed once that time has passed, so tokens keep + * fire-date order with foreign timers however many are overdue. In exchange + * every post, cancel and runloop pass costs O(pending timers) in CF, and + * matured tokens run back to back in one timer pass without yielding. A + * token that fires in a runloop spun from inside an ordered task waits for + * that task to return. * * Internal lane - work in its own ordering domain: v8 platform foreground * tasks (Atomics.waitAsync wakeups, GC tasks, streaming-compilation @@ -103,22 +126,21 @@ class EventLoop { bool PostOrderedDelayed(std::function fn, double delayMs); /** - * Posts a bare ordered token due at an absolute CLOCK_MONOTONIC time - * (NowMs() units) for an item the OrderedTaskSource keeps in its own - * bookkeeping (Timers). One token per item; the drain picks the earliest - * due item across the source and the ordered entries, so the token needn't - * name what it will run. Returns the key actually recorded (an overdue due - * time is clamped to now) - the value TryCancelOrderedToken must be given - * to recall this token. + * Posts a bare ordered token due at an absolute NowMs() time for an item + * the OrderedTaskSource keeps in its own bookkeeping (Timers). One token per + * item; the drain picks the earliest due item across the source and the + * ordered entries, so the token needn't name what it will run. Returns the + * key actually recorded (an overdue due time is clamped to now) - the value + * TryCancelOrderedToken must be given to recall this token. */ double PostOrderedToken(double dueTimeMs); /** - * Removes one not-yet-matured ordered token at this due time, un-arming its - * wakeup. Returns false when no such token is pending - it already matured, - * so its slot cannot be recalled; the caller must leave a tombstone for it - * instead. Tokens are anonymous and counted, - * so cancelling one token plus one item keeps slots 1:1 no matter which + * Removes one not-yet-matured ordered token at this due time, un-arming + * its wakeup. Returns false when no such token is pending - it already + * matured, so its slot cannot be recalled; the caller must leave a + * tombstone for it instead. Tokens are anonymous and counted, so + * cancelling one token plus one item keeps slots 1:1 no matter which * producer's token is physically removed. */ bool TryCancelOrderedToken(double dueTimeMs); @@ -173,7 +195,9 @@ class EventLoop { */ void RunOrderedTask(); - // CLOCK_MONOTONIC milliseconds - the clock every due time and token is on + // milliseconds on the clock every due time and token is on: CLOCK_MONOTONIC, + // or with NS_EXACT_TIMER_ORDERING CLOCK_UPTIME_RAW, which pauses during + // sleep like the CFRunLoopTimers those tokens are fixed on static double NowMs(); private: @@ -205,13 +229,20 @@ class EventLoop { static bool HasDueLocked(Lane& lane, double now); void SignalInternalLocked(); void ArmInternalTimerLocked(double now); - void ArmOrderedTimerLocked(double now); + void AddOrderedTokenLocked(double key, double now); void RunEntry(Entry& entry); void RunOneInternal(); + // reports what the ordered task just run left unhandled; mutex_ not held + void DrainRejectionsAfterOrderedTask(); static void InternalSourcePerform(void* info); static void InternalTimerFired(CFRunLoopTimerRef timer, void* info); +#if NS_EXACT_TIMER_ORDERING + static void OrderedTokenFired(CFRunLoopTimerRef timer, void* info); +#else + void ArmOrderedTimerLocked(double now); static void OrderedTimerFired(CFRunLoopTimerRef timer, void* info); +#endif v8::Isolate* isolate_; std::mutex mutex_; @@ -219,14 +250,26 @@ class EventLoop { Lane ordered_; // ordered-lane source with its own bookkeeping (Timers); home-thread only OrderedTaskSource* timerSource_ = nullptr; - // future-due ordered tokens awaiting orderedTimer_ +#if NS_EXACT_TIMER_ORDERING + // pending ordered tokens by key, each owning its CFRunLoopTimer (+1) + std::multimap pendingTokens_; + // set while an ordered task runs; tokens that fire meanwhile (from a + // runloop the task spins) are parked, still in pendingTokens_, and + // re-armed when it returns + bool runningOrderedTask_ = false; + std::vector> parkedTokens_; +#else + // pending ordered tokens, all riding orderedTimer_ std::multiset pendingTokens_; + CFRunLoopTimerRef orderedTimer_ = nullptr; + // the token key orderedTimer_ is armed for; NaN while disarmed or spent + double armedTokenKey_ = std::numeric_limits::quiet_NaN(); +#endif // tokens posted before the bind; flushed by BindToCurrentThread std::vector bufferedTokens_; CFRunLoopRef loop_ = nullptr; CFRunLoopSourceRef internalSource_ = nullptr; CFRunLoopTimerRef internalTimer_ = nullptr; - CFRunLoopTimerRef orderedTimer_ = nullptr; bool stopped_ = false; }; diff --git a/NativeScript/runtime/EventLoop.mm b/NativeScript/runtime/EventLoop.mm index 9ca381ca..c33c4216 100644 --- a/NativeScript/runtime/EventLoop.mm +++ b/NativeScript/runtime/EventLoop.mm @@ -1,6 +1,8 @@ #include "EventLoop.h" #include +#include +#include #include #include @@ -32,17 +34,56 @@ void RunGuarded(F&& body) { } } +#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 refs{0}; +}; + +const void* RetainOrderedTokenInfo(const void* info) { + auto token = const_cast(static_cast(info)); + token->refs.fetch_add(1, std::memory_order_relaxed); + return info; +} + +void ReleaseOrderedTokenInfo(const void* info) { + auto token = const_cast(static_cast(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 CLOCK_MONOTONIC due time to a CFRunLoopTimer fire date. The two +// 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) { @@ -68,10 +109,12 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { 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(); @@ -85,9 +128,8 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { auto tokens = std::move(bufferedTokens_); bufferedTokens_.clear(); for (double due : tokens) { - pendingTokens_.insert(due); + AddOrderedTokenLocked(due, now); } - ArmOrderedTimerLocked(now); } void EventLoop::Shutdown() { @@ -108,6 +150,18 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { 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) { @@ -120,11 +174,6 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { CFRelease(internalTimer_); internalTimer_ = nullptr; } - if (orderedTimer_ != nullptr) { - CFRunLoopTimerInvalidate(orderedTimer_); - CFRelease(orderedTimer_); - orderedTimer_ = nullptr; - } loop_ = nullptr; } @@ -169,19 +218,61 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { return dueTimeMs; } // every token rides the timer phase, even due-now ones (a past fire date - // fires on the next runloop pass). Performed blocks would deliver sooner, + // 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 - while a due timer still yields a full - // pass between fires. This also keeps due-now tokens in fire-date order - // with foreign NSTimers, like the per-timer CFRunLoopTimers this replaces. + // pool and the rejection drain. double key = std::max(dueTimeMs, now); - pendingTokens_.insert(key); - ArmOrderedTimerLocked(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::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 fn) { std::lock_guard lock(mutex_); if (stopped_) { @@ -249,8 +340,13 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { 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; } @@ -339,15 +435,6 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { due >= 0 ? FireDateFor(due, now) : CFAbsoluteTimeGetCurrent() + kNeverFireInterval); } -void EventLoop::ArmOrderedTimerLocked(double now) { - if (orderedTimer_ == nullptr) { - return; - } - CFRunLoopTimerSetNextFireDate( - orderedTimer_, !pendingTokens_.empty() ? FireDateFor(*pendingTokens_.begin(), now) - : CFAbsoluteTimeGetCurrent() + kNeverFireInterval); -} - void EventLoop::RunEntry(Entry& entry) { if (entry.bare) { // the fn does its own ceremony - it may lock a different isolate, or @@ -402,7 +489,10 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { RunEntry(*entry); return; } - RunGuarded([&] { RunEntry(*entry); }); + RunGuarded([&] { + RunEntry(*entry); + PromiseRejectionTracker::DrainIfPending(isolate_); + }); } void EventLoop::RunNestableV8Tasks() { @@ -483,6 +573,17 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { self->ArmInternalTimerLocked(now); } +void EventLoop::DrainRejectionsAfterOrderedTask() { + { + std::lock_guard 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(info); bool due = false; @@ -496,14 +597,85 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { 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 foreign timers and blocks due - // between two matured tokens interleave instead of waiting out a batch + // 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::quiet_NaN(); self->ArmOrderedTimerLocked(now); } if (due) { self->RunOrderedTask(); + self->DrainRejectionsAfterOrderedTask(); + } +} +#else +void EventLoop::OrderedTokenFired(CFRunLoopTimerRef timer, void* info) { + auto token = static_cast(info); + auto self = token->loop; + { + std::lock_guard 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 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 diff --git a/NativeScript/runtime/Messaging.cpp b/NativeScript/runtime/Messaging.cpp index 4163be09..2477e1d5 100644 --- a/NativeScript/runtime/Messaging.cpp +++ b/NativeScript/runtime/Messaging.cpp @@ -739,8 +739,10 @@ void NativeMessagePort::Drain() { break; } // Per message, not per drain: a handler's microtasks run before the next - // message arrives, which is what both browsers and Node observe. + // message arrives, which is what both browsers and Node observe - and a + // rejection it leaves unhandled is reported before the next handler runs. isolate->PerformMicrotaskCheckpoint(); + PromiseRejectionTracker::DrainIfPending(isolate); } if (reschedule && this->data_ != nullptr) { diff --git a/NativeScript/runtime/NativeScriptException.h b/NativeScript/runtime/NativeScriptException.h index 9928fcdb..a75502d6 100644 --- a/NativeScript/runtime/NativeScriptException.h +++ b/NativeScript/runtime/NativeScriptException.h @@ -128,6 +128,14 @@ class PromiseRejectionTracker { void OnReject(v8::Local promise, v8::Local reason); void OnHandlerAdded(v8::Local promise); void Drain(v8::Local context); + // Drains the isolate's tracker when it has work, taking the Locker and + // entering the main context. Runs after every event-loop task and port + // message, Node's model (rejections processed after each callback): a + // rejection left unhandled by one task is reported before the next task + // can attach a handler. HTML is looser - it queues the notification as a + // task that re-checks the promise - so this is the deterministic choice. + // Isolate's own thread only. + static void DrainIfPending(v8::Isolate* isolate); // Safe to call without holding the isolate lock: OnReject can run on any // thread that holds the v8::Locker (e.g. a background-thread rejection), so // the runloop observer polls this atomic instead of touching pending_. diff --git a/NativeScript/runtime/NativeScriptException.mm b/NativeScript/runtime/NativeScriptException.mm index ee29e0ac..5e5db012 100644 --- a/NativeScript/runtime/NativeScriptException.mm +++ b/NativeScript/runtime/NativeScriptException.mm @@ -598,6 +598,24 @@ static bool GiveWorkerOnErrorAChance(Isolate* isolate, Local context, L return !result.IsEmpty() && result->BooleanValue(isolate); } +void PromiseRejectionTracker::DrainIfPending(Isolate* isolate) { + auto cache = Caches::Get(isolate); + // HasPending is an atomic read: OnReject can run on any thread holding the + // v8::Locker, so pending_ itself must only be touched under the lock below. + // The event loop runs v8 tasks before Runtime::Init creates the context. + if (cache == nullptr || !cache->IsValid() || !cache->HasContext() || + cache->PromiseRejections == nullptr || !cache->PromiseRejections->HasPending()) { + return; + } + + v8::Locker locker(isolate); + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + Local context = cache->GetContext(); + Context::Scope context_scope(context); + cache->PromiseRejections->Drain(context); +} + void PromiseRejectionTracker::Drain(Local context) { if (draining_) { return; diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index 58da0942..e60a35ab 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -510,9 +510,11 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) { Local context = Context::New(isolate, nullptr, globalTemplate); context->Enter(); - // Drain tracked unhandled promise rejections once per runloop turn, just - // before the loop sleeps. The info pointer is the isolate; the callback - // re-validates liveness because the isolate may be torn down between turns. + // The event loop drains tracked unhandled promise rejections after each of + // its tasks; this observer catches rejections from JS entered any other way + // (native callbacks, NSTimer blocks) once per runloop turn, just before the + // loop sleeps. The info pointer is the isolate; the callback re-validates + // liveness because the isolate may be torn down between turns. CFRunLoopObserverContext observerContext = {0, isolate, nullptr, nullptr, nullptr}; rejectionObserver_ = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, /*repeats*/ true, @@ -808,20 +810,7 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) { if (!Runtime::IsAlive(isolate)) { return; } - auto cache = Caches::Get(isolate); - // HasPending is an atomic read: OnReject can run on any thread holding the - // v8::Locker, so pending_ itself must only be touched under the lock below. - if (!cache->IsValid() || cache->PromiseRejections == nullptr || - !cache->PromiseRejections->HasPending()) { - return; - } - - v8::Locker locker(isolate); - Isolate::Scope isolate_scope(isolate); - HandleScope handle_scope(isolate); - Local context = cache->GetContext(); - Context::Scope context_scope(context); - cache->PromiseRejections->Drain(context); + PromiseRejectionTracker::DrainIfPending(isolate); } bool Runtime::IsAlive(const Isolate* isolate) { diff --git a/NativeScript/runtime/Timers.cpp b/NativeScript/runtime/Timers.cpp index 353fd587..fee7f9e6 100644 --- a/NativeScript/runtime/Timers.cpp +++ b/NativeScript/runtime/Timers.cpp @@ -55,11 +55,8 @@ inline static double ToMaybePositiveValue(const v8::Local& v, return value; } -static double now_ms() { - struct timespec res; - clock_gettime(CLOCK_MONOTONIC, &res); - return 1000.0 * res.tv_sec + (double)res.tv_nsec / 1e6; -} +// due times become ordered-token keys, so they share the EventLoop's clock +static double now_ms() { return tns::EventLoop::NowMs(); } namespace tns { diff --git a/TestRunner/app/tests/CreateRequireTests.js b/TestRunner/app/tests/CreateRequireTests.js index 68d41845..91e70412 100644 --- a/TestRunner/app/tests/CreateRequireTests.js +++ b/TestRunner/app/tests/CreateRequireTests.js @@ -256,13 +256,12 @@ describe("createRequire", function () { }, 0); }); - // Entered from a main-queue block, not from a timer callback: JS - // timers ride ONE shared CFRunLoopTimer, and a CFRunLoopTimer does - // not re-enter, so a require started from inside that timer's own - // callback can never let another timer fire no matter how the loop - // is pumped. From a runloop block the timer is free to fire, which - // is what makes this a test of pumpRunLoop rather than of - // re-entrancy. + // Entered from a main-queue block, not from a timer callback: + // ordered tasks (JS timers, macrotasks) never nest, so a require + // started from inside a timer callback can never let another + // timer fire no matter how the loop is pumped. From a runloop + // block the timer is free to fire, which is what makes this a + // test of pumpRunLoop rather than of re-entrancy. function onFreshTask(fn) { NSOperationQueue.mainQueue.addOperationWithBlock(fn); } diff --git a/TestRunner/app/tests/EventLoopTests.js b/TestRunner/app/tests/EventLoopTests.js index cb5ec242..49aa9d78 100644 --- a/TestRunner/app/tests/EventLoopTests.js +++ b/TestRunner/app/tests/EventLoopTests.js @@ -165,6 +165,137 @@ describe("event loop ordered macrotasks", function () { done(); }, 30); }); + + // CF clamps a past fire date to now, so re-arming the lane for a matured + // token lands it behind every overdue foreign timer. Each case makes ns20 + // and nstimer25 overdue together and disturbs the ordered lane in a + // different way. + function expectDueOrderAfterBusyWait(order, expected, afterBusyWait, done) { + __ns__setTimeout(() => order.push("ns20"), 20); + foreignSetTimeout(() => order.push("nstimer25"), 25); + __ns__setTimeout(() => order.push("ns30"), 30); + const start = Date.now(); + while (Date.now() - start < 45) { } + if (afterBusyWait) { + afterBusyWait(); + } + foreignSetTimeout(() => { + expect(order).toEqual(expected); + done(); + }, 30); + } + + // Two matured runtime timers ahead of a foreign one: the default build + // yields a runloop pass between matured timers (setTimeout(fn, 0) is how + // apps yield to native), so the second is re-armed after the foreign + // timer. Only a build with NS_EXACT_TIMER_ORDERING=1 passes these. + xit("keeps due-time order with foreign timers behind an earlier overdue timer", function (done) { + const order = []; + __ns__setTimeout(() => order.push("ns10"), 10); + expectDueOrderAfterBusyWait(order, ["ns10", "ns20", "nstimer25", "ns30"], null, done); + }); + + xit("keeps due-time order with foreign timers behind an earlier macrotask", function (done) { + const order = []; + __ns__queueMacrotask(() => order.push("macro")); + expectDueOrderAfterBusyWait(order, ["macro", "ns20", "nstimer25", "ns30"], null, done); + }); + + it("keeps due-time order with foreign timers when a timer is scheduled after they matured", function (done) { + const order = []; + let late; + expectDueOrderAfterBusyWait(order, ["ns20", "nstimer25", "ns30"], () => { + late = __ns__setTimeout(() => order.push("late"), 1000); + }, () => { + __ns__clearTimeout(late); + done(); + }); + }); + + // A runloop spun from inside a timer callback (a pumped require, app code) + // must not run other ordered tasks nested inside it. + it("does not run ordered tasks inside a runloop spun from a timer callback", function (done) { + __ns__setTimeout(() => { + const order = []; + __ns__setTimeout(() => order.push("timer"), 0); + __ns__queueMacrotask(() => order.push("macro")); + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, false); + expect(order).toEqual([]); + __ns__setTimeout(() => { + expect(order).toEqual(["timer", "macro"]); + done(); + }, 0); + }, 0); + }); + + it("keeps due-time order with foreign timers when a timer is cleared after they matured", function (done) { + const order = []; + const unrelated = __ns__setTimeout(() => order.push("cleared"), 1000); + expectDueOrderAfterBusyWait(order, ["ns20", "nstimer25", "ns30"], () => { + __ns__clearTimeout(unrelated); + }, done); + }); +}); + +// A rejection a task leaves unhandled is reported before the next task runs, +// Node's model (rejections processed after each callback), even when both +// tasks were due in the same runloop pass or arrive in one port drain. A +// later task attaching a handler then gets rejectionhandled, not silence. +describe("event loop unhandled rejections", function () { + // schedule(reject, handle) queues two tasks and may return a cleanup + function expectReportedBeforeNextTask(schedule) { + return raisesGlobalErrors(function (done) { + const events = []; + const onUnhandled = (e) => { + e.preventDefault(); + events.push("unhandled"); + }; + const onHandled = () => events.push("handled"); + global.addEventListener("unhandledrejection", onUnhandled); + global.addEventListener("rejectionhandled", onHandled); + let rejected; + const cleanup = schedule(() => { + rejected = Promise.reject(new Error("reported before the next task")); + events.push("reject"); + }, () => { + rejected.catch(() => { }); + events.push("handle"); + }); + foreignSetTimeout(() => { + global.removeEventListener("unhandledrejection", onUnhandled); + global.removeEventListener("rejectionhandled", onHandled); + if (cleanup) { + cleanup(); + } + expect(events).toEqual(["reject", "unhandled", "handle", "handled"]); + done(); + }, 100); + }); + } + + it("reports before a timer due in the same pass attaches a handler", + expectReportedBeforeNextTask((reject, handle) => { + __ns__setTimeout(reject, 0); + __ns__setTimeout(handle, 0); + })); + + it("reports before a macrotask due in the same pass attaches a handler", + expectReportedBeforeNextTask((reject, handle) => { + __ns__setTimeout(reject, 0); + __ns__queueMacrotask(handle); + })); + + it("reports before the next message on the same port attaches a handler", + expectReportedBeforeNextTask((reject, handle) => { + const channel = new MessageChannel(); + channel.port2.onmessage = (event) => (event.data === "reject" ? reject : handle)(); + channel.port1.postMessage("reject"); + channel.port1.postMessage("handle"); + return () => { + channel.port1.close(); + channel.port2.close(); + }; + })); }); // A self-rescheduling immediate timer must not starve the rest of the