Skip to content

Commit

Permalink
Switch from wasmer to wasmtime
Browse files Browse the repository at this point in the history
  • Loading branch information
coolreader18 committed Nov 1, 2023
1 parent 593702c commit 3a99f58
Show file tree
Hide file tree
Showing 15 changed files with 544 additions and 1,795 deletions.
541 changes: 33 additions & 508 deletions Cargo.lock

Large diffs are not rendered by default.

15 changes: 6 additions & 9 deletions crates/client-api/src/routes/energy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,10 @@ pub async fn add_energy<S: ControlStateDelegate>(
let mut balance = ctx
.get_energy_balance(&auth.identity)
.map_err(log_and_500)?
.map(|quanta| quanta.0)
.unwrap_or(0);
.map_or(0, |quanta| quanta.get());

if let Some(satoshi) = amount {
ctx.add_energy(&auth.identity, EnergyQuanta(satoshi))
ctx.add_energy(&auth.identity, EnergyQuanta::new(satoshi))
.await
.map_err(log_and_500)?;
balance += satoshi;
Expand All @@ -68,8 +67,7 @@ fn get_budget_inner(ctx: impl ControlStateDelegate, identity: &Identity) -> axum
let balance = ctx
.get_energy_balance(identity)
.map_err(log_and_500)?
.map(|quanta| quanta.0)
.unwrap_or(0);
.map_or(0, |quanta| quanta.get());

let response_json = json!({
// Note: balance must be returned as a string to avoid truncation.
Expand Down Expand Up @@ -114,18 +112,17 @@ pub async fn set_energy_balance<S: ControlStateDelegate>(
let current_balance = ctx
.get_energy_balance(&identity)
.map_err(log_and_500)?
.map(|quanta| quanta.0)
.unwrap_or(0);
.map_or(0, |quanta| quanta.get());

let balance: i128 = if desired_balance > current_balance {
let delta = desired_balance - current_balance;
ctx.add_energy(&identity, EnergyQuanta(delta))
ctx.add_energy(&identity, EnergyQuanta::new(delta))
.await
.map_err(log_and_500)?;
delta
} else {
let delta = current_balance - desired_balance;
ctx.withdraw_energy(&identity, EnergyQuanta(delta))
ctx.withdraw_energy(&identity, EnergyQuanta::new(delta))
.await
.map_err(log_and_500)?;
delta
Expand Down
9 changes: 5 additions & 4 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,11 @@ tracing.workspace = true
url.workspace = true
urlencoding.workspace = true
uuid.workspace = true
wasmer-middlewares.workspace = true
wasmer-types.workspace = true
wasmer-vm.workspace = true
wasmer.workspace = true
# wasmer-middlewares.workspace = true
# wasmer-types.workspace = true
# wasmer-vm.workspace = true
# wasmer.workspace = true
wasmtime.workspace = true
# Rocksdb ostorage backend, linked only if "rocksdb" feature enabled.
rocksdb = {workspace = true, optional = true}

Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/control_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ impl ControlDb {
return Err(Error::DecodingError(bsatn::DecodeError::BufferLength));
};
let balance = i128::from_be_bytes(arr);
Ok(Some(EnergyQuanta(balance)))
Ok(Some(EnergyQuanta::new(balance)))
} else {
Ok(None)
}
Expand All @@ -560,7 +560,7 @@ impl ControlDb {
/// `control_budget`, where a cached copy is stored along with business logic for managing it.
pub fn set_energy_balance(&self, identity: Identity, energy_balance: EnergyQuanta) -> Result<()> {
let tree = self.db.open_tree("energy_budget")?;
tree.insert(identity.as_bytes(), &energy_balance.0.to_be_bytes())?;
tree.insert(identity.as_bytes(), &energy_balance.get().to_be_bytes())?;

Ok(())
}
Expand Down
27 changes: 23 additions & 4 deletions crates/core/src/host/host_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,16 +90,26 @@ impl fmt::Display for DescribedEntityType {
/// for a user's balance to go negative. This is allowable
/// for reasons of eventual consistency motivated by performance.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct EnergyQuanta(pub i128);
pub struct EnergyQuanta(i128);

impl EnergyQuanta {
pub const ZERO: Self = EnergyQuanta(0);

pub const DEFAULT_BUDGET: Self = EnergyQuanta(1_000_000_000_000_000_000);

#[inline]
pub fn new(v: i128) -> Self {
Self(v)
}

#[inline]
pub fn get(&self) -> i128 {
self.0
}

/// A conversion function to convert from the canonical unit to points used
/// by Wasmer to track energy usage.
pub fn as_points(&self) -> u64 {
pub fn as_wasmer_points(&self) -> u64 {
if self.0 < 0 {
return 0;
} else if self.0 > u64::MAX as i128 {
Expand All @@ -108,10 +118,19 @@ impl EnergyQuanta {
self.0 as u64
}

const WASMTIME_MULTIPLIER: u64 = 1_000;
pub fn as_wasmtime_points(&self) -> u64 {
self.as_wasmer_points() / Self::WASMTIME_MULTIPLIER
}

/// A conversion function to convert from point used
/// by Wasmer to track energy usage, to our canonical unit.
pub fn from_points(points: u64) -> Self {
Self(points as i128)
pub fn from_wasmer_points(points: u64) -> Self {
Self(points.into())
}

pub fn from_wasmtime_points(points: u64) -> Self {
Self(i128::from(points) * i128::from(Self::WASMTIME_MULTIPLIER))
}
}

Expand Down
6 changes: 3 additions & 3 deletions crates/core/src/host/instance_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,13 +194,13 @@ impl InstanceEnv {
///
/// Errors with `TableNotFound` if the table does not exist.
#[tracing::instrument(skip_all)]
pub fn get_table_id(&self, table_name: String) -> Result<TableId, NodesError> {
pub fn get_table_id(&self, table_name: &str) -> Result<TableId, NodesError> {
let stdb = &*self.dbic.relational_db;
let tx = &mut *self.get_tx()?;

// Query the table id from the name.
let table_id = stdb
.table_id_from_name(tx, &table_name)?
.table_id_from_name(tx, table_name)?
.ok_or(NodesError::TableNotFound)?;

Ok(table_id)
Expand Down Expand Up @@ -238,7 +238,7 @@ impl InstanceEnv {
_ => return Err(NodesError::BadIndexType(index_type)),
};

let cols = NonEmpty::from_slice(&col_ids)
let cols = NonEmpty::from_vec(col_ids)
.expect("Attempt to create an index with zero columns")
.map(Into::into);

Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/host/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ impl EnergyMonitor for NullEnergyMonitor {
}

/// Tags for each call that a `WasmInstanceEnv` can make.
#[derive(Debug, Display, Enum)]
#[derive(Debug, Display, Enum, Clone, Copy)]
pub enum AbiCall {
CancelReducer,
ConsoleLog,
Expand Down
27 changes: 18 additions & 9 deletions crates/core/src/host/wasm_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod module_host_actor;

use std::time::Instant;

use super::AbiCall;
use crate::error::{DBError, IndexError, NodesError};

pub const CALL_REDUCER_DUNDER: &str = "__call_reducer__";
Expand Down Expand Up @@ -67,7 +68,7 @@ macro_rules! type_eq {
}
};
}
type_eq!(wasmer::Type);
type_eq!(wasmtime::ValType);

#[derive(Debug)]
pub struct FuncSig<T: AsRef<[WasmType]>> {
Expand All @@ -81,22 +82,22 @@ impl StaticFuncSig {
Self { params, results }
}
}
impl<T: AsRef<[WasmType]>> PartialEq<FuncSig<T>> for wasmer::ExternType {
impl<T: AsRef<[WasmType]>> PartialEq<FuncSig<T>> for wasmtime::ExternType {
fn eq(&self, other: &FuncSig<T>) -> bool {
self.func().map_or(false, |f| {
f.params() == other.params.as_ref() && f.results() == other.results.as_ref()
f.params().eq(other.params.as_ref()) && f.results().eq(other.results.as_ref())
})
}
}
impl FuncSigLike for wasmer::ExternType {
impl FuncSigLike for wasmtime::ExternType {
fn to_func_sig(&self) -> Option<BoxFuncSig> {
self.func().map(|f| FuncSig {
params: f.params().iter().map(|t| (*t).into()).collect(),
results: f.results().iter().map(|t| (*t).into()).collect(),
params: f.params().map(Into::into).collect(),
results: f.results().map(Into::into).collect(),
})
}
fn is_memory(&self) -> bool {
matches!(self, wasmer::ExternType::Memory(_))
matches!(self, wasmtime::ExternType::Memory(_))
}
}

Expand Down Expand Up @@ -220,7 +221,7 @@ pub trait ResourceIndex {

macro_rules! decl_index {
($name:ident => $resource:ty) => {
#[derive(Copy, Clone, wasmer::ValueType)]
#[derive(Copy, Clone)] // , wasmer::ValueType
#[repr(transparent)]
pub(super) struct $name(pub u32);

Expand All @@ -233,6 +234,14 @@ macro_rules! decl_index {
self.0
}
}

impl $name {
#[allow(unused)]
#[doc(hidden)]
pub(super) fn to_le_bytes(self) -> [u8; 4] {
self.0.to_le_bytes()
}
}
};
}

Expand Down Expand Up @@ -355,7 +364,7 @@ pub fn err_to_errno(err: &NodesError) -> Option<u16> {
#[derive(Debug, thiserror::Error)]
#[error("runtime error calling {func}: {err}")]
pub struct AbiRuntimeError {
pub func: &'static str,
pub func: AbiCall,
#[source]
pub err: NodesError,
}
2 changes: 1 addition & 1 deletion crates/core/src/host/wasm_common/module_host_actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ impl<T: WasmInstance> WasmModuleInstance<T> {
let reducer_span = tracing::trace_span!(
"run_reducer",
timings.total_duration = tracing::field::Empty,
energy.budget = budget.0,
energy.budget = budget.get(),
energy.used = tracing::field::Empty,
)
.entered();
Expand Down
Loading

0 comments on commit 3a99f58

Please sign in to comment.