aboutsummaryrefslogtreecommitdiff
path: root/crates/whirl_api/src/lib.rs
blob: d2f781177752e3e0dbdc9c64c8b2d21489aa4162 (plain) (blame)
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
// Copyleft (ɔ) 2021-2021 The Whirlsplash Collective
// SPDX-License-Identifier: GPL-3.0-only

//! The API, for external interaction.

#![feature(
  type_ascription,
  hash_set_entry,
  type_name_of_val,
  decl_macro,
  proc_macro_hygiene
)]
#![warn(rust_2018_idioms)]
#![recursion_limit = "128"]

#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;

use actix_web::web::resource;

mod routes;

pub struct Api;
impl Api {
  /// Begin handling connections on the web-server.
  pub async fn listen(
    tx: std::sync::mpsc::Sender<actix_web::dev::Server>,
    address: &str,
  ) -> std::io::Result<()> {
    let mut sys = actix_web::rt::System::new("api");

    let server = actix_web::HttpServer::new(|| {
      actix_web::App::new()
        .wrap(actix_cors::Cors::default().allow_any_origin())
        .service(resource("/").to(|| async { "Whirlsplash" }))
        .service(resource("/api/v1/statistics").to(routes::stats::statistics))
    })
    .bind(address)?
    .run();

    info!("http api now listening at {}", address);

    let _ = tx.send(server.clone());

    sys.block_on(server)
  }
}

pub fn make() -> tokio::task::JoinHandle<()> {
  // actix_web::rt::System::new("").block_on(rx.recv().unwrap().stop(true));

  tokio::spawn(async move {
    let _ = crate::Api::listen(
      std::sync::mpsc::channel().0,
      &*format!(
        "0.0.0.0:{}",
        whirl_config::Config::get().whirlsplash.api.port
      ),
    )
    .await;
  })
}