mirror of
https://github.com/clockworklabs/SpacetimeDB.git
synced 2026-05-06 07:26:43 -04:00
Properly handle execution time<->energy conversion in v8 host (#4884)
# Description of Changes Fixes a todo. # Expected complexity level and risk 1 # Testing - [x] Checked that conversion ratio is sane.
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user