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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use crate::app_state::*;
use crate::emitters::{EmitterInstance, EmitterManager, Emitters};
use crate::resources::{ResourceInstance, ResourceManager, Resources};
use crate::states::{StateInstance, StateManager, States};
use crate::system::{BoxedSystem, CallbackSystem, System, SystemFunc};
use crate::tracing::TracingOptions;
use miette::IntoDiagnostic;
use std::any::Any;
use std::mem;
use std::sync::Arc;
use tokio::sync::{RwLock, Semaphore};
use tokio::task;

pub type AppResult<T = ()> = miette::Result<T>;
pub type MainResult = miette::Result<()>;

#[derive(Debug, Default)]
pub enum Phase {
    #[default]
    Startup,
    Analyze,
    Execute,
    Shutdown,
}

#[derive(Debug)]
pub struct App {
    // Data
    emitters: EmitterManager,
    resources: ResourceManager,
    states: StateManager,

    // Systems
    startups: Vec<BoxedSystem>,
    analyzers: Vec<BoxedSystem>,
    executors: Vec<BoxedSystem>,
    shutdowns: Vec<BoxedSystem>,
}

impl App {
    /// Create a new application instance.
    #[allow(clippy::new_without_default)]
    pub fn new() -> App {
        let mut app = App {
            analyzers: vec![],
            emitters: EmitterManager::default(),
            executors: vec![],
            shutdowns: vec![],
            startups: vec![],
            resources: ResourceManager::default(),
            states: StateManager::default(),
        };
        app.startup(start_startup_phase);
        app.analyze(start_analyze_phase);
        app.execute(start_execute_phase);
        app.shutdown(start_shutdown_phase);
        app
    }

    /// Setup `miette` diagnostics by registering error and panic hooks.
    pub fn setup_diagnostics() {
        crate::diagnostics::setup_miette();
    }

    /// Setup `tracing` messages with default options.
    #[cfg(feature = "tracing")]
    pub fn setup_tracing() {
        Self::setup_tracing_with_options(TracingOptions::default())
    }

    /// Setup `tracing` messages with custom options.
    #[cfg(feature = "tracing")]
    pub fn setup_tracing_with_options(options: TracingOptions) {
        crate::tracing::setup_tracing(options);
    }

