Skip to content

Commit

Permalink
Merge pull request #303 from emmatebibyte/unix-time
Browse files Browse the repository at this point in the history
Add UNIX time API
  • Loading branch information
marceline-cramer committed Mar 18, 2024
2 parents 82acfb8 + 975d01c commit 69b828d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
9 changes: 9 additions & 0 deletions kindling/host/src/time.rs
Expand Up @@ -28,6 +28,9 @@ lazy_static::lazy_static! {

static ref STOPWATCH_FACTORY: RequestResponse<(), ()> =
RequestResponse::expect_service("hearth.StopwatchFactory");

static ref UNIX_TIME: RequestResponse<(), u128> =
RequestResponse::expect_service("hearth.UnixTime");
}

/// Sleeps for the given time in seconds.
Expand All @@ -41,6 +44,12 @@ pub fn sleep(duration: f32) {
let _ = reply.recv_raw();
}

/// Gets the time since the UNIX epoch in nanoseconds as a unsigned 128-bit
/// integer.
pub fn get_unix_time() -> u128 {
UNIX_TIME.request((), &[]).0
}

pub struct Timer(RequestResponse<f32, ()>);

impl Default for Timer {
Expand Down
40 changes: 38 additions & 2 deletions plugins/time/src/lib.rs
Expand Up @@ -16,6 +16,8 @@
// You should have received a copy of the GNU Affero General Public License
// along with Hearth. If not, see <https://www.gnu.org/licenses/>.

use std::time::SystemTime;

use hearth_runtime::{
async_trait,
flue::Table,
Expand All @@ -34,7 +36,11 @@ use hearth_runtime::{

/// A plugin that provides timing services to guests.
///
/// Adds the [SleepService], [TimerFactory], and [StopwatchFactory] services.
/// Adds the following services:
/// - [SleepService]
/// - [TimerFactory]
/// - [StopwatchFactory]
/// - [UnixTimeService]
#[derive(Default)]
pub struct TimePlugin;

Expand All @@ -43,7 +49,8 @@ impl Plugin for TimePlugin {
builder
.add_plugin(SleepService)
.add_plugin(TimerFactory)
.add_plugin(StopwatchFactory);
.add_plugin(StopwatchFactory)
.add_plugin(UnixTimeService);
}
}

Expand Down Expand Up @@ -203,3 +210,32 @@ impl RequestResponseProcess for Stopwatch {
}
}
}

/// Native service that returns time since the UNIX epoch in nanoseconds as an
/// unsigned 128-bit integer.
#[derive(GetProcessMetadata)]
pub struct UnixTimeService;

#[async_trait]
impl RequestResponseProcess for UnixTimeService {
type Request = ();
type Response = u128;

async fn on_request<'a>(
&'a mut self,
_request: &mut RequestInfo<'a, Self::Request>,
) -> ResponseInfo<'a, Self::Response> {
let time_since_epoch = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("system time before UNIX epoch");

ResponseInfo {
data: time_since_epoch.as_nanos(),
caps: vec![],
}
}
}

impl ServiceRunner for UnixTimeService {
const NAME: &'static str = "hearth.UnixTime";
}

0 comments on commit 69b828d

Please sign in to comment.