Skip to content

Commit

Permalink
perf(ext/web): optimize timer cancellation (#16316)
Browse files Browse the repository at this point in the history
Towards #16315 

It created a bunch of Error objects and rejected the promise. This patch
changes `op_sleep` to resolve with `true` if it was cancelled.
  • Loading branch information
littledivy authored and bartlomieju committed Oct 17, 2022
1 parent 454a9f1 commit 1a6d312
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
16 changes: 6 additions & 10 deletions ext/web/02_timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
// deno-lint-ignore camelcase
NumberPOSITIVE_INFINITY,
PromisePrototypeThen,
ObjectPrototypeIsPrototypeOf,
SafeArrayIterator,
SymbolFor,
TypeError,
Expand Down Expand Up @@ -245,7 +244,12 @@
// 1.
PromisePrototypeThen(
sleepPromise,
() => {
(cancelled) => {
if (!cancelled) {
// The timer was cancelled.
removeFromScheduledTimers(timerObject);
return;
}
// 2. Wait until any invocations of this algorithm that had the same
// global and orderingIdentifier, that started before this one, and
// whose milliseconds is equal to or less than this one's, have
Expand Down Expand Up @@ -278,14 +282,6 @@
currentEntry = currentEntry.next;
}
},
(err) => {
if (ObjectPrototypeIsPrototypeOf(core.InterruptedPrototype, err)) {
// The timer was cancelled.
removeFromScheduledTimers(timerObject);
} else {
throw err;
}
},
);
}

Expand Down
10 changes: 6 additions & 4 deletions ext/web/timers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,17 @@ pub fn op_timer_handle(state: &mut OpState) -> ResourceId {

/// Waits asynchronously until either `millis` milliseconds have passed or the
/// [`TimerHandle`] resource given by `rid` has been canceled.
///
/// If the timer is canceled, this returns `false`. Otherwise, it returns `true`.
#[op(deferred)]
pub async fn op_sleep(
state: Rc<RefCell<OpState>>,
millis: u64,
rid: ResourceId,
) -> Result<(), AnyError> {
) -> Result<bool, AnyError> {
let handle = state.borrow().resource_table.get::<TimerHandle>(rid)?;
tokio::time::sleep(Duration::from_millis(millis))
let res = tokio::time::sleep(Duration::from_millis(millis))
.or_cancel(handle.0.clone())
.await?;
Ok(())
.await;
Ok(res.is_ok())
}

0 comments on commit 1a6d312

Please sign in to comment.