    /// Add a system function that runs during the startup phase.
    pub fn startup<S: SystemFunc + 'static>(&mut self, system: S) -> &mut Self {
        self.add_system(Phase::Startup, CallbackSystem::new(system))
    }

    /// Add a system function that runs during the analyze phase.
    pub fn analyze<S: SystemFunc + 'static>(&mut self, system: S) -> &mut Self {
        self.add_system(Phase::Analyze, CallbackSystem::new(system))
    }

    /// Add a system function that runs during the execute phase.
    pub fn execute<S: SystemFunc + 'static>(&mut self, system: S) -> &mut Self {
        self.add_system(Phase::Execute, CallbackSystem::new(system))
    }

    /// Add a system function that runs during the shutdown phase.
    pub fn shutdown<S: SystemFunc + 'static>(&mut self, system: S) -> &mut Self {
        self.add_system(Phase::Shutdown, CallbackSystem::new(system))
    }

    /// Add a system that runs during the specified phase.
    pub fn add_system<S: System + 'static>(&mut self, phase: Phase, system: S) -> &mut Self {
        match phase {
            Phase::Startup => {
                self.startups.push(Box::new(system));
            }
            Phase::Analyze => {
                self.analyzers.push(Box::new(system));
            }
            Phase::Execute => {
                self.executors.push(Box::new(system));
            }
            Phase::Shutdown => {
                self.shutdowns.push(Box::new(system));
            }
        };

        self
    }

    /// Add an event emitter instance to the application context.
    pub fn set_emitter<M: Any + Send + Sync + EmitterInstance>(
        &mut self,
        instance: M,
    ) -> &mut Self {
        self.emitters.set(instance);
        self
    }

    /// Add a resource instance to the application context.
    pub fn set_resource<R: Any + Send + Sync + ResourceInstance>(
        &mut self,
        instance: R,
    ) -> &mut Self {
        self.resources.set(instance);
        self
    }

    /// Add a state instance to the application context.
    pub fn set_state<S: Any + Send + Sync + StateInstance>(&mut self, instance: S) -> &mut Self {
        self.states.set(instance);
        self
    }

    /// Start the application and run all registered systems grouped into phases.
    pub async fn run(&mut self) -> miette::Result<StateManager> {
        let emitters = Arc::new(RwLock::new(mem::take(&mut self.emitters)));
        let resources = Arc::new(RwLock::new(mem::take(&mut self.resources)));
        let states = Arc::new(RwLock::new(mem::take(&mut self.states)));

        // Startup
        if let Err(error) = self
            .run_startup(states.clone(), resources.clone(), emitters.clone())
            .await
        {
            self.run_shutdown(states.clone(), resources.clone(), emitters.clone())
                .await?;

            return Err(error);
        }

        // Analyze
        if let Err(error) = self
            .run_analyze(states.clone(), resources.clone(), emitters.clone())
            .await
        {
            self.run_shutdown(states.clone(), resources.clone(), emitters.clone())
                .await?;

            return Err(error);
        }

        // Execute
        if let Err(error) = self
            .run_execute(states.clone(), resources.clone(), emitters.clone())
            .await
        {
            self.run_shutdown(states.clone(), resources.clone(), emitters.clone())
                .await?;

            return Err(error);
        }

        // Shutdown
        self.run_shutdown(states.clone(), resources.clone(), emitters.clone())
            .await?;

        let states = Arc::into_inner(states)
            .expect("Failed to acquire state before closing the application. This typically means that threads are still running that have not been awaited.").into_inner();

        Ok(states)
    }

    // Private

    async fn run_startup(
        &mut self,
        states: States,
        resources: Resources,
        emitters: Emitters,
    ) -> AppResult {
        let systems = mem::take(&mut self.startups);

        self.run_systems_in_serial(systems, states, resources, emitters)
            .await?;

        Ok(())
    }

    async fn run_analyze(
        &mut self,
        states: States,
        resources: Resources,
        emitters: Emitters,
    ) -> AppResult {
        let systems = mem::take(&mut self.analyzers);

        self.run_systems_in_parallel(systems, states, resources, emitters)
            .await?;

        Ok(())
    }

    async fn run_execute(
        &mut self,
        states: States,
        resources: Resources,
        emitters: Emitters,
    ) -> AppResult {
        let systems = mem::take(&mut self.executors);

        self.run_systems_in_parallel(systems, states, resources, emitters)
            .await?;

        Ok(())
    }

    async fn run_shutdown(
        &mut self,
        states: States,
        resources: Resources,
        emitters: Emitters,
    ) -> AppResult {
        let systems = mem::take(&mut self.shutdowns);

        self.run_systems_in_parallel(systems, states, resources, emitters)
            .await?;

        Ok(())
    }

    async fn run_systems_in_parallel(
        &self,
        systems: Vec<BoxedSystem>,
        states: States,
        resources: Resources,
        emitters: Emitters,
    ) -> AppResult {
        let mut futures = Vec::with_capacity(systems.len());
        let semaphore = Arc::new(Semaphore::new(num_cpus::get()));

        for system in systems {
            let states = Arc::clone(&states);
            let resources = Arc::clone(&resources);
            let emitters = Arc::clone(&emitters);
            let semaphore = Arc::clone(&semaphore);

            futures.push(task::spawn(async move {
                let permit = semaphore.acquire().await.into_diagnostic()?;
                let result = system.run(states, resources, emitters).await;
                drop(permit);
                result
            }));
        }

        for future in futures {
            future.await.into_diagnostic()??;
        }

        Ok(())
    }

    async fn run_systems_in_serial(
        &self,
        systems: Vec<BoxedSystem>,
        states: States,
        resources: Resources,
        emitters: Emitters,
    ) -> AppResult {
        for system in systems {
            let states = Arc::clone(&states);
            let resources = Arc::clone(&resources);
            let emitters = Arc::clone(&emitters);

            system.run(states, resources, emitters).await?;
        }

        Ok(())
    }
}