Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 4 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"; \
Expand Down Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
17 changes: 17 additions & 0 deletions examples/hello-single-latest/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"] }
Comment thread
harunugurlu marked this conversation as resolved.
Outdated
48 changes: 48 additions & 0 deletions examples/hello-single-latest/README.md
Original file line number Diff line number Diff line change
@@ -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.
```
110 changes: 110 additions & 0 deletions examples/hello-single-latest/src/main.rs
Original file line number Diff line number Diff line change
@@ -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<dyn std::error::Error>> {
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::<FeatureFlag>(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::<FeatureFlag>(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.
thread::sleep(Duration::from_millis(1000));
Comment thread
harunugurlu marked this conversation as resolved.
Outdated

// 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<FeatureFlag>) {
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<FeatureFlag>) {
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;
}
}