d_engine_server/lib.rs
1//! # d-engine-server
2//!
3//! Complete Raft server with gRPC and storage - batteries included
4//!
5//! ## When to use this crate directly
6//!
7//! - ✅ Embedding server in a larger Rust application
8//! - ✅ Need programmatic access to server APIs
9//! - ✅ Building custom tooling around d-engine
10//! - ✅ Already have your own client implementation
11//!
12//! ## When to use `d-engine` instead
13//!
14//! Most users should use [`d-engine`](https://crates.io/crates/d-engine):
15//!
16//! ```toml
17//! [dependencies]
18//! d-engine = { version = "0.2", features = ["server"] }
19//! ```
20//!
21//! It re-exports this crate plus optional client libraries with simpler dependency management.
22//!
23//! ## Quick Start
24//!
25//! **Embedded Mode** (zero-overhead local client):
26//!
27//! ```rust,ignore
28//! use d_engine_server::EmbeddedEngine;
29//! use std::time::Duration;
30//!
31//! #[tokio::main]
32//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
33//! let engine = EmbeddedEngine::start_with("config.toml").await?;
34//! engine.wait_ready(Duration::from_secs(5)).await?;
35//!
36//! let client = engine.client();
37//! client.put(b"key".to_vec(), b"value".to_vec()).await?;
38//!
39//! engine.stop().await?;
40//! Ok(())
41//! }
42//! ```
43//!
44//! **Standalone Mode** (independent server):
45//!
46//! ```rust,ignore
47//! use d_engine_server::StandaloneEngine;
48//! use tokio::sync::watch;
49//!
50//! #[tokio::main]
51//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
52//! let (_shutdown_tx, shutdown_rx) = watch::channel(());
53//! StandaloneEngine::run("./data", shutdown_rx).await?;
54//! Ok(())
55//! }
56//! ```
57//!
58//! ## Features
59//!
60//! This crate provides:
61//! - **gRPC Server** - Production-ready Raft RPC implementation
62//! - **Storage Backends** - File-based and RocksDB storage
63//! - **Cluster Orchestration** - Node lifecycle and membership management
64//! - **Snapshot Coordination** - Automatic log compaction
65//! - **Watch API** - Real-time state change notifications
66//!
67//! ## Custom Storage
68//!
69//! Implement the [`StateMachine`] and [`StorageEngine`] traits:
70//!
71//! ```rust,ignore
72//! use d_engine_server::{StateMachine, StorageEngine};
73//!
74//! struct MyStateMachine;
75//! impl StateMachine for MyStateMachine {
76//! // Apply committed entries to your application state
77//! }
78//!
79//! struct MyStorageEngine;
80//! impl StorageEngine for MyStorageEngine {
81//! // Persist Raft logs and metadata
82//! }
83//! ```
84//!
85//! ## Documentation
86//!
87//! For comprehensive guides:
88//! - [Customize Storage Engine](https://docs.rs/d-engine/latest/d_engine/docs/server_guide/customize_storage_engine/index.html)
89//! - [Customize State Machine](https://docs.rs/d-engine/latest/d_engine/docs/server_guide/customize_state_machine/index.html)
90//! - [Watch Feature Guide](https://docs.rs/d-engine/latest/d_engine/docs/server_guide/watch_feature/index.html)
91
92#![warn(missing_docs)]
93
94// ==================== Core Public API ====================
95
96/// Proto ↔ core type conversions — the single place that bridges gRPC and core types.
97mod proto_convert;
98#[cfg(test)]
99mod proto_convert_test;
100
101/// Node lifecycle management
102///
103/// Contains [`Node`] and [`NodeBuilder`] for server setup.
104pub mod node;
105
106/// Public API layer for different deployment modes
107///
108/// Contains [`EmbeddedEngine`] and [`StandaloneEngine`].
109pub mod api;
110
111// Re-export LeaderInfo from d-engine-core
112pub use d_engine_core::LeaderInfo;
113
114/// Storage layer implementations
115///
116/// Provides file-based and RocksDB storage backends.
117pub mod storage;
118
119// -------------------- Primary Entry Points --------------------
120pub use api::EmbeddedEngine;
121pub use api::StandaloneEngine;
122pub use membership::MembershipSnapshot;
123// -------------------- Error Types --------------------
124/// Unified error type for all d-engine operations
125pub use d_engine_core::Error;
126/// Log storage trait
127pub use d_engine_core::LogStore;
128/// Metadata storage trait
129pub use d_engine_core::MetaStore;
130/// Unified result type (equivalent to Result<T, Error>)
131pub use d_engine_core::Result;
132/// Prefix scan result: matching entries + revision anchor for watch deduplication
133pub use d_engine_core::ScanResult;
134/// Storage-specific error type
135pub use d_engine_core::StorageError;
136// Internal types required by storage implementations — not part of user API
137#[doc(hidden)]
138pub use d_engine_core::HardState;
139#[doc(hidden)]
140pub use d_engine_core::ProstError;
141#[doc(hidden)]
142pub use d_engine_core::SnapshotError;
143// -------------------- Client API --------------------
144pub use api::EmbeddedClient;
145/// Error code discriminator returned by [`ClientApiError::code()`].
146/// Use this to pattern-match error categories without inspecting message strings:
147/// `e.code() == ErrorCode::NotLeader`
148pub use d_engine_core::client::ErrorCode;
149/// Unified client operations trait (put/get/delete/CAS/watch).
150/// Re-exported here so embedded-mode users don't need a separate d-engine-client dependency.
151pub use d_engine_core::client::{ClientApi, ClientApiError, ClientApiResult};
152/// Storage trait for implementing custom storage backends
153///
154/// Implement this trait to create your own storage engine.
155pub use d_engine_core::{StateMachine, StorageEngine};
156pub use node::Node;
157pub use node::NodeBuilder;
158// Re-export storage implementations
159pub use storage::{FileStateMachine, FileStorageEngine};
160// Re-export core types needed by applications
161pub use d_engine_core::ApplyResult;
162pub use d_engine_core::{ApplyEntry, Command};
163// Conditional RocksDB exports
164#[cfg(feature = "rocksdb")]
165pub use storage::{RocksDBStateMachine, RocksDBStorageEngine, RocksDBUnifiedEngine};
166
167// -------------------- Watch API Types --------------------
168/// Watch event types and handles — available when the `watch` feature is enabled.
169///
170/// Use these when implementing embedded watch handlers:
171/// ```rust,ignore
172/// use d_engine::{WatchEventType, WatcherHandle, WatchEvent};
173/// ```
174#[cfg(feature = "watch")]
175pub use d_engine_core::{WatchError, WatchEvent, WatchEventType, WatcherHandle};
176
177// -------------------- Data Types --------------------
178
179/// Common Raft protocol types
180pub mod common {
181 // Basic types used in Raft consensus protocol
182 pub use d_engine_proto::common::Entry;
183 pub use d_engine_proto::common::EntryPayload;
184 pub use d_engine_proto::common::LogId;
185 pub use d_engine_proto::common::entry_payload;
186}
187
188/// Client protocol types
189pub mod client {
190 // Client write command types for custom business logic
191 pub use d_engine_proto::client::WriteCommand;
192 pub use d_engine_proto::client::write_command;
193}
194
195/// Server storage protocol types
196pub mod server_storage {
197 // Server storage protocol types (snapshots, replication)
198 pub use d_engine_proto::server::storage::SnapshotMetadata;
199}
200
201// ==================== Internal API (Hidden) ====================
202mod membership;
203mod network;
204mod utils;
205
206// ==================== Test Utilities ====================
207
208/// Standardized test suite for custom [`StateMachine`] implementations.
209///
210/// Enable the `__test_support` feature in your `[dev-dependencies]` to access this module:
211/// ```toml
212/// [dev-dependencies]
213/// d-engine = { version = "...", features = ["server", "__test_support"] }
214/// ```
215#[cfg(feature = "__test_support")]
216pub use d_engine_core::state_machine_test;
217
218/// Standardized test suite for custom [`StorageEngine`] implementations.
219///
220/// Enable the `__test_support` feature in your `[dev-dependencies]` to access this module:
221/// ```toml
222/// [dev-dependencies]
223/// d-engine = { version = "...", features = ["server", "__test_support"] }
224/// ```
225#[cfg(feature = "__test_support")]
226pub use d_engine_core::storage_engine_test;
227
228/// Test utilities for d-engine-server
229///
230/// This module is only available when running tests.
231///
232/// Contains mock implementations and test helpers.
233#[cfg(test)]
234#[doc(hidden)]
235pub(crate) mod test_utils;