EmbeddedEngine

Struct EmbeddedEngine 

Source
pub struct EmbeddedEngine { /* private fields */ }
Expand description

Embedded d-engine with automatic lifecycle management.

Provides high-level KV API for embedded usage:

  • start() / start_with() - Initialize and spawn node
  • wait_ready() - Wait for leader election
  • client() - Get local KV client
  • stop() - Graceful shutdown

§Example

use d_engine::EmbeddedEngine;
use std::time::Duration;

let engine = EmbeddedEngine::start().await?;
engine.wait_ready(Duration::from_secs(5)).await?;

let client = engine.client();
client.put(b"key", b"value").await?;

engine.stop().await?;

Implementations§

Source§

impl EmbeddedEngine

Source

pub async fn start() -> Result<EmbeddedEngine, Error>

Start engine with configuration from environment.

Reads CONFIG_PATH environment variable or uses default configuration. Data directory is determined by config’s cluster.db_root_dir setting.

§Example
// Set config path via environment variable
std::env::set_var("CONFIG_PATH", "/etc/d-engine/production.toml");

let engine = EmbeddedEngine::start().await?;
engine.wait_ready(Duration::from_secs(5)).await?;
Source

pub async fn start_with(config_path: &str) -> Result<EmbeddedEngine, Error>

Start engine with explicit configuration file.

Reads configuration from specified file path. Data directory is determined by config’s cluster.db_root_dir setting.

§Arguments
  • config_path: Path to configuration file (e.g. “d-engine.toml”)
§Example
let engine = EmbeddedEngine::start_with("config/node1.toml").await?;
engine.wait_ready(Duration::from_secs(5)).await?;
Source

pub async fn start_custom<SE, SM>( storage_engine: Arc<SE>, state_machine: Arc<SM>, config_path: Option<&str>, ) -> Result<EmbeddedEngine, Error>
where SE: StorageEngine + Debug + 'static, SM: StateMachine + Debug + 'static,

Start engine with custom storage and state machine.

Advanced API for users providing custom storage implementations.

§Arguments
  • config_path: Optional path to configuration file
  • storage_engine: Custom storage engine implementation
  • state_machine: Custom state machine implementation
§Example
let storage = Arc::new(MyCustomStorage::new()?);
let sm = Arc::new(MyCustomStateMachine::new()?);
let engine = EmbeddedEngine::start_custom(storage, sm, None).await?;
Source

pub async fn wait_ready(&self, timeout: Duration) -> Result<LeaderInfo, Error>

Wait for leader election to complete.

Blocks until a leader has been elected in the cluster. Event-driven notification (no polling), <1ms latency.

§Timeout
  • Single-node: Returns immediately (<100ms)
  • Multi-node: May take seconds depending on network
§Example
let engine = EmbeddedEngine::start().await?;
let leader = engine.wait_ready(Duration::from_secs(10)).await?;
println!("Leader elected: {} (term {})", leader.leader_id, leader.term);
Source

pub fn leader_change_notifier(&self) -> Receiver<Option<LeaderInfo>>

Subscribe to leader change notifications.

Returns a receiver that will be notified whenever:

  • First leader is elected
  • Leader changes (re-election)
  • No leader exists (during election)
§Performance

Event-driven notification (no polling), <1ms latency

§Example
let mut leader_rx = engine.leader_change_notifier();
tokio::spawn(async move {
    while leader_rx.changed().await.is_ok() {
        match leader_rx.borrow().as_ref() {
            Some(info) => println!("Leader: {} (term {})", info.leader_id, info.term),
            None => println!("No leader"),
        }
    }
});
Source

pub fn client(&self) -> &LocalKvClient

Get a reference to the local KV client.

The client is available immediately after start(), but requests will only succeed after wait_ready() completes.

§Example
let engine = EmbeddedEngine::start().await?;
engine.wait_ready(Duration::from_secs(5)).await?;
let client = engine.client();
client.put(b"key", b"value").await?;
Source

pub fn watch(&self, key: impl AsRef<[u8]>) -> Result<WatcherHandle, Error>

Register a watcher for a specific key.

Returns a handle that receives watch events via an mpsc channel. The watcher is automatically unregistered when the handle is dropped.

§Arguments
  • key - The exact key to watch
§Returns
  • Result<WatcherHandle> - Handle for receiving events
§Example
let engine = EmbeddedEngine::start().await?;
let mut handle = engine.watch(b"mykey")?;
while let Some(event) = handle.receiver_mut().recv().await {
    println!("Key changed: {:?}", event);
}
Source

pub async fn stop(self) -> Result<(), Error>

Gracefully stop the embedded engine.

This method:

  1. Sends shutdown signal to node
  2. Waits for node.run() to complete
  3. Propagates any errors from node execution
§Errors

Returns error if node encountered issues during shutdown.

§Example
engine.stop().await?;

Trait Implementations§

Source§

impl Drop for EmbeddedEngine

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more