1
1
use std::time::Duration;
2

            
3
use bonsaidb::{
4
    core::pubsub::{PubSub, Subscriber},
5
    local::{
6
        config::{Builder, StorageConfiguration},
7
        Database,
8
    },
9
};
10
use tokio::time::sleep;
11

            
12
#[tokio::main]
13
1
async fn main() -> Result<(), bonsaidb::local::Error> {
14
    // This example is using a database with no collections, because PubSub is a
15
    // system independent of the data stored in the database.
16
19
    let db = Database::open::<()>(StorageConfiguration::new("pubsub.bonsaidb")).await?;
17

            
18
1
    let subscriber = db.create_subscriber().await?;
19
    // Subscribe for messages sent to the topic "pong"
20
1
    subscriber.subscribe_to("pong").await?;
21

            
22
    // Launch a task that sends out "ping" messages.
23
1
    tokio::spawn(pinger(db.clone()));
24
1
    // Launch a task that receives "ping" messages and sends "pong" responses.
25
1
    tokio::spawn(ponger(db.clone()));
26

            
27
    // Loop until a we receive a message letting us know when the ponger() has
28
    // no pings remaining.
29
    loop {
30
5
        let message = subscriber.receiver().recv_async().await?;
31
5
        let pings_remaining = message.payload::<usize>()?;
32
5
        println!(
33
5
            "<-- Received {}, pings remaining: {}",
34
5
            message.topic, pings_remaining
35
5
        );
36
5
        if pings_remaining == 0 {
37
1
            break;
38
4
        }
39
    }
40

            
41
1
    println!("Received all pongs.");
42
1

            
43
1
    Ok(())
44
1
}
45

            
46
1
async fn pinger<P: PubSub>(pubsub: P) -> Result<(), bonsaidb::local::Error> {
47
1
    let mut ping_count = 0u32;
48
    loop {
49
5
        ping_count += 1;
50
5
        println!("-> Sending ping {}", ping_count);
51
5
        pubsub.publish("ping", &ping_count).await?;
52
5
        sleep(Duration::from_millis(250)).await;
53
    }
54
}
55

            
56
1
async fn ponger<P: PubSub>(pubsub: P) -> Result<(), bonsaidb::local::Error> {
57
    const NUMBER_OF_PONGS: usize = 5;
58
1
    let subscriber = pubsub.create_subscriber().await?;
59
1
    subscriber.subscribe_to("ping").await?;
60
1
    let mut pings_remaining = NUMBER_OF_PONGS;
61
1

            
62
1
    println!(
63
1
        "Ponger started, waiting to respond to {} pings",
64
1
        pings_remaining
65
1
    );
66

            
67
6
    while pings_remaining > 0 {
68
5
        let message = subscriber.receiver().recv_async().await?;
69
5
        println!(
70
5
            "<- Received {}, id {}",
71
5
            message.topic,
72
5
            message.payload::<u32>()?
73
        );
74
5
        pings_remaining -= 1;
75
5
        pubsub.publish("pong", &pings_remaining).await?;
76
    }
77

            
78
1
    println!("Ponger finished.");
79
1

            
80
1
    Ok(())
81
1
}
82

            
83
1
#[test]
84
1
fn runs() {
85
1
    main().unwrap()
86
1
}