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
//! 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 dependecies import them.
#![allow(clippy::multiple_crate_versions)]

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 log::info;

pub mod config;
pub mod controller;
pub mod db;
pub mod error;
pub mod model;
/// Auto generated by diesel.
#[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) => panic!("Error reading configuration: {e}"),
    };

    env_logger::init();

    Config::init(&config).await;

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

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

    HttpServer::new(move || {
        App::new()
            .wrap(cors_configuration())
            .app_data(data.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: Pool) {
    tokio::spawn(cleanup_maps(pool.clone()));
    tokio::spawn(cleanup_layers(pool));
}