summaryrefslogtreecommitdiffstats
path: root/crates/auth/src/main.rs
blob: 72f991f19fa5c79425a6c51b537eaeaf1a6b7495 (plain)
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
mod auth;
mod client;
mod cnfg;
mod error;
mod server;
mod state;

use std::net::{Ipv6Addr, SocketAddr};

use clap::Parser;
use reqwest::header::CONTENT_TYPE;
use sellershut_core::auth::{AUTH_FILE_DESCRIPTOR_SET, auth_server::AuthServer};
use stack_up::{Configuration, Services, tracing::Tracing};
use tokio::{signal, task::AbortHandle};
use tonic::service::Routes;
use tower::{make::Shared, steer::Steer};
use tracing::{info, trace};

use crate::{
    error::AppError,
    server::{grpc::interceptor::MyInterceptor, routes::authorised::AuthRequest},
    state::AppState,
};

/// auth-service
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// Path to config file
    #[arg(short, long)]
    config_file: Option<std::path::PathBuf>,
}

#[tokio::main]
async fn main() -> Result<(), AppError> {
    let args = Args::parse();
    let config = include_str!("../auth.toml");

    let mut config = config::Config::builder()
        .add_source(config::File::from_str(config, config::FileFormat::Toml))
        .add_source(
            config::Environment::with_prefix("APP")
                .separator("__")
                .convert_case(config::Case::Kebab),
        );

    if let Some(cf) = args.config_file.as_ref().and_then(|v| v.to_str()) {
        config = config.add_source(config::File::new(cf, config::FileFormat::Toml));
    };

    let mut config: Configuration = config.build()?.try_deserialize()?;
    config.application.name = env!("CARGO_CRATE_NAME").into();
    config.application.version = env!("CARGO_PKG_VERSION").into();

    let _tracing = Tracing::builder().build(&config.monitoring);

    let services = Services::builder()
        .postgres(&config.database)
        .await
        .inspect_err(|e| tracing::error!("database: {e}"))?
        .build();

    trace!("running migrations");
    sqlx::migrate!("./migrations")
        .run(&services.postgres)
        .await?;

    let (state, deletion_task) = AppState::create(services, &config).await?;

    let addr = SocketAddr::from((Ipv6Addr::UNSPECIFIED, config.application.port));

    let listener = tokio::net::TcpListener::bind(addr).await?;
    info!(port = addr.port(), "serving api");

    let service = AuthServer::with_interceptor(state.clone(), MyInterceptor);
    let auth_reflector = tonic_reflection::server::Builder::configure()
        .register_encoded_file_descriptor_set(AUTH_FILE_DESCRIPTOR_SET)
        .build_v1()?;

    let grpc_server = Routes::new(service)
        .add_service(auth_reflector)
        .into_axum_router();

    let service = Steer::new(
        vec![server::router(state), grpc_server],
        |req: &axum::extract::Request, _services: &[_]| {
            if req
                .headers()
                .get(CONTENT_TYPE)
                .map(|content_type| content_type.as_bytes())
                .filter(|content_type| content_type.starts_with(b"application/grpc"))
                .is_some()
            {
                // grpc service
                1
            } else {
                // http service
                0
            }
        },
    );

    axum::serve(listener, Shared::new(service))
        .with_graceful_shutdown(shutdown_signal(deletion_task.abort_handle()))
        .await?;

    deletion_task.await??;

    Ok(())
}

async fn shutdown_signal(deletion_task_abort_handle: AbortHandle) {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => { deletion_task_abort_handle.abort() },
        _ = terminate => { deletion_task_abort_handle.abort() },
    }
}