Skip to main content

wasmtime_wasi/p2/host/
clocks.rs

1use crate::clocks::WasiClocksCtxView;
2use crate::p2::DynPollable;
3use crate::p2::bindings::{
4    clocks::monotonic_clock::{self, Duration as WasiDuration, Instant},
5    clocks::wall_clock::{self, Datetime},
6};
7use crate::runtime::with_ambient_tokio_runtime;
8use std::time::Duration;
9use std::time::SystemTime;
10use wasmtime::component::Resource;
11use wasmtime_wasi_io::poll::{Pollable, subscribe};
12
13impl TryFrom<crate::clocks::Datetime> for Datetime {
14    type Error = crate::clocks::DatetimeError;
15
16    fn try_from(
17        crate::clocks::Datetime {
18            seconds,
19            nanoseconds,
20        }: crate::clocks::Datetime,
21    ) -> Result<Self, Self::Error> {
22        Ok(Self {
23            seconds: seconds.try_into()?,
24            nanoseconds,
25        })
26    }
27}
28
29impl TryFrom<Datetime> for crate::clocks::Datetime {
30    type Error = crate::clocks::DatetimeError;
31
32    fn try_from(
33        Datetime {
34            seconds,
35            nanoseconds,
36        }: Datetime,
37    ) -> Result<Self, Self::Error> {
38        Ok(Self {
39            seconds: seconds.try_into()?,
40            nanoseconds,
41        })
42    }
43}
44
45impl TryFrom<SystemTime> for Datetime {
46    type Error = crate::clocks::DatetimeError;
47
48    fn try_from(time: SystemTime) -> Result<Self, Self::Error> {
49        let time = crate::clocks::Datetime::try_from(time)?;
50        time.try_into()
51    }
52}
53
54impl wall_clock::Host for WasiClocksCtxView<'_> {
55    fn now(&mut self) -> wasmtime::Result<Datetime> {
56        let now = self.ctx.wall_clock.now();
57        Ok(Datetime {
58            seconds: now.as_secs(),
59            nanoseconds: now.subsec_nanos(),
60        })
61    }
62
63    fn resolution(&mut self) -> wasmtime::Result<Datetime> {
64        let res = self.ctx.wall_clock.resolution();
65        Ok(Datetime {
66            seconds: res.as_secs(),
67            nanoseconds: res.subsec_nanos(),
68        })
69    }
70}
71
72fn subscribe_to_duration(
73    table: &mut wasmtime::component::ResourceTable,
74    duration: tokio::time::Duration,
75) -> wasmtime::Result<Resource<DynPollable>> {
76    let sleep = if duration.is_zero() {
77        table.push(Deadline::Past { yielded: false })?
78    } else if let Some(deadline) = tokio::time::Instant::now().checked_add(duration) {
79        // NB: this resource created here is not actually exposed to wasm, it's
80        // only an internal implementation detail used to match the signature
81        // expected by `subscribe`.
82        table.push(Deadline::Instant(deadline))?
83    } else {
84        // If the user specifies a time so far in the future we can't
85        // represent it, wait forever rather than trap.
86        table.push(Deadline::Never)?
87    };
88    subscribe(table, sleep)
89}
90
91impl monotonic_clock::Host for WasiClocksCtxView<'_> {
92    fn now(&mut self) -> wasmtime::Result<Instant> {
93        Ok(self.ctx.monotonic_clock.now())
94    }
95
96    fn resolution(&mut self) -> wasmtime::Result<Instant> {
97        Ok(self.ctx.monotonic_clock.resolution())
98    }
99
100    fn subscribe_instant(&mut self, when: Instant) -> wasmtime::Result<Resource<DynPollable>> {
101        let clock_now = self.ctx.monotonic_clock.now();
102        let duration = if when > clock_now {
103            Duration::from_nanos(when - clock_now)
104        } else {
105            Duration::from_nanos(0)
106        };
107        subscribe_to_duration(self.table, duration)
108    }
109
110    fn subscribe_duration(
111        &mut self,
112        duration: WasiDuration,
113    ) -> wasmtime::Result<Resource<DynPollable>> {
114        subscribe_to_duration(self.table, Duration::from_nanos(duration))
115    }
116}
117
118enum Deadline {
119    Past { yielded: bool },
120    Instant(tokio::time::Instant),
121    Never,
122}
123
124#[async_trait::async_trait]
125impl Pollable for Deadline {
126    async fn ready(&mut self) {
127        match self {
128            Deadline::Past { yielded: true } => {}
129            Deadline::Past { yielded } => {
130                // It is important we yield to Tokio here; otherwise we risk
131                // starving `mio` such that it is unable to signal readiness for
132                // other pollables (e.g. TCP sockets) when the guest is polling
133                // in a busy loop.
134                //
135                // This is somewhat of a hack to ensure that
136                // `wasmtime-wasi-io`'s implementation of `wasi:io/poll` does
137                // not starve `mio` when the guest calls `wasi:io/poll#poll` in
138                // a busy loop with a zero timeout.  It relies on the guest
139                // using the most natural approach to making a non-blocking call
140                // to `wasi:io/poll#poll`, which is to include a zero-duration
141                // `monotonic_clock::subscribe_{instant,duration}` in the list
142                // of pollables.  That's what `wasi-libc`'s `poll(2)`
143                // implementation does as of this writing, for example.  There
144                // are hypothetically other ways to generate a pollable that's
145                // always immediately ready, which this hack doesn't cover, but
146                // we consider this sufficient for now.
147                *yielded = true;
148                tokio::task::yield_now().await
149            }
150            Deadline::Instant(instant) => {
151                with_ambient_tokio_runtime(|| tokio::time::sleep_until(*instant)).await
152            }
153            Deadline::Never => std::future::pending().await,
154        }
155    }
156}
157
158mod named {
159    use crate::clocks::WasiClocksNamedView;
160    use crate::p2::DynPollable;
161    use crate::p2::bindings::clocks::monotonic_clock::{Duration as WasiDuration, Instant};
162    use crate::p2::bindings::clocks::wall_clock::Datetime;
163    use crate::p2::bindings::named_imports::wasi::clocks::{monotonic_clock, wall_clock};
164    use crate::{NamedId, WasiCtxNamedView};
165    use wasmtime::component::Resource;
166
167    impl<T> wall_clock::Host for WasiCtxNamedView<'_, T>
168    where
169        T: WasiClocksNamedView,
170    {
171        fn now(&mut self, id: NamedId) -> wasmtime::Result<Datetime> {
172            super::wall_clock::Host::now(&mut self.0.clocks(id))
173        }
174
175        fn resolution(&mut self, id: NamedId) -> wasmtime::Result<Datetime> {
176            super::wall_clock::Host::resolution(&mut self.0.clocks(id))
177        }
178    }
179
180    impl<T> monotonic_clock::Host for WasiCtxNamedView<'_, T>
181    where
182        T: WasiClocksNamedView,
183    {
184        fn now(&mut self, id: NamedId) -> wasmtime::Result<Instant> {
185            super::monotonic_clock::Host::now(&mut self.0.clocks(id))
186        }
187
188        fn resolution(&mut self, id: NamedId) -> wasmtime::Result<Instant> {
189            super::monotonic_clock::Host::resolution(&mut self.0.clocks(id))
190        }
191
192        fn subscribe_instant(
193            &mut self,
194            id: NamedId,
195            when: Instant,
196        ) -> wasmtime::Result<Resource<DynPollable>> {
197            super::monotonic_clock::Host::subscribe_instant(&mut self.0.clocks(id), when)
198        }
199
200        fn subscribe_duration(
201            &mut self,
202            id: NamedId,
203            duration: WasiDuration,
204        ) -> wasmtime::Result<Resource<DynPollable>> {
205            super::monotonic_clock::Host::subscribe_duration(&mut self.0.clocks(id), duration)
206        }
207    }
208}