-
Notifications
You must be signed in to change notification settings - Fork 16
Feat: add an example for spmc ring buffer #181
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| [package] | ||
| name = "hello-spmc-ring-async" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
| license.workspace = true | ||
| description = "AimDB minimal example demonstrating async SPMC buffer" | ||
| publish = false | ||
|
|
||
| [dependencies] | ||
| aimdb-core = { path = "../../aimdb-core", features = ["std"] } | ||
| aimdb-tokio-adapter = { path = "../../aimdb-tokio-adapter", features = ["tokio-runtime"] } | ||
| tokio = { workspace = true, features = ["time"] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # hello-spmc-ring-async: async Spmc Ring buffer demo | ||
| The Spmc Ring buffer supports Single Producer - Multi Consumer pattern. It features a ring buffer with fixed capacity. Each consumer could read the full sequence at its own rate without waiting for consumption states of other consumers. | ||
|
|
||
| ## When to use | ||
| This Spmc Ring buffer demo is useful in a variety of scenarios where you need to broadcast messages to different types of consumers but you are not sure if one could lag behind others. | ||
|
|
||
| ## How it works | ||
| The Spmc buffer demo works by simulating: | ||
| - A producer generating a message at fixed interval (struct `Temperature`); | ||
| - A consumer/observer 01 consuming at a rate faster than producer's; | ||
| - A consumer/observer 02 consuming at a rate slower than producer's, and eventually lagging behind (messages dropped), as the ring size is small (10 slots); | ||
|
|
||
| ## How to run | ||
| From the workspace root, run: | ||
| ``` | ||
| cargo run -p hello-spmc-ring-async | ||
| ``` | ||
| **Expected output** | ||
| ``` | ||
| === hello-spmc-ring-async: SPMC ring buffer demo === | ||
|
|
||
| Ring size: 10 | ||
| Producer at rate 20.0 messages/sec | ||
| Observer 01 at rate 25.0 message/sec | ||
| Observer 02 at rate 6.7 message/sec | ||
|
|
||
|
|
||
| Observer 01: At 1783932208: -18 celcius | ||
| Observer 02: At 1783932208: -18 celcius | ||
| Observer 01: At 1783932208: -16 celcius | ||
| Observer 01: At 1783932208: -14 celcius | ||
| ... | ||
| Observer 02: At 1783932208: -2 celcius | ||
| Observer 01: At 1783932209: 30 celcius | ||
| Observer 01: At 1783932209: 32 celcius | ||
| Observer 01: At 1783932209: 34 celcius | ||
| Observer 02 lagged, dropped 2 | ||
| Observer 02: At 1783932209: 4 celcius | ||
| ... | ||
|
|
||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| use std::time::Duration; | ||
| use std::{fmt::Display, sync::Arc}; | ||
|
|
||
| use aimdb_core::{buffer::BufferCfg, AimDbBuilder, Producer, RuntimeContext}; | ||
| use aimdb_core::{Consumer, DbError}; | ||
| use aimdb_tokio_adapter::{TokioAdapter, TokioRecordRegistrarExt}; | ||
|
|
||
| #[derive(Debug, Clone, PartialEq)] | ||
| pub struct Temperature { | ||
| /// Temperature in degrees Celsius | ||
| pub celcius: f32, | ||
|
|
||
| /// Unix timestamp (milliseconds) | ||
| pub timestamp: u64, | ||
| } | ||
|
|
||
| impl Display for Temperature { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| write!(f, "At {}: {} celcius", self.timestamp, self.celcius) | ||
| } | ||
| } | ||
|
|
||
| // Main function | ||
| #[tokio::main] | ||
| async fn main() -> Result<(), DbError> { | ||
| println!("=== hello-spmc-ring-async: SPMC ring buffer demo ===\n"); | ||
| println!("Ring size: 10"); | ||
| println!("Producer at rate 20.0 messages/sec"); | ||
| println!("Observer 01 at rate 25.0 messages/sec"); | ||
| println!("Observer 02 at rate 6.7 messages/sec"); | ||
| println!("\n"); | ||
|
|
||
| // configuration | ||
| let adapter = Arc::new(TokioAdapter); | ||
| let mut builder = AimDbBuilder::new().runtime(adapter); | ||
|
|
||
| // Two observers consuming at different rates | ||
| builder.configure::<Temperature>("sensor.temp", |reg| { | ||
| reg.buffer(BufferCfg::SpmcRing { capacity: 10 }) | ||
| .source(rollout_source) | ||
| .tap(rollout_observer01) | ||
| .tap(rollout_observer02); | ||
| }); | ||
|
|
||
| let (_db, runner) = builder.build().await?; | ||
| tokio::spawn(runner.run()); | ||
| tokio::time::sleep(Duration::from_millis(6000)).await; | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| async fn rollout_source(ctx: RuntimeContext, producer: Producer<Temperature>) { | ||
| let time = ctx.time(); | ||
| let t0: f32 = -20.0; | ||
| for i in 0..40 { | ||
| time.sleep_millis(50).await; | ||
| // Read wall-clock time through the runtime abstraction rather than | ||
| // `SystemTime::now()`, so the example stays runtime/sim-friendly. | ||
| let timestamp = time.unix_time().map(|(secs, _)| secs).unwrap_or(0); | ||
| publich_rollout(&producer, t0 + (i as f32 + 1.0) * 2.0, timestamp).await; | ||
| } | ||
| } | ||
|
|
||
| async fn publich_rollout(producer: &Producer<Temperature>, t: f32, timestamp: u64) { | ||
| let temperature = Temperature { | ||
| celcius: t, | ||
| timestamp, | ||
| }; | ||
| producer.produce(temperature); | ||
| } | ||
|
|
||
| async fn rollout_observer01(ctx: RuntimeContext, consumer: Consumer<Temperature>) { | ||
| let mut reader = consumer.subscribe(); | ||
| let time = ctx.time(); | ||
|
|
||
| while let Ok(t) = reader.recv().await { | ||
| println!("Observer 01: {}", t); | ||
| time.sleep_millis(40).await; | ||
| } | ||
| } | ||
|
|
||
| async fn rollout_observer02(ctx: RuntimeContext, consumer: Consumer<Temperature>) { | ||
| let mut reader = consumer.subscribe(); | ||
| let time = ctx.time(); | ||
|
|
||
| // Consume at slower rate, must miss data | ||
| loop { | ||
| match reader.recv().await { | ||
| Ok(t) => { | ||
| println!("Observer 02: {}", t); | ||
| time.sleep_millis(150).await; | ||
| } | ||
| Err(DbError::BufferLagged { lag_count, .. }) => { | ||
| println!("Observer 02 lagged, dropped {lag_count}"); | ||
| } | ||
| Err(_) => break, | ||
| }; | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.