WebAssembly / wasi-clocks

Clocks API for WASI
37 stars 14 forks source link

Should we have a `duration` type distinct from `instant`? #52

Closed pchickey closed 10 months ago

pchickey commented 11 months ago

Presently, in the monotonic clock interface, duration is conflated with a timestamp, with a boolean in the subscribe function indicating whether the instant actually represents a duration.

I believe we should distinguish between these in the type system, and rather than use a boolean, expose two different subscribe functions, as shown below.

One advantage of this is that other WASI libraries can then use wasi:clocks/monotonic-clock.{duration}; as a standard representation of duration. For instance, right now wasi-http uses a u32 to represent at timeout in milliseconds. It would be nice to point to one single duration type and say to always use that one unless the problem domain insists otherwise.

diff --git a/crates/wasi-http/wit/deps/clocks/monotonic-clock.wit b/crates/wasi-http/wit/deps/clocks/monotonic-clock.wit
index d9ac7cb3f..a6e2574bf 100644
--- a/crates/wasi-http/wit/deps/clocks/monotonic-clock.wit
+++ b/crates/wasi-http/wit/deps/clocks/monotonic-clock.wit
@@ -14,6 +14,9 @@ interface monotonic-clock {
     /// A timestamp in nanoseconds.
     type instant = u64;

+    /// A duration in nanoseconds.
+    type duration = u64;
+
     /// Read the current value of the clock.
     ///
     /// The clock is monotonic, therefore calling this function repeatedly will
@@ -25,8 +28,13 @@ interface monotonic-clock {

     /// Create a `pollable` which will resolve once the specified time has been
     /// reached.
-    subscribe: func(
+    subscribe_instant: func(
         when: instant,
-        absolute: bool
+    ) -> pollable;
+
+    /// Create a `pollable` which will resolve once the given duration
+    /// has elapsed, starting at the time this function is called.
+    subscribe_duration: func(
+        when: duration,
     ) -> pollable;
sunfishcode commented 11 months ago

Having absolute be a dynamic flag comes from CloudABI, which comes from POSIX clock_nanosleep which has a dynamic TIMER_ABSTIME flag. Could we guess that most users using clock_nanosleep and/or calling the WASI API directly are using a constant value for the TIMER_ABSTIME/CLOCK_ABSTIME flag?

pchickey commented 11 months ago

Yes, I think we should expect that its easy for anyone using the WASI interface directly to handle this change, and for libc to dispatch based on the flag bit is reasonable.

sunfishcode commented 11 months ago

I agree.