Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions crates/client-api-messages/src/energy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@ pub struct EnergyQuanta {
impl EnergyQuanta {
pub const ZERO: Self = EnergyQuanta { quanta: 0 };

// per the comment on [`FunctionBudget::DEFAULT_BUDGET`]: 1 second of wasm runtime is roughtly 2 TeV
pub const PER_EXECUTION_SEC: Self = Self::new(2_000_000_000_000);
pub const PER_EXECUTION_NANOSEC: Self = Self::new(Self::PER_EXECUTION_SEC.get() / 1_000_000_000);

#[inline]
pub fn new(quanta: u128) -> Self {
pub const fn new(quanta: u128) -> Self {
Self { quanta }
}

#[inline]
pub fn get(&self) -> u128 {
pub const fn get(&self) -> u128 {
self.quanta
}

Expand Down
9 changes: 7 additions & 2 deletions crates/core/src/host/v8/budget.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use core::ptr;
use core::sync::atomic::Ordering;
use core::time::Duration;
use core::{ffi::c_void, sync::atomic::AtomicBool};
use spacetimedb_client_api_messages::energy::FunctionBudget;
use spacetimedb_client_api_messages::energy::{EnergyQuanta, FunctionBudget};
use std::sync::Arc;
use v8::{Isolate, IsolateHandle};

Expand Down Expand Up @@ -118,7 +118,12 @@ fn budget_to_duration(_budget: FunctionBudget) -> Duration {
/// Returns [`EnergyStats`] for a reducer given its `budget`
/// and the `duration` it took to execute.
pub(super) fn energy_from_elapsed(budget: FunctionBudget, duration: Duration) -> EnergyStats {
let used = duration_to_budget(duration);
let used = duration.as_nanos() * EnergyQuanta::PER_EXECUTION_NANOSEC.get();
// in order for duration_nanos * ev_per_ns >= u64::MAX:
// duration_nanos >= u64::MAX / ev_per_ns
// duration_nanos >= (9223372036854775 ns = 106.75 days)
// so it's unlikely we'll have to worry about it
let used = FunctionBudget::new(u64::try_from(used).unwrap_or(u64::MAX));
let remaining = budget - used;
EnergyStats { budget, remaining }
}
Expand Down
Loading