From 79351f36cc5254af78b5109bd487e2844f543db3 Mon Sep 17 00:00:00 2001 From: harunugurlu Date: Wed, 15 Jul 2026 17:38:10 +0300 Subject: [PATCH 1/3] add hello-single-latest sync example --- Cargo.lock | 10 +++ Cargo.toml | 1 + Makefile | 6 +- README.md | 2 +- examples/hello-single-latest/Cargo.toml | 17 +++++ examples/hello-single-latest/README.md | 43 +++++++++++ examples/hello-single-latest/src/main.rs | 90 ++++++++++++++++++++++++ 7 files changed, 166 insertions(+), 3 deletions(-) create mode 100644 examples/hello-single-latest/Cargo.toml create mode 100644 examples/hello-single-latest/README.md create mode 100644 examples/hello-single-latest/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 28c8132..d14be68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2200,6 +2200,16 @@ dependencies = [ "tokio", ] +[[package]] +name = "hello-single-latest" +version = "1.1.0" +dependencies = [ + "aimdb-core", + "aimdb-sync", + "aimdb-tokio-adapter", + "tokio", +] + [[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 2b76464..0a7b802 100644 --- a/Makefile +++ b/Makefile @@ -182,7 +182,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 @@ -191,7 +191,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"; \ @@ -416,6 +416,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..62bff3b --- /dev/null +++ b/examples/hello-single-latest/Cargo.toml @@ -0,0 +1,17 @@ +[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" } + +# Runtime for initialization +tokio = { workspace = true, features = ["time"] } \ 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..1a67a40 --- /dev/null +++ b/examples/hello-single-latest/README.md @@ -0,0 +1,43 @@ +# hello-single-latest: SingleLatest buffer demo + +The `SingleLatest` buffer stores the current value of a record. Each new writes replace 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` +- an async `.tap()` that observes rollout updates + +The program attaches AimDB through its sync API, and publishes rollout updates using the sync, blocking `producer.set()` method. The tap is 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. + +## How to run + +From the workspace root, run: + +```bash +cargo run -p hello-single-latest-async +``` + +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% +Current rollout percentage: 0% + Main: Setting FeatureFlag 25% +Current rollout percentage: 25% + Main: Setting FeatureFlag 50% +Current rollout percentage: 50% + Main: Setting FeatureFlag 75% +Current rollout percentage: 75% + Main: Setting FeatureFlag 100% +Current rollout percentage: 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..4a0e140 --- /dev/null +++ b/examples/hello-single-latest/src/main.rs @@ -0,0 +1,90 @@ +//! # 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 a tap observer +//! 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}; +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 a tap that observes rollout percentage values + .tap(|_ctx, consumer| async move { + let mut reader = consumer.subscribe(); + while let Ok(feature_flag) = reader.recv().await { + println!( + "Current rollout percentage: {}%", + feature_flag.rollout_percent + ); + } + }); + }); + + // 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_secs(1)); + } + } + + // Give the tap time to observe the final update before shutdown. + thread::sleep(Duration::from_millis(50)); + + // 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 a SingleLatest tap."); + + Ok(()) +} From 6b188bbd87570439eb6955837b2f6c572f40c207 Mon Sep 17 00:00:00 2001 From: harunugurlu Date: Wed, 15 Jul 2026 21:43:31 +0300 Subject: [PATCH 2/3] update sinle latest example to demonstrate SingleLatest with slow and fast taps, fix incorrect cargo run command in the single latest example README --- examples/hello-single-latest/README.md | 25 +++++++----- examples/hello-single-latest/src/main.rs | 52 ++++++++++++++++-------- 2 files changed, 51 insertions(+), 26 deletions(-) diff --git a/examples/hello-single-latest/README.md b/examples/hello-single-latest/README.md index 1a67a40..2de9862 100644 --- a/examples/hello-single-latest/README.md +++ b/examples/hello-single-latest/README.md @@ -1,23 +1,25 @@ # hello-single-latest: SingleLatest buffer demo -The `SingleLatest` buffer stores the current value of a record. Each new writes replace 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. +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` -- an async `.tap()` that observes rollout updates +- 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 tap is managed by AimDB's internal async runtime, so the application can use a synchronous `main` function without `async` or `#[tokio::main]`. +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. +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-async +cargo run -p hello-single-latest ``` Expected output includes lines similar to: @@ -29,15 +31,18 @@ Expected output includes lines similar to: 2. Creating producer and producing values... 3. Producing rollout percentage values Main: Setting FeatureFlag 0% -Current rollout percentage: 0% +[info] [fast] rollout: 0% +[info] [slow] rollout: 0% Main: Setting FeatureFlag 25% -Current rollout percentage: 25% +[info] [fast] rollout: 25% Main: Setting FeatureFlag 50% -Current rollout percentage: 50% +[info] [fast] rollout: 50% +[info] [slow] rollout: 50% Main: Setting FeatureFlag 75% -Current rollout percentage: 75% +[info] [fast] rollout: 75% Main: Setting FeatureFlag 100% -Current rollout percentage: 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 index 4a0e140..7eabcac 100644 --- a/examples/hello-single-latest/src/main.rs +++ b/examples/hello-single-latest/src/main.rs @@ -3,13 +3,13 @@ //! //! ## What This Demo Shows //! -//! 1. Building an AimDB instance with a typed record and a tap observer +//! 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}; +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}; @@ -33,16 +33,9 @@ fn main() -> Result<(), Box> { builder.configure::(KEY, |reg| { // Configure a SingleLatest buffer reg.buffer(BufferCfg::SingleLatest) - // Register a tap that observes rollout percentage values - .tap(|_ctx, consumer| async move { - let mut reader = consumer.subscribe(); - while let Ok(feature_flag) = reader.recv().await { - println!( - "Current rollout percentage: {}%", - feature_flag.rollout_percent - ); - } - }); + // 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 @@ -70,12 +63,12 @@ fn main() -> Result<(), Box> { // Producer publishes new value every second if i < 4 { - thread::sleep(Duration::from_secs(1)); + thread::sleep(Duration::from_millis(1000)); } } - // Give the tap time to observe the final update before shutdown. - thread::sleep(Duration::from_millis(50)); + // Give the slow tap time to observe the final update before shutdown. + thread::sleep(Duration::from_millis(1000)); // Step 4: Clean shutdown // Detach the handle to gracefully shut down the runtime thread @@ -84,7 +77,34 @@ fn main() -> Result<(), Box> { handle.detach()?; - println!("Done. The sync producer published rollout updates observed by a SingleLatest tap."); + 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; + } +} From 3e21adaed6306099cca19e98a66e6bf6d87e167f Mon Sep 17 00:00:00 2001 From: harunugurlu Date: Thu, 16 Jul 2026 00:24:26 +0300 Subject: [PATCH 3/3] fix: adjust sleep duration for slow tap observation in hello-single-latest example and update the Cargo.toml to remove unused tokio dependency --- Cargo.lock | 1 - examples/hello-single-latest/Cargo.toml | 5 +---- examples/hello-single-latest/src/main.rs | 4 ++-- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bfe0168..1c4a387 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2223,7 +2223,6 @@ dependencies = [ "aimdb-core", "aimdb-sync", "aimdb-tokio-adapter", - "tokio", ] [[package]] diff --git a/examples/hello-single-latest/Cargo.toml b/examples/hello-single-latest/Cargo.toml index 62bff3b..b4f21ad 100644 --- a/examples/hello-single-latest/Cargo.toml +++ b/examples/hello-single-latest/Cargo.toml @@ -11,7 +11,4 @@ aimdb-core = { path = "../../aimdb-core", features = ["std"] } aimdb-tokio-adapter = { path = "../../aimdb-tokio-adapter", features = [ "tokio-runtime", ] } -aimdb-sync = { path = "../../aimdb-sync" } - -# Runtime for initialization -tokio = { workspace = true, features = ["time"] } \ No newline at end of file +aimdb-sync = { path = "../../aimdb-sync" } \ No newline at end of file diff --git a/examples/hello-single-latest/src/main.rs b/examples/hello-single-latest/src/main.rs index 7eabcac..b553fcf 100644 --- a/examples/hello-single-latest/src/main.rs +++ b/examples/hello-single-latest/src/main.rs @@ -67,8 +67,8 @@ fn main() -> Result<(), Box> { } } - // Give the slow tap time to observe the final update before shutdown. - 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