Skip to content

Commit

Permalink
chore: integrate sdk & runtime (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
scarmuega authored Oct 5, 2024
1 parent 455f3a4 commit 1f71139
Show file tree
Hide file tree
Showing 18 changed files with 530 additions and 146 deletions.
111 changes: 111 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions balius-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
struct _Main;

impl balius_sdk::wit::Guest for _Main {
fn init(env: balius_sdk::wit::Env) {
fn init(config: balius_sdk::wit::Config) {
let worker = #func_name();
balius_sdk::_internal::global_init_worker(env, worker);
balius_sdk::_internal::global_init_worker(config, worker);
}

fn handle(
Expand Down
36 changes: 35 additions & 1 deletion balius-runtime/src/adapter.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
router::Router,
wit::balius::app::{driver, kv, submit},
wit::balius::app::{driver, kv, ledger, submit},
};

#[derive(Clone)]
Expand Down Expand Up @@ -44,3 +44,37 @@ impl driver::Host for Adapter {
self.router.register_channel(&self.worker_id, id, &pattern);
}
}

impl ledger::Host for Adapter {
fn read_utxos(
&mut self,
refs: Vec<ledger::TxoRef>,
) -> Result<Vec<ledger::Utxo>, ledger::LedgerError> {
let output = pallas::ledger::primitives::babbage::MintedTransactionOutput::PostAlonzo(pallas::ledger::primitives::babbage::MintedPostAlonzoTransactionOutput {
address: pallas::ledger::addresses::Address::from_bech32("addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3n0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgse35a3x").unwrap().to_vec().into(),
value: pallas::ledger::primitives::babbage::Value::Coin(5_000_000),
datum_option: None,
script_ref: None,
});

let cbor = pallas::codec::minicbor::to_vec(&output).unwrap();

Ok(vec![ledger::Utxo {
ref_: ledger::TxoRef {
tx_hash: hex::decode(
"f7d3837715680f3a170e99cd202b726842d97f82c05af8fcd18053c64e33ec4f",
)
.unwrap(),
tx_index: 0,
},
body: cbor,
}])
}

fn search_utxos(
&mut self,
pattern: ledger::UtxoPattern,
) -> Result<Vec<ledger::Utxo>, ledger::LedgerError> {
todo!()
}
}
31 changes: 17 additions & 14 deletions balius-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ mod loader;
mod router;
mod store;

pub use loader::Loader;
pub use router::Router;
pub use store::Store;

pub type WorkerId = String;
Expand All @@ -29,8 +27,8 @@ pub enum Error {
#[error("worker not found '{0}'")]
WorkerNotFound(WorkerId),

#[error("worker failed to handle event (code: '{0}')")]
Handle(u32),
#[error("worker failed to handle event (code: '{0}', message: '{1}')")]
Handle(u32, String),

#[error("no target available to solve request")]
NoTarget,
Expand Down Expand Up @@ -94,17 +92,17 @@ pub type LogSeq = u64;

#[derive(Clone)]
pub struct Runtime {
loader: Loader,
router: Router,
store: Store,
loader: loader::Loader,
router: router::Router,
store: store::Store,
}

impl Runtime {
pub fn new(store: Store) -> Result<Self, Error> {
let router = Router::new();
pub fn new(store: store::Store) -> Result<Self, Error> {
let router = router::Router::new();

Ok(Self {
loader: Loader::new(router.clone())?,
loader: loader::Loader::new(router.clone())?,
router,
store,
})
Expand All @@ -116,8 +114,13 @@ impl Runtime {
Ok(cursor)
}

pub fn register_worker(&mut self, id: &str, wasm_path: impl AsRef<Path>) -> Result<(), Error> {
self.loader.register_worker(id, wasm_path)?;
pub fn register_worker(
&mut self,
id: &str,
wasm_path: impl AsRef<Path>,
config: serde_json::Value,
) -> Result<(), Error> {
self.loader.register_worker(id, wasm_path, config)?;

Ok(())
}
Expand All @@ -139,8 +142,8 @@ impl Runtime {
Ok(_) => {
tracing::warn!(worker = target.worker, "worker returned unexpected data");
}
Err(Error::Handle(code)) => {
tracing::warn!(code, "worker error");
Err(Error::Handle(code, message)) => {
tracing::warn!(code, message);
}
Err(e) => return Err(e),
}
Expand Down
8 changes: 5 additions & 3 deletions balius-runtime/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ impl Loader {
wit::balius::app::driver::add_to_linker(&mut linker, |state: &mut Adapter| state)?;
wit::balius::app::kv::add_to_linker(&mut linker, |state: &mut Adapter| state)?;
wit::balius::app::submit::add_to_linker(&mut linker, |state: &mut Adapter| state)?;
wit::balius::app::ledger::add_to_linker(&mut linker, |state: &mut Adapter| state)?;

Ok(Self {
engine,
Expand All @@ -44,6 +45,7 @@ impl Loader {
&mut self,
id: &str,
wasm_path: impl AsRef<Path>,
config: serde_json::Value,
) -> wasmtime::Result<()> {
let component = Component::from_file(&self.engine, wasm_path)?;

Expand All @@ -53,8 +55,8 @@ impl Loader {
);

let instance = wit::Worker::instantiate(&mut store, &component, &self.linker)?;
//instance.call_init(&mut store, &vec![])?;
instance.call_init(&mut store, &hex::decode("7b22667265655f76616c696461746f72223a7b227265665f74786f223a7b2268617368223a2266376433383337373135363830663361313730653939636432303262373236383432643937663832633035616638666364313830353363363465333365633466222c22696e646578223a307d2c2268617368223a226566376131636562623264633764653838346464663832663866636263393166653937353064636438633132656337363433613939626265222c2261646472657373223a22616464723171783266787632756d796874746b78797870387830646c706474336b3663776e673570786a336a687379647a6572336e306433766c6c6d797177737835776b7463643863633373713833356c75376472763278776c32777977666773653335613378227d7d").unwrap())?;
let config = serde_json::to_vec(&config).unwrap();
instance.call_init(&mut store, &config)?;

self.loaded
.lock()
Expand All @@ -80,7 +82,7 @@ impl Loader {
.instance
.call_handle(&mut worker.store, channel, event)?;

let response = result.map_err(|code| super::Error::Handle(code))?;
let response = result.map_err(|err| super::Error::Handle(err.code, err.message))?;

Ok(response)
}
Expand Down
29 changes: 24 additions & 5 deletions balius-runtime/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ type ChannelId = u32;
type Method = String;
type AddressBytes = Vec<u8>;

#[derive(Hash, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum MatchKey {
RequestMethod(WorkerId, Method),
UtxoAddress(AddressBytes),
}

#[derive(PartialEq, Eq, Hash, Clone)]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Target {
pub channel: u32,
pub channel: ChannelId,
pub worker: String,
}

Expand All @@ -34,11 +34,11 @@ fn infer_match_keys(worker: &str, pattern: &EventPattern) -> Vec<MatchKey> {
}
}

type Routes = HashMap<MatchKey, HashSet<Target>>;
type RouteMap = HashMap<MatchKey, HashSet<Target>>;

#[derive(Default, Clone)]
pub struct Router {
routes: Arc<RwLock<Routes>>,
routes: Arc<RwLock<RouteMap>>,
}

impl Router {
Expand Down Expand Up @@ -100,3 +100,22 @@ impl Router {
Ok(target.clone())
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_request_channel() {
let mut router = Router::new();
let worker = "test_worker";
let method = "test_method";
let channel = 1;

router.register_channel(worker, channel, &EventPattern::Request(method.to_string()));

let target = router.find_request_target(worker, method).unwrap();
assert_eq!(target.worker, worker);
assert_eq!(target.channel, channel);
}
}
1 change: 1 addition & 0 deletions balius-runtime/tests/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
balius.db
Loading

0 comments on commit 1f71139

Please sign in to comment.