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
use std::path::PathBuf;

use axum::async_trait;
use color_eyre::owo_colors::OwoColorize;
use colored::Colorize;

use crate::application::{container, Container};
use crate::contracts::Configuration;
use crate::Result;
use crate::{app, config, env};

#[async_trait]
pub trait Application: Sync + Send {
    fn logo() -> &'static str {
        r"
░░      ░░░  ░░░░  ░░  ░░░░  ░░   ░░░  ░
▒  ▒▒▒▒  ▒▒▒  ▒▒  ▒▒▒  ▒▒▒▒  ▒▒    ▒▒  ▒
▓  ▓▓▓▓  ▓▓▓▓    ▓▓▓▓  ▓▓▓▓  ▓▓  ▓  ▓  ▓
█        █████  █████  ████  ██  ██    █
█  ████  █████  ██████      ███  ███   █
"
    }

    fn name() -> &'static str {
        env!("CARGO_CRATE_NAME")
    }

    fn version() -> &'static str {
        env!("CARGO_PKG_VERSION")
    }

    fn base_path() -> PathBuf {
        env("CARGO_MANIFEST_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| {
                std::env::current_dir()
                    .expect("project directory does not exist or permissions are insufficient")
            })
    }

    #[cfg(any(feature = "http1", feature = "http2"))]
    fn with_routing() -> axum::Router {
        axum::Router::new()
            .merge(crate::http::Router::group(Box::new(|mut router| {
                // without middleware

                router.route("/", axum::routing::get(|| async { "hello,ayun" }));
                router
            })))
            .merge(crate::http::Router::group(Box::new(|mut router| {
                // with middleware

                router
                    .with_global_middlewares()
                    .route("/ping", axum::routing::get(|| async { "pong" }))
                    .route("/pong", axum::routing::get(|| async { "ping" }));

                router
            })))
    }

    #[cfg(feature = "schedule")]
    fn with_schedule() -> Result<crate::support::scheduling::Schedule> {
        use crate::support::scheduling::Task;

        let mut schedule = crate::support::scheduling::Schedule::default();

        schedule.add(Task::foreground("0/1 * * * * *", || {
            tracing::info!("task: 0/1 * * * * *")
        })?);

        schedule.add(Task::foreground("0/5 * * * * *", || {
            tracing::info!("task: 0/5 * * * * *")
        })?);

        schedule.add(Task::background("0/10 * * * * *", || {
            Box::pin(async { tracing::info!("async task: 0/10 * * * * *") })
        })?);

        Ok(schedule)
    }

    fn register() -> Container {
        let mut container = Container::default();

        container.register::<Self, crate::support::facades::Path>();
        container.register::<Self, crate::support::facades::Environment>();
        container.register::<Self, crate::support::facades::Config>();
        container.register::<Self, crate::support::facades::Logger>();
        #[cfg(feature = "metrics")]
        container.register::<Self, crate::support::facades::Metrics>();
        #[cfg(any(
            feature = "http1",
            feature = "http2",
            feature = "database",
            feature = "redis"
        ))]
        container.register::<Self, crate::support::facades::Runtime>();
        #[cfg(feature = "database")]
        container.register::<Self, crate::support::facades::Database>();
        #[cfg(feature = "redis")]
        container.register::<Self, crate::support::facades::Redis>();

        container
    }

    fn boot() -> Result<()> {
        let _enter = app::<crate::support::facades::Logger>().map(|span| span.enter());

        for (scope, name) in container().instances() {
            tracing::info!("[{}] `{}` successfully boot.", scope, name);
        }

        println!("{}", Self::logo().cyan());

        let workspace = Self::base_path().to_string_lossy().to_string();
        let environment =
            app::<crate::support::facades::Environment>().map(|environment| environment.is())?;

        let source = app::<crate::support::facades::Config>()?
            .source()
            .replace(&workspace, "");
        let level = config::<crate::enums::config::Logger>("log")
            .unwrap_or_default()
            .level;

        println!("environment: {}", environment.green().bold());
        println!("     config: {}", source.yellow());
        println!("     logger: {}", level.green());
        println!();

        // scheduler
        #[cfg(feature = "schedule")]
        crate::support::scheduling::run::<Self>()?;

        // http server
        #[cfg(any(feature = "http1", feature = "http2"))]
        {
            let runtime = app::<crate::support::facades::Runtime>()?;

            let config = config::<crate::enums::config::Server>("server").unwrap_or_default();

            println!("server listening on {}", config.uri.green());

            runtime.block_on(crate::http::server::<Self>(config))?;
        }

        Ok(())
    }
}