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
//! The backend of `PermaplanT`.

#![recursion_limit = "1024"]
// Enable all lints apart from clippy::restriction by default.
// See https://rust-lang.github.io/rust-clippy/master/index.html#blanket_clippy_restriction_lints for as to why restriction is not enabled.
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![warn(clippy::cargo)]
// Lints in clippy::restriction which seem useful.
#![warn(
    clippy::clone_on_ref_ptr,
    clippy::empty_structs_with_brackets,
    clippy::exit,
    clippy::expect_used,
    clippy::format_push_string,
    clippy::get_unwrap,
    clippy::if_then_some_else_none,
    clippy::indexing_slicing,
    clippy::integer_division,
    clippy::large_include_file,
    clippy::missing_docs_in_private_items,
    clippy::mixed_read_write_in_expression,
    clippy::multiple_inherent_impl,
    clippy::mutex_atomic,
    clippy::panic_in_result_fn,
    clippy::partial_pub_fields,
    clippy::print_stderr,
    clippy::print_stdout,
    clippy::rc_buffer,
    clippy::rc_mutex,
    clippy::rest_pat_in_fully_bound_structs,
    clippy::same_name_method,
    clippy::shadow_unrelated,
    clippy::str_to_string,
    clippy::string_to_string,
    clippy::suspicious_xor_used_as_pow,
    clippy::todo,
    clippy::try_err,
    clippy::unimplemented,
    clippy::unnecessary_self_imports,
    clippy::unneeded_field_pattern,
    clippy::unreachable,
    clippy::unseparated_literal_suffix,
    clippy::unwrap_in_result,
    clippy::unwrap_used,
    clippy::use_debug,
    clippy::verbose_file_reads
)]
// Cannot fix some errors because dependencies import them.
#![allow(clippy::multiple_crate_versions)]
// Clippy suggests lots of false "x.get(0)" => "x.first()"
#![allow(clippy::get_first)]
// We often want the same name per module (for instance every enum).
#![allow(clippy::module_name_repetitions)]

use actix_cors::Cors;
use actix_web::{http, middleware::Logger, App, HttpServer};
use config::{api_doc, auth::Config, routes};
use db::{
    connection::Pool,
    cronjobs::{cleanup_layers, cleanup_maps},
};
use std::sync::Arc;

pub mod config;
pub mod controller;
pub mod db;
pub mod error;
pub mod keycloak_api;
pub mod model;
/// Auto generated by diesel.
#[allow(clippy::wildcard_imports)]
#[allow(clippy::missing_docs_in_private_items)]
pub mod schema;
pub mod service;
pub mod sse;
#[cfg(test)]
pub mod test;

/// Main function.
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let config = match config::app::Config::from_env() {
        Ok(config) => config,
        Err(e) => {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Error reading configuration: {e}"),
            ));
        }
    };

    env_logger::init();

    log::info!("Configuration loaded: {:#?}", config);

    Config::init(&config).await;

    log::info!(
        "Starting server on {}:{}",
        config.bind_address.0,
        config.bind_address.1
    );

    let data_init = config::data::init(&config);
    let pool = data_init.pool.clone().into_inner();
    start_cronjobs(pool);

    HttpServer::new(move || {
        App::new()
            .wrap(cors_configuration())
            .app_data(data_init.pool.clone())
            .app_data(data_init.broadcaster.clone())
            .app_data(data_init.http_client.clone())
            .app_data(data_init.keycloak_api.clone())
            .configure(routes::config)
            .configure(api_doc::config)
            .wrap(Logger::default())
    })
    .shutdown_timeout(5)
    .bind(config.bind_address)?
    .run()
    .await
}

/// Create a CORS configuration for the server.
fn cors_configuration() -> Cors {
    Cors::default()
        .allowed_origin("http://localhost:5173")
        .allowed_origin("https://mr.permaplant.net")
        .allowed_origin("https://dev.permaplant.net")
        .allowed_origin("https://master.permaplant.net")
        .allowed_origin("https://www.permaplant.net")
        .allowed_origin("https://cloud.permaplant.net")
        .allowed_methods(vec!["GET", "POST", "PUT", "PATCH", "DELETE"])
        .allowed_headers(vec![
            http::header::AUTHORIZATION,
            http::header::ACCEPT,
            http::header::CONTENT_TYPE,
        ])
        .max_age(3600)
}

/// Start all scheduled jobs that get run in the backend.
fn start_cronjobs(pool: Arc<Pool>) {
    tokio::spawn(cleanup_maps(Arc::clone(&pool)));
    tokio::spawn(cleanup_layers(pool));
}