1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use std::sync::Arc;

use anyhow::Result;
use tokio::sync::mpsc;

use crate::core::common::logger::get_logger;

use super::{processor, App, Environment};

/// Notification to deliver to the application.
pub(super) enum Notify {
    RuntimeBlock(u64),
    RuntimeBlockDone,
    InitialRegistrationCompleted,
}

#[derive(Default)]
struct NotifyState {
    pending: bool,
    running: bool,
}

/// Application notifier task.
pub(super) struct Task<A: App> {
    imp: Option<Impl<A>>,
    tx: mpsc::Sender<Notify>,
}

impl<A> Task<A>
where
    A: App,
{
    /// Create an application notifier task.
    pub(super) fn new(state: Arc<processor::State<A>>, env: Environment<A>) -> Self {
        let (tx, rx) = mpsc::channel(16);

        let imp = Impl {
            state,
            env,
            logger: get_logger("modules/rofl/app/notifier"),
            notify: rx,
            notify_tx: tx.downgrade(),
        };

        Self { imp: Some(imp), tx }
    }

    /// Start the application notifier task.
    pub(super) fn start(&mut self) {
        if let Some(imp) = self.imp.take() {
            imp.start();
        }
    }

    /// Deliver a notification.
    pub(super) async fn notify(&self, notification: Notify) -> Result<()> {
        self.tx.send(notification).await?;
        Ok(())
    }
}

struct Impl<A: App> {
    state: Arc<processor::State<A>>,
    env: Environment<A>,
    logger: slog::Logger,

    notify: mpsc::Receiver<Notify>,
    notify_tx: mpsc::WeakSender<Notify>,
}

impl<A> Impl<A>
where
    A: App,
{
    /// Start the application notifier task.
    pub(super) fn start(self) {
        tokio::task::spawn(self.run());
    }

    /// Run the application notifier task.
    async fn run(mut self) {
        slog::info!(self.logger, "starting notifier task");

        // Pending notifications.
        let mut registered = false;
        let mut block = NotifyState::default();
        let mut last_round = 0;

        while let Some(notification) = self.notify.recv().await {
            match notification {
                Notify::RuntimeBlock(round) if registered => {
                    block.pending = true;
                    last_round = round;
                }
                Notify::RuntimeBlock(_) => continue, // Skip blocks before registration.
                Notify::RuntimeBlockDone => block.running = false,
                Notify::InitialRegistrationCompleted => registered = true,
            }

            // Don't do anything unless registered.
            if !registered {
                continue;
            }

            // Block notifications.
            if block.pending && !block.running {
                block.pending = false;
                block.running = true;

                let notify_tx = self.notify_tx.clone();
                let app = self.state.app.clone();
                let env = self.env.clone();

                tokio::spawn(async move {
                    app.on_runtime_block(env, last_round).await;
                    if let Some(tx) = notify_tx.upgrade() {
                        let _ = tx.send(Notify::RuntimeBlockDone).await;
                    }
                });
            }
        }

        slog::info!(self.logger, "notifier task stopped");
    }
}