Skip to content

Commit

Permalink
Eliminate the (now) unnecessary surrogate parent resource of clock po…
Browse files Browse the repository at this point in the history
…llables
  • Loading branch information
badeend committed Jan 24, 2024
1 parent fcc3e87 commit d9a9842
Showing 1 changed file with 14 additions and 36 deletions.
50 changes: 14 additions & 36 deletions crates/wasi/src/preview2/host/clocks.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
#![allow(unused_variables)]

use crate::preview2::bindings::{
clocks::monotonic_clock::{self, Duration as WasiDuration, Instant},
clocks::wall_clock::{self, Datetime},
};
use crate::preview2::poll::{subscribe, Subscribe};
use crate::preview2::{PollableResource, WasiView};
use crate::preview2::poll;
use crate::preview2::{Pollable, PollableResource, WasiView};
use cap_std::time::SystemTime;
use std::time::Duration;
use wasmtime::component::Resource;
Expand Down Expand Up @@ -42,23 +40,18 @@ impl<T: WasiView> wall_clock::Host for T {
}
}

fn subscribe_to_duration(
table: &mut wasmtime::component::ResourceTable,
duration: tokio::time::Duration,
) -> anyhow::Result<Resource<PollableResource>> {
let sleep = if duration.is_zero() {
table.push(Deadline::Past)?
fn make_pollable(duration: tokio::time::Duration) -> Box<dyn Pollable> {
if duration.is_zero() {
Box::new(poll::ready())
} else if let Some(deadline) = tokio::time::Instant::now().checked_add(duration) {
// NB: this resource created here is not actually exposed to wasm, it's
// only an internal implementation detail used to match the signature
// expected by `subscribe`.
table.push(Deadline::Instant(deadline))?
Box::new(poll::once(async move {
tokio::time::sleep_until(deadline).await
}))
} else {
// If the user specifies a time so far in the future we can't
// represent it, wait forever rather than trap.
table.push(Deadline::Never)?
};
subscribe(table, &sleep)
Box::new(poll::pending())
}
}

impl<T: WasiView> monotonic_clock::Host for T {
Expand All @@ -77,30 +70,15 @@ impl<T: WasiView> monotonic_clock::Host for T {
} else {
Duration::from_nanos(0)
};
subscribe_to_duration(&mut self.table(), duration)
let pollable = make_pollable(duration);
Ok(self.table().push(PollableResource::new(pollable))?)
}

fn subscribe_duration(
&mut self,
duration: WasiDuration,
) -> anyhow::Result<Resource<PollableResource>> {
subscribe_to_duration(&mut self.table(), Duration::from_nanos(duration))
}
}

enum Deadline {
Past,
Instant(tokio::time::Instant),
Never,
}

#[async_trait::async_trait]
impl Subscribe for Deadline {
async fn ready(&mut self) {
match self {
Deadline::Past => {}
Deadline::Instant(instant) => tokio::time::sleep_until(*instant).await,
Deadline::Never => std::future::pending().await,
}
let pollable = make_pollable(Duration::from_nanos(duration));
Ok(self.table().push(PollableResource::new(pollable))?)
}
}

0 comments on commit d9a9842

Please sign in to comment.