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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
mod api;
pub mod db;
mod indexer;
mod logging;
mod settings;

use crate::indexer::Indexer;
use anyhow::Context;
use chain_core::{packer::Codec, property::Deserialize};
use chain_impl_mockchain::block::Block;
use chain_network::grpc::watch::client::{
    BlockSubscription, Client, SyncMultiverseStream, TipSubscription,
};
use db::ExplorerDb;
use futures::stream::StreamExt;
use futures_util::{future, pin_mut, FutureExt, TryFutureExt};
use settings::Settings;
use thiserror::Error;
use tokio::{
    select,
    signal::ctrl_c,
    sync::{broadcast, oneshot},
};
use tracing::{error, span, Instrument, Level};

#[derive(Debug, Error)]
pub enum Error {
    #[error(transparent)]
    IndexerError(#[from] indexer::IndexerError),
    #[error(transparent)]
    SettingsError(#[from] settings::Error),
    #[error(transparent)]
    LoggingError(#[from] logging::Error),
    #[error("failed to bootstrap from node, reason {0}")]
    BootstrapError(#[from] BootstrapError),
    #[error(transparent)]
    Other(anyhow::Error),
    #[error(transparent)]
    UnrecoverableError(anyhow::Error),
}

#[derive(Debug, Error)]
pub enum BootstrapError {
    #[error(transparent)]
    DbError(db::error::ExplorerError),
    #[error("empty bootstrap stream")]
    EmptyStream,
}

#[derive(Clone)]
enum GlobalState {
    Bootstraping,
    Ready(Indexer),
    ShuttingDown,
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let (_log_guard, settings) = {
        let mut settings = Settings::load()?;
        let guard = settings.log_settings.take().unwrap().init_log()?;

        let init_span = span!(Level::TRACE, "task", kind = "init");
        let _enter = init_span.enter();
        tracing::info!("Starting explorer");

        (guard, settings)
    };

    let mut settings = Some(settings);

    let (state_tx, state_rx) = broadcast::channel(3);

    // this unwrap won't panic because the capacity is greater than 1
    state_tx.send(GlobalState::Bootstraping).unwrap();

    let (bootstrap, mut services) = {
        let settings = settings.take().unwrap();

        let mut client = Client::connect(settings.node.clone())
            .await
            .context("Couldn't establish connection with node")
            .map_err(Error::UnrecoverableError)?;

        let sync_stream = client
            .sync_multiverse(vec![])
            .await
            .context("Failed to establish bootstrap stream")
            .map_err(Error::UnrecoverableError)?;

        let block_events = client
            .block_subscription()
            .await
            .context("Failed to establish block subscription")
            .map_err(Error::UnrecoverableError)?;

        let tip_events = client
            .tip_subscription()
            .await
            .context("Failed to establish tip subscription")
            .map_err(Error::UnrecoverableError)?;

        let bootstrap = {
            let state_tx = state_tx.clone();

            tokio::spawn(
                async move {
                    let db = bootstrap(sync_stream).await?;

                    let msg = GlobalState::Ready(Indexer::new(db));

                    state_tx
                        .send(msg)
                        .context("failed to broadcast state")
                        .map_err(Error::Other)
                        .map(|_| ())
                }
                .instrument(span!(Level::INFO, "bootstrap task")),
            )
        };

        tracing::info!("starting subscriptions");

        let subscriptions = tokio::spawn(
            process_subscriptions(state_tx.subscribe(), block_events, tip_events)
                .instrument(span!(Level::INFO, "subscriptions")),
        );

        tracing::info!("starting rest task");

        let rest = tokio::spawn(
            async {
                rest_service(state_rx, settings).await;
                Ok(())
            }
            .instrument(span!(Level::INFO, "rest service")),
        );

        (bootstrap, vec![subscriptions, rest])
    };

    let interrupt_handler = tokio::spawn({
        let state_tx = state_tx.clone();

        async move {
            let mut state_rx = state_tx.subscribe();
            let ctrl_c = ctrl_c().fuse();
            pin_mut!(ctrl_c);

            loop {
                select! {
                    s = state_rx.recv() => {
                        if matches!(s.unwrap(), GlobalState::ShuttingDown) {
                            tracing::trace!("shutting down interrupt handler service");
                            break;
                        }
                    }
                    s = (&mut ctrl_c) => {
                        s.context("failed to set interrupt handler")
                            .map_err(Error::UnrecoverableError)?;

                        tracing::trace!("sending ShuttingDown event");

                        state_tx
                            .send(GlobalState::ShuttingDown)
                            .context("failed to send shutdown signal")
                            .map_err(Error::UnrecoverableError)?;

                        break;
                    }
                }
            }

            Ok::<(), Error>(())
        }
    });

    services.push(interrupt_handler);

    let (exit_status, remaining_services) = {
        let bootstrap_status = bootstrap.await;

        if bootstrap_status.is_ok() {
            let (status, _idx, rest) = future::select_all(services).await;
            (status, rest)
        } else {
            (bootstrap_status, services)
        }
    };

    tracing::debug!("sending shutdown event");

    let _ = state_tx.send(GlobalState::ShuttingDown);

    let exit_status = exit_status
        .map_err(|e| Error::UnrecoverableError(e.into()))
        .and_then(std::convert::identity);

    if let Err(error) = exit_status.as_ref() {
        tracing::error!(error = %error,"process finished with error");

        let _ = future::join_all(remaining_services).await;

        tracing::error!("finished joining on the rest");

        // TODO: map to custom error code
        std::process::exit(1);
    }

    Ok(())
}

async fn bootstrap(mut sync_stream: SyncMultiverseStream) -> Result<ExplorerDb, Error> {
    tracing::info!("starting bootstrap process");

    let mut db: Option<ExplorerDb> = None;

    // TODO: technically, blocks with the same length can be applied in parallel
    // but it is simpler to do it serially for now at least
    while let Some(block) = sync_stream.next().await {
        let bytes = block
            .context("failed to decode Block received through bootstrap subscription")
            .map_err(Error::UnrecoverableError)?;

        let mut codec = Codec::new(bytes.as_ref());

        let block = Block::deserialize(&mut codec)
            .context("failed to decode Block received through bootstrap subscription")
            .map_err(Error::UnrecoverableError)?;

        if let Some(ref db) = db {
            tracing::trace!(
                "applying block {:?} {:?}",
                block.header().hash(),
                block.header().chain_length()
            );
            db.apply_block(block)
                .await
                .map_err(BootstrapError::DbError)?;
        } else {
            db = Some(ExplorerDb::bootstrap(block).map_err(BootstrapError::DbError)?)
        }
    }

    tracing::info!("finish bootstrap process");

    db.ok_or(BootstrapError::EmptyStream).map_err(Into::into)
}

async fn rest_service(mut state: broadcast::Receiver<GlobalState>, settings: Settings) {
    tracing::info!("starting rest task, waiting for database to be ready");

    let (rest_shutdown, rest_shutdown_signal) = oneshot::channel();
    let (indexer_tx, indexer_rx) = oneshot::channel();

    tokio::spawn(async move {
        let mut indexer_tx = Some(indexer_tx);
        loop {
            match state.recv().await.unwrap() {
                GlobalState::Bootstraping => continue,
                GlobalState::Ready(i) => {
                    if let Some(indexer_tx) = indexer_tx.take() {
                        let _ = indexer_tx.send(i);
                    } else {
                        panic!("received ready event twice");
                    }
                }
                GlobalState::ShuttingDown => {
                    let _ = rest_shutdown.send(());
                    break;
                }
            }
        }
    });

    let db = indexer_rx.await.unwrap().db;

    let api = api::filter(
        db,
        crate::db::Settings {
            address_bech32_prefix: settings.address_bech32_prefix,
            query_depth_limit: settings.query_depth_limit,
            query_complexity_limit: settings.query_complexity_limit,
        },
    );

    let binding_address = settings.binding_address;
    let tls = settings.tls.clone();
    let cors = settings.cors.clone();

    tracing::info!("starting rest task, listening on {}", binding_address);

    api::setup_cors(api, binding_address, tls, cors, async {
        rest_shutdown_signal.await.unwrap()
    })
    .await;

    tracing::info!("rest task finished");
}

async fn handle_tip(raw_tip: chain_network::data::Header, indexer: Indexer) -> Result<(), Error> {
    let mut codec = Codec::new(raw_tip.as_bytes());
    let header = chain_impl_mockchain::block::Header::deserialize(&mut codec)
        .context("failed to decode tip header")
        .map_err(Error::Other)?;

    indexer.set_tip(header.hash()).await;

    Ok(())
}

async fn handle_block(
    raw_block: chain_network::data::Block,
    indexer: Indexer,
) -> Result<(), Error> {
    let mut codec = chain_core::packer::Codec::new(raw_block.as_bytes());
    let block = Block::deserialize(&mut codec)
        .context("Failed to deserialize block from block subscription")
        .map_err(Error::Other)?;

    indexer.apply_block(block).await?;

    Ok(())
}

async fn process_subscriptions(
    state: broadcast::Receiver<GlobalState>,
    blocks: BlockSubscription,
    tips: TipSubscription,
) -> Result<(), Error> {
    tracing::info!("start consuming subscriptions");

    let blocks = blocks.fuse();
    let tips = tips.fuse();

    let mut indexer = None;

    pin_mut!(blocks, tips, state);

    loop {
        let state = state
            .recv()
            .await
            .expect("state broadcast channel doesn't have enough capacity");

        match state {
            GlobalState::Bootstraping => continue,
            GlobalState::Ready(i) => {
                indexer.replace(i);
                break;
            }

            GlobalState::ShuttingDown => {
                return Ok(());
            }
        }
    }

    let indexer = indexer.unwrap();

    loop {
        select! {
            state = state.recv() => {
                let state = state.expect("state broadcast channel doesn't have enough capacity");

                tracing::trace!("got state message {:?}", state);

                match state {
                    GlobalState::ShuttingDown => {
                        break;
                    },
                    _ => unreachable!(),
                }
            },
            Some(block) = blocks.next() => {
                let indexer = indexer.clone();

                 async move {
                    future::ready(block)
                        .map_err(|e| Error::Other(e.into()))
                        .and_then(|block| handle_block(block, indexer))
                        .await
                }
                .instrument(span!(Level::INFO, "handle_block"))
                .await?;
            },
            Some(tip) = tips.next() => {
                tracing::debug!("received tip event");
                let indexer = indexer.clone();

                async {
                    handle_tip(
                        tip.context("Failed to receive tip from subscription")
                            .map_err(Error::Other)?,
                        indexer,
                    )
                    .await
                }
                .instrument(span!(Level::INFO, "handle_tip")).await?;
            },
            else => break,
        };
    }

    tracing::trace!("finishing subscriptions service");

    Ok(())
}

// TODO: implement Debug on Indexer so we can derive?
impl std::fmt::Debug for GlobalState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GlobalState::Bootstraping => write!(f, "Bootstrapping"),
            GlobalState::Ready(_) => write!(f, "Ready"),
            GlobalState::ShuttingDown => write!(f, "ShuttingDown"),
        }
    }
}