diff --git a/Cargo.lock b/Cargo.lock index c81c21d..1c4a387 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2216,6 +2216,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "hello-single-latest" +version = "1.1.0" +dependencies = [ + "aimdb-core", + "aimdb-sync", + "aimdb-tokio-adapter", +] + [[package]] name = "hello-single-latest-async" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 34e7894..cc6cf7b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ members = [ "examples/weather-mesh-demo/weather-station-gamma", "examples/hello-mailbox", "examples/hello-mailbox-async", + "examples/hello-single-latest", "examples/hello-single-latest-async", "examples/hello-spmc-ring-async", "examples/readme-quickstart", diff --git a/Makefile b/Makefile index de54dc7..859f1d7 100644 --- a/Makefile +++ b/Makefile @@ -184,7 +184,7 @@ test: fmt: @printf "$(GREEN)Formatting code (workspace members only)...$(NC)\n" - @for pkg in aimdb-derive aimdb-data-contracts aimdb-core aimdb-client aimdb-embassy-adapter aimdb-tokio-adapter aimdb-wasm-adapter aimdb-sync aimdb-persistence aimdb-persistence-sqlite aimdb-mqtt-connector aimdb-knx-connector aimdb-ws-protocol aimdb-websocket-connector aimdb-uds-connector aimdb-serial-connector aimdb-tcp-connector aimdb-codegen aimdb-cli aimdb-mcp sync-api-demo tokio-mqtt-connector-demo embassy-mqtt-connector-demo tokio-knx-connector-demo embassy-knx-connector-demo embassy-serial-connector-demo embassy-bench-stm32h5 weather-mesh-common weather-hub weather-station-alpha weather-station-beta hello-mailbox hello-mailbox-async hello-single-latest-async hello-spmc-ring-async aimdb-bench; do \ + @for pkg in aimdb-derive aimdb-data-contracts aimdb-core aimdb-client aimdb-embassy-adapter aimdb-tokio-adapter aimdb-wasm-adapter aimdb-sync aimdb-persistence aimdb-persistence-sqlite aimdb-mqtt-connector aimdb-knx-connector aimdb-ws-protocol aimdb-websocket-connector aimdb-uds-connector aimdb-serial-connector aimdb-tcp-connector aimdb-codegen aimdb-cli aimdb-mcp sync-api-demo tokio-mqtt-connector-demo embassy-mqtt-connector-demo tokio-knx-connector-demo embassy-knx-connector-demo embassy-serial-connector-demo embassy-bench-stm32h5 weather-mesh-common weather-hub weather-station-alpha weather-station-beta hello-mailbox hello-mailbox-async hello-single-latest hello-single-latest-async hello-spmc-ring-async aimdb-bench; do \ printf "$(YELLOW) → Formatting $$pkg$(NC)\n"; \ cargo fmt -p $$pkg 2>/dev/null || true; \ done @@ -193,7 +193,7 @@ fmt: fmt-check: @printf "$(GREEN)Checking code formatting (workspace members only)...$(NC)\n" @FAILED=0; \ - for pkg in aimdb-derive aimdb-data-contracts aimdb-core aimdb-client aimdb-embassy-adapter aimdb-tokio-adapter aimdb-wasm-adapter aimdb-sync aimdb-persistence aimdb-persistence-sqlite aimdb-mqtt-connector aimdb-knx-connector aimdb-ws-protocol aimdb-websocket-connector aimdb-uds-connector aimdb-serial-connector aimdb-tcp-connector aimdb-codegen aimdb-cli aimdb-mcp sync-api-demo tokio-mqtt-connector-demo embassy-mqtt-connector-demo tokio-knx-connector-demo embassy-knx-connector-demo embassy-serial-connector-demo embassy-bench-stm32h5 weather-mesh-common weather-hub weather-station-alpha weather-station-beta hello-mailbox hello-mailbox-async hello-single-latest-async hello-spmc-ring-async aimdb-bench; do \ + for pkg in aimdb-derive aimdb-data-contracts aimdb-core aimdb-client aimdb-embassy-adapter aimdb-tokio-adapter aimdb-wasm-adapter aimdb-sync aimdb-persistence aimdb-persistence-sqlite aimdb-mqtt-connector aimdb-knx-connector aimdb-ws-protocol aimdb-websocket-connector aimdb-uds-connector aimdb-serial-connector aimdb-tcp-connector aimdb-codegen aimdb-cli aimdb-mcp sync-api-demo tokio-mqtt-connector-demo embassy-mqtt-connector-demo tokio-knx-connector-demo embassy-knx-connector-demo embassy-serial-connector-demo embassy-bench-stm32h5 weather-mesh-common weather-hub weather-station-alpha weather-station-beta hello-mailbox hello-mailbox-async hello-single-latest hello-single-latest-async hello-spmc-ring-async aimdb-bench; do \ printf "$(YELLOW) → Checking $$pkg$(NC)\n"; \ if ! cargo fmt -p $$pkg -- --check 2>&1; then \ printf "$(RED)❌ Formatting check failed for $$pkg$(NC)\n"; \ @@ -420,6 +420,8 @@ examples: cargo build --package hello-mailbox @printf "$(YELLOW) → Building hello-mailbox-async $(NC)\n" cargo build --package hello-mailbox-async + @printf "$(YELLOW) → Building hello-single-latest$(NC)\n" + cargo build --package hello-single-latest @printf "$(YELLOW) → Building hello-single-latest-async$(NC)\n" cargo build --package hello-single-latest-async @printf "$(YELLOW) → Building hello-spmc-ring-async$(NC)\n" diff --git a/README.md b/README.md index c5fdfd1..a037d32 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,7 @@ docker compose up | Buffer | Semantics | Use cases | | --- | --- | --- | | [**SPMC Ring**](examples/hello-spmc-ring-async) | Bounded stream with independent consumers | Sensor telemetry, event logs | -| [**SingleLatest**](examples/hello-single-latest-async) | Only the current value matters | Feature flags, config, UI state | +| [**SingleLatest**](examples/hello-single-latest) / [**SingleLatest async**](examples/hello-single-latest-async) | Only the current value matters | Feature flags, config, UI state | | [**Mailbox**](examples/hello-mailbox) / [**async Mailbox**](examples/hello-mailbox-async)| Latest instruction wins | Device commands, actuation, RPC | **One async API across runtimes.** Tokio, Embassy, WASM — swap the runtime adapter, keep the code. → [How the runtime abstraction works](https://aimdb.dev/blog/building-aimdb-one-async-api) diff --git a/examples/hello-single-latest/Cargo.toml b/examples/hello-single-latest/Cargo.toml new file mode 100644 index 0000000..b4f21ad --- /dev/null +++ b/examples/hello-single-latest/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "hello-single-latest" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "AimDB minimal sync example demonstrating SingleLatest buffer semantics" +publish = false + +[dependencies] +aimdb-core = { path = "../../aimdb-core", features = ["std"] } +aimdb-tokio-adapter = { path = "../../aimdb-tokio-adapter", features = [ + "tokio-runtime", +] } +aimdb-sync = { path = "../../aimdb-sync" } \ No newline at end of file diff --git a/examples/hello-single-latest/README.md b/examples/hello-single-latest/README.md new file mode 100644 index 0000000..2de9862 --- /dev/null +++ b/examples/hello-single-latest/README.md @@ -0,0 +1,48 @@ +# hello-single-latest: SingleLatest buffer demo + +The `SingleLatest` buffer stores the current value of a record. Each new write replaces the previous value, so subscribers read the latest value instead of replaying every intermediate update. This is useful for feature flags, configuration, UI state, and other records where stale values can be skipped. + +## How it works + +This example registers a `FeatureFlag` record with: +- `BufferCfg::SingleLatest` +- 2 async `.tap()` that observe rollout updates +- One of the tap observers is "fast", that doesn't wait between receives +- One of the tap observers is "slow", that waits for 2000 ms between receives + +The program attaches AimDB through its sync API, and publishes rollout updates using the sync, blocking `producer.set()` method. The taps are managed by AimDB's internal async runtime, so the application can use a synchronous `main` function without `async` or `#[tokio::main]`. + +The synchronous producer publishes one update per second. If multiple values are written before the tap reads them, SingleLatest retains only the newest value. In the example, while the fast tap reads the value in the single latest slot, the slow one skips overwritten intermediate values. + +## How to run + +From the workspace root, run: + +```bash +cargo run -p hello-single-latest +``` + +Expected output includes lines similar to: + +```text +=== AimDB SingleLatest Sync Demo === + +1. Building database and attaching for sync API... +2. Creating producer and producing values... +3. Producing rollout percentage values + Main: Setting FeatureFlag 0% +[info] [fast] rollout: 0% +[info] [slow] rollout: 0% + Main: Setting FeatureFlag 25% +[info] [fast] rollout: 25% + Main: Setting FeatureFlag 50% +[info] [fast] rollout: 50% +[info] [slow] rollout: 50% + Main: Setting FeatureFlag 75% +[info] [fast] rollout: 75% + Main: Setting FeatureFlag 100% +[info] [fast] rollout: 100% +[info] [slow] rollout: 100% +4. Shutting down... +Done. The sync producer published rollout updates observed by a SingleLatest tap. +``` \ No newline at end of file diff --git a/examples/hello-single-latest/src/main.rs b/examples/hello-single-latest/src/main.rs new file mode 100644 index 0000000..b553fcf --- /dev/null +++ b/examples/hello-single-latest/src/main.rs @@ -0,0 +1,110 @@ +//! # AimDB SingleLatest Sync Demo +//! This example demonstrates the `SingleLatest` buffer primitive using AimDB's synchronous API. +//! +//! ## What This Demo Shows +//! +//! 1. Building an AimDB instance with a typed record and 2 tap observers (slow and fast) +//! 2. Attaching the database to get a sync handle +//! 3. Creating a producer in sync context +//! 4. Setting values using blocking operations +//! 5. Clean shutdown with detach() + +use aimdb_core::{buffer::BufferCfg, AimDbBuilder, Consumer, RuntimeContext}; +use aimdb_sync::AimDbBuilderSyncExt; // Extension trait for .attach() +use aimdb_tokio_adapter::{TokioAdapter, TokioRecordRegistrarExt}; // Extension for .buffer() +use std::{sync::Arc, thread, time::Duration}; + +#[derive(Debug, Clone)] +struct FeatureFlag { + rollout_percent: f32, +} + +const KEY: &str = "config.checkout_rollout"; + +fn main() -> Result<(), Box> { + println!("=== AimDB SingleLatest Sync Demo ===\n"); + + // Step 1: Build the database and attach it for sync API usage + println!("1. Building database and attaching for sync API..."); + + let adapter = Arc::new(TokioAdapter); + let mut builder = AimDbBuilder::new().runtime(adapter); + + builder.configure::(KEY, |reg| { + // Configure a SingleLatest buffer + reg.buffer(BufferCfg::SingleLatest) + // Register 2 taps that observe rollout percentage values + .tap(rollout_observer_fast) + .tap(rollout_observer_slow); + }); + + // Build happens inside the runtime thread where Tokio context exists + let handle = builder.attach()?; + + // Step 2: Create a synchronous producer + println!("2. Creating producer and producing values..."); + + let producer = handle.producer::(KEY)?; + + // Step 3: Produce values + println!("3. Producing rollout percentage values"); + + for i in 0..5 { + let feature_flag = FeatureFlag { + rollout_percent: i as f32 * 25.0, + }; + println!( + " Main: Setting FeatureFlag {}%", + feature_flag.rollout_percent + ); + + // Use blocking send + producer.set(feature_flag)?; + + // Producer publishes new value every second + if i < 4 { + thread::sleep(Duration::from_millis(1000)); + } + } + + // Give the slow tap time to observe the final update before shutdown. Its read cycle is 2000ms, therefore wait a little longer than that. + thread::sleep(Duration::from_millis(2500)); + + // Step 4: Clean shutdown + // Detach the handle to gracefully shut down the runtime thread + + println!("4. Shutting down..."); + + handle.detach()?; + + println!("Done. The sync producer published rollout updates observed by fast and slow SingleLatest taps"); + + Ok(()) +} + +// A fast tap observer +async fn rollout_observer_fast(ctx: RuntimeContext, consumer: Consumer) { + let mut reader = consumer.subscribe(); + + while let Ok(feature_flag) = reader.recv().await { + ctx.log().info(&format!( + "[fast] rollout: {}%", + feature_flag.rollout_percent + )); + } +} + +// A slow tap observer +async fn rollout_observer_slow(ctx: RuntimeContext, consumer: Consumer) { + let mut reader = consumer.subscribe(); + let time = ctx.time(); + + while let Ok(feature_flag) = reader.recv().await { + ctx.log().info(&format!( + "[slow] rollout: {}%", + feature_flag.rollout_percent + )); + + time.sleep_millis(2000).await; + } +}