Skip to content

Commit 31a5fd7

Browse files
authored
docs: add async SingleLatest example (#112)
* docs: add async SingleLatest example * docs: refine SingleLatest example review notes Signed-off-by: Phung <nvphungdev@users.noreply.github.com> --------- Signed-off-by: Phung <nvphungdev@users.noreply.github.com> Co-authored-by: Phung <nvphungdev@users.noreply.github.com>
1 parent 71b0bfa commit 31a5fd7

7 files changed

Lines changed: 150 additions & 4 deletions

File tree

Cargo.lock

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ members = [
3232
"examples/weather-mesh-demo/weather-station-beta",
3333
"examples/weather-mesh-demo/weather-station-gamma",
3434
"examples/hello-mailbox",
35+
"examples/hello-single-latest-async",
3536
]
3637
exclude = ["_external"]
3738
resolver = "2"

Makefile

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ test:
135135

136136
fmt:
137137
@printf "$(GREEN)Formatting code (workspace members only)...$(NC)\n"
138-
@for pkg in aimdb-executor 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-codegen aimdb-cli aimdb-mcp sync-api-demo tokio-mqtt-connector-demo embassy-mqtt-connector-demo tokio-knx-connector-demo embassy-knx-connector-demo weather-mesh-common weather-hub weather-station-alpha weather-station-beta hello-mailbox; do \
138+
@for pkg in aimdb-executor 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-codegen aimdb-cli aimdb-mcp sync-api-demo tokio-mqtt-connector-demo embassy-mqtt-connector-demo tokio-knx-connector-demo embassy-knx-connector-demo weather-mesh-common weather-hub weather-station-alpha weather-station-beta hello-mailbox hello-single-latest-async; do \
139139
printf "$(YELLOW) → Formatting $$pkg$(NC)\n"; \
140140
cargo fmt -p $$pkg 2>/dev/null || true; \
141141
done
@@ -144,7 +144,7 @@ fmt:
144144
fmt-check:
145145
@printf "$(GREEN)Checking code formatting (workspace members only)...$(NC)\n"
146146
@FAILED=0; \
147-
for pkg in aimdb-executor 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-codegen aimdb-cli aimdb-mcp sync-api-demo tokio-mqtt-connector-demo embassy-mqtt-connector-demo tokio-knx-connector-demo embassy-knx-connector-demo weather-mesh-common weather-hub weather-station-alpha weather-station-beta hello-mailbox; do \
147+
for pkg in aimdb-executor 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-codegen aimdb-cli aimdb-mcp sync-api-demo tokio-mqtt-connector-demo embassy-mqtt-connector-demo tokio-knx-connector-demo embassy-knx-connector-demo weather-mesh-common weather-hub weather-station-alpha weather-station-beta hello-mailbox hello-single-latest-async; do \
148148
printf "$(YELLOW) → Checking $$pkg$(NC)\n"; \
149149
if ! cargo fmt -p $$pkg -- --check 2>&1; then \
150150
printf "$(RED)❌ Formatting check failed for $$pkg$(NC)\n"; \
@@ -297,6 +297,8 @@ examples:
297297
cargo build --package weather-station-gamma --target thumbv7em-none-eabihf
298298
@printf "$(YELLOW) → Building hello-mailbox (sync)$(NC)\n"
299299
cargo build --package hello-mailbox
300+
@printf "$(YELLOW) → Building hello-single-latest-async$(NC)\n"
301+
cargo build --package hello-single-latest-async
300302
@printf "$(GREEN)All examples built successfully!$(NC)\n"
301303

302304
## Security & Quality commands

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,8 @@ docker compose up
121121
| Buffer | Semantics | Use cases |
122122
| --- | --- | --- |
123123
| **SPMC Ring** | Bounded stream with independent consumers | Sensor telemetry, event logs |
124-
| **SingleLatest** | Only the current value matters | Feature flags, config, UI state |
125-
| [**Mailbox**](https://github.com/aimdb-dev/aimdb/tree/main/examples/hello-mailbox) | Latest instruction wins | Device commands, actuation, RPC |
124+
| [**SingleLatest**](examples/hello-single-latest-async) | Only the current value matters | Feature flags, config, UI state |
125+
| [**Mailbox**](examples/hello-mailbox) | Latest instruction wins | Device commands, actuation, RPC |
126126

127127
**Four capability traits** — opt-in, type-checked:
128128

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
[package]
2+
name = "hello-single-latest-async"
3+
version.workspace = true
4+
edition.workspace = true
5+
license.workspace = true
6+
description = "AimDB minimal async example demonstrating SingleLatest buffer semantics"
7+
publish = false
8+
9+
[dependencies]
10+
aimdb-core = { path = "../../aimdb-core", features = ["std"] }
11+
aimdb-tokio-adapter = { path = "../../aimdb-tokio-adapter", features = ["tokio-runtime"] }
12+
tokio = { workspace = true, features = ["time"] }
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# hello-single-latest-async: SingleLatest buffer demo
2+
3+
The `SingleLatest` buffer stores the current value for a record. New writes replace the previous value, so subscribers read the latest state instead of replaying every intermediate update. Use it for feature flags, configuration, UI state, or other records where stale values should be skipped.
4+
5+
## How it works
6+
7+
This example registers a `FeatureGate` record with:
8+
9+
- `BufferCfg::SingleLatest`
10+
- an async `.source()` that publishes rollout percentages
11+
- an async `.tap()` that observes the latest value whenever it changes
12+
13+
The source sends an initial burst of updates without waiting between writes. The tap prints the latest observed rollout, demonstrating that the buffer carries current state rather than a full event log.
14+
15+
## How to run
16+
17+
From the workspace root, run:
18+
19+
```bash
20+
cargo run -p hello-single-latest-async
21+
```
22+
23+
Expected output includes lines similar to:
24+
25+
```text
26+
=== hello-single-latest-async: SingleLatest buffer demo ===
27+
28+
source published rollout: 0%
29+
source published rollout: 10%
30+
source published rollout: 25%
31+
tap observed current rollout: 25%
32+
source published rollout: 50%
33+
tap observed current rollout: 50%
34+
source published rollout: 100%
35+
tap observed current rollout: 100%
36+
Done. SingleLatest keeps only the current value for each subscriber.
37+
```
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
use aimdb_core::{buffer::BufferCfg, AimDbBuilder, Consumer, Producer, RuntimeContext};
2+
use aimdb_tokio_adapter::{TokioAdapter, TokioRecordRegistrarExt};
3+
use std::sync::Arc;
4+
use std::time::Duration;
5+
6+
#[derive(Clone, Debug)]
7+
struct FeatureGate {
8+
rollout_percent: u8,
9+
}
10+
11+
#[tokio::main]
12+
async fn main() -> Result<(), Box<dyn std::error::Error>> {
13+
println!("=== hello-single-latest-async: SingleLatest buffer demo ===\n");
14+
15+
let adapter = Arc::new(TokioAdapter::new()?);
16+
let mut builder = AimDbBuilder::new().runtime(adapter);
17+
18+
builder.configure::<FeatureGate>("config.checkout_rollout", |reg| {
19+
reg.buffer(BufferCfg::SingleLatest)
20+
.source(rollout_source)
21+
.tap(rollout_observer);
22+
});
23+
24+
let _db = builder.build().await?;
25+
26+
tokio::time::sleep(Duration::from_millis(700)).await;
27+
println!("Done. SingleLatest keeps only the current value for each subscriber.");
28+
29+
Ok(())
30+
}
31+
32+
async fn rollout_source(
33+
ctx: RuntimeContext<TokioAdapter>,
34+
producer: Producer<FeatureGate, TokioAdapter>,
35+
) {
36+
let time = ctx.time();
37+
38+
time.sleep(time.millis(50)).await;
39+
40+
for rollout_percent in [0, 10, 25] {
41+
publish_rollout(&producer, rollout_percent).await;
42+
}
43+
44+
for rollout_percent in [50, 100] {
45+
time.sleep(time.millis(120)).await;
46+
publish_rollout(&producer, rollout_percent).await;
47+
}
48+
}
49+
50+
async fn publish_rollout(producer: &Producer<FeatureGate, TokioAdapter>, rollout_percent: u8) {
51+
let gate = FeatureGate { rollout_percent };
52+
match producer.produce(gate).await {
53+
Ok(()) => println!("source published rollout: {rollout_percent}%"),
54+
Err(err) => eprintln!("failed to publish rollout {rollout_percent}%: {err}"),
55+
}
56+
}
57+
58+
async fn rollout_observer(
59+
ctx: RuntimeContext<TokioAdapter>,
60+
consumer: Consumer<FeatureGate, TokioAdapter>,
61+
) {
62+
let Ok(mut reader) = consumer.subscribe() else {
63+
eprintln!("failed to subscribe to config.checkout_rollout");
64+
return;
65+
};
66+
let time = ctx.time();
67+
68+
let mut first = true;
69+
while let Ok(gate) = reader.recv().await {
70+
if first {
71+
first = false;
72+
if gate.rollout_percent != 0 {
73+
println!(
74+
" (rollouts before {}% were overwritten before the tap could read them - SingleLatest keeps only the latest)",
75+
gate.rollout_percent
76+
);
77+
}
78+
}
79+
println!("tap observed current rollout: {}%", gate.rollout_percent);
80+
if gate.rollout_percent == 100 {
81+
break;
82+
}
83+
time.sleep(time.millis(90)).await;
84+
}
85+
}

0 commit comments

Comments
 (0)