rogue-runtime 0.1.0

Async RPC Runtime
Documentation
use anyhow::Result;

use rogue_runtime::prelude::*;

// Stateful bank account example via RPC methods on a struct
rpc! {
    struct BankAccount {
        id: InstanceId,
        balance: i64,
    }

    impl Identity for BankAccount {
        fn id(&self) -> &InstanceId {
            &self.id
        }
    }

    impl BankAccount {
        /// Create a new account with an initial balance.
        pub async fn new(initial: i64) -> Self {
            Self {
                id: InstanceId::new(),
                balance: initial,
            }
        }

        /// Get the current balance.
        pub async fn balance(&self) -> i64 {
            self.balance
        }

        /// Deposit an amount into the account.
        pub async fn deposit(&mut self, amount: i64) {
            self.balance += amount;
        }

        /// Attempt to withdraw an amount. Returns true if successful.
        pub async fn withdraw(&mut self, amount: i64) -> bool {
            if self.balance >= amount {
                self.balance -= amount;
                true
            } else {
                false
            }
        }
    }
}

#[tokio::test]
async fn test_bank_account_runtime() -> Result<()> {
    // Create a new runtime for the bank account example
    let runtime = Runtime::create("instance_test".to_string()).await?;

    // Execute RPC calls locally
    runtime
        .execute_local(async move {
            // Start with initial balance of 100
            let mut acct = BankAccount::new(100).await;
            assert_eq!(acct.balance().await, 100);
            // Deposit 50
            acct.deposit(50).await;
            assert_eq!(acct.balance().await, 150);
            // Withdraw 70 successfully
            assert!(acct.withdraw(70).await);
            assert_eq!(acct.balance().await, 80);
            // Attempt to overdraw
            assert!(!acct.withdraw(200).await);
            // Balance remains unchanged
            assert_eq!(acct.balance().await, 80);
            // Deposit to bring back to 100
            acct.deposit(20).await;
            assert_eq!(acct.balance().await, 100);
            Ok(())
        })
        .await?;

    Ok(())
}