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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use crate::grpc::{book_summary, serve_grpc, AssetBooks, OrderbookAggregator};
use crate::http::start_http_service;
use common::{wrap_result, Book, Context, InnerMessage};
use gateways::{Gateway, WsUpdate};
use slog::{error, info, warn};
use std::collections::{HashMap, HashSet};

/// The Kollector is the main the main service
pub struct Kollector {
    pub context: Context<InnerMessage>,
    pub max_depth: usize,
    pub pairs: Vec<String>,
    gateways: HashMap<String, Box<dyn Gateway>>,
    books: HashMap<String, AssetBooks>,
    grpc: Option<OrderbookAggregator>,
}

impl Kollector {
    /// Create a new Kollector service
    ///
    /// # Arguments
    ///
    /// * pairs - comma separated list of crypto pairs
    /// * max_depth - maximum depth of order book to stream
    pub fn new(pairs: &str, max_depth: usize) -> Self {
        let pairs_: Vec<String> = HashSet::<String>::from_iter(pairs.split(',').map(String::from))
            .into_iter()
            .collect();
        Self {
            context: Context::<InnerMessage>::new("kollector", None),
            gateways: HashMap::new(),
            books: HashMap::new(),
            pairs: pairs_,
            grpc: None,
            max_depth,
        }
    }

    /// Spawn a gateway
    ///
    /// This method add a new gateway to the gateway's hashmap and
    /// start the websocket coroutine which connect to the exchange.
    ///
    /// This method should be called before running the service.
    pub fn spawn_gateway(&mut self, gateway: Box<dyn Gateway>) {
        gateway.setup();
        let ws = gateway.ws_consumer();
        self.gateways.insert(gateway.name().to_owned(), gateway);
        tokio::spawn(async move {
            let result = ws.run().await;
            wrap_result(&ws.context, result).await;
        });
    }

    /// Spawn the grpc server
    ///
    /// This method should be called before running the service
    pub fn spawn_grpc(&mut self) {
        let grpc = OrderbookAggregator::new(&self.pairs, self.max_depth);
        self.grpc = Some(grpc.clone());
        serve_grpc(grpc, &self.context);
    }

    /// Add web service
    ///
    /// Add a web service for prometheus metrics and k8s liveness probe
    pub fn spawn_http(&self) {
        let service = self.context.clone();
        tokio::spawn(async move {
            start_http_service(service).await;
        });
    }

    /// Add Ctrl-C handler
    pub fn handle_ctrlc(&self) {
        // handle shutdown
        let signal = self.context.clone();
        ctrlc::set_handler(move || {
            signal.sender.try_send(InnerMessage::Exit).unwrap();
        })
        .expect("Error setting Ctrl-C handler");
    }

    /// Main coroutine
    ///
    /// This coroutine runs the main part of the kollector service
    pub async fn run(&mut self) {
        let context = self.context.clone();

        for gateway in self.gateways.values_mut() {
            info!(
                context.logger,
                "subscribe to {} {:?}",
                gateway.name(),
                self.pairs
            );
            gateway.subscribe(&self.pairs);
        }

        info!(
            context.logger,
            "start {} with depth {}", context.name, self.max_depth
        );
        loop {
            match context.receiver.recv().await {
                Ok(InnerMessage::Failure) => {
                    warn!(context.logger, "exit main worker after failure");
                    return;
                }
                Ok(InnerMessage::Exit) => {
                    warn!(context.logger, "exit main worker");
                    return;
                }
                //
                Ok(InnerMessage::NewBookSnapshot(snapshot)) => {
                    match self.gateways.get_mut(&snapshot.name) {
                        Some(gw) => {
                            gw.request_snapshot();
                        }
                        None => {
                            error!(
                                context.logger,
                                "snapshot from an unknown gateway {}", snapshot.name
                            );
                        }
                    }
                }
                //
                Ok(InnerMessage::BookSnapshot(snapshot)) => {
                    let name = snapshot.name.to_owned();
                    match self.gateways.get_mut(&name) {
                        Some(gw) => {
                            if let Some(book) = gw.on_book_snapshot(snapshot) {
                                self.update_book(&name, book);
                            }
                        }
                        None => {
                            error!(context.logger, "snapshot from an unknown gateway {}", name);
                        }
                    }
                }
                // websocket payload
                Ok(InnerMessage::WsPayload(ws_payload)) => {
                    match self.gateways.get_mut(&ws_payload.name) {
                        Some(gw) => {
                            if let Some(update) = gw.on_websocket_message(ws_payload.value) {
                                match update {
                                    WsUpdate::Book(book) => {
                                        self.update_book(&ws_payload.name, book);
                                    }
                                }
                            }
                        }
                        None => {
                            error!(
                                context.logger,
                                "message from an unknown gateway {}", ws_payload.name
                            );
                        }
                    };
                }
                Ok(_) => {
                    // skip any other message
                }
                //
                Err(err) => {
                    error!(
                        context.logger,
                        "Main loop could not receive message: {}", err
                    );
                    return;
                }
            }
        }
    }

    fn update_book(&mut self, name: &str, book: Book) {
        let asset = book.asset.to_owned();
        let asset_books = self
            .books
            .entry(asset.to_owned())
            .or_insert_with(HashMap::new);
        asset_books.insert(name.to_owned(), book);
        let summary = book_summary(asset_books);
        // broadcast the summary to listeners (for now grpc only)
        if let Some(grpc) = &self.grpc {
            grpc.context.try_send((asset, summary));
        }
    }
}