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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
mod backend_compiling_server;
mod dev_server;
mod frontend_dev_server;

pub mod controller;
use cargo_metadata::CompilerMessage;
use cargo_toml::Manifest;
use serde::Serialize;
use serde_json::json;
mod endpoints;
use crate::util::net::find_free_port;
use async_priority_channel as priority;
pub use endpoints::*;
use std::iter::FromIterator;
use std::path::PathBuf;
use std::process::exit;
use std::sync::Arc;
use tokio::sync::Mutex;
use watchexec::event::{Event, Priority, Tag};
use watchexec::signal::source::worker;
use watchexec::signal::source::MainSignal;

#[cfg(windows)]
const NPM: &str = "npm.cmd";

#[cfg(not(windows))]
const NPM: &str = "npm";

pub async fn vitejs_ping_down() {
    let port = std::env::var("DEV_SERVER_PORT");
    if port.is_err() {
        return;
    }
    let port = port.unwrap();

    let url = format!("http://localhost:{port}/vitejs-down");

    // send event to dev server that the backend is up!
    match reqwest::get(url).await {
        Ok(_) => {}
        Err(_) => {
            println!("WARNING: Could not inform dev server that vitejs is down.");
        }
    };
}

pub async fn vitejs_ping_up() {
    let port = std::env::var("DEV_SERVER_PORT");
    if port.is_err() {
        return;
    }
    let port = port.unwrap();

    let url = format!("http://localhost:{port}/vitejs-up");

    // send event to dev server that the backend is up!
    match reqwest::get(url).await {
        Ok(_) => {}
        Err(_) => {
            println!("WARNING: Could not inform dev server that vitejs is up.");
        }
    };
}

pub async fn setup_development() {
    let port = std::env::var("DEV_SERVER_PORT");
    if port.is_err() {
        return;
    }
    let port = port.unwrap();

    let url = format!("http://localhost:{port}/backend-up");

    // send event to dev server that the backend is up!
    match reqwest::get(url).await {
        Ok(_) => {}
        Err(_) => {
            println!("WARNING: Could not inform dev server of presence.");
        }
    };
}

#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum DevServerEvent {
    /*
        These events are internal: they shouldn't be used to communicate with the web browser client
    */
    /// sent when Ctrl+C or similar signals are sent to the dev server parent process
    SHUTDOWN, // related to external event: "BackendStatus"
    /// sent once when the backend compiles successfully and more when files in the migrations/ directory change
    CHECK_MIGRATIONS, // related to external event: "PendingMigrations"

    /*
        These events are external: they are sent to the web browser client
    */
    PendingMigrations(bool, Vec<CreateRustAppMigration>),
    MigrationResponse(bool, Option<String>),
    FeaturesList(Vec<String>),
    ViteJSStatus(bool),
    BackendCompiling(bool),
    BackendRestarting(bool),
    BackendStatus(bool),
    CompileSuccess(bool),
    CompileMessages(Vec<CompilerMessage>),
}

#[derive(Serialize, Debug, Clone)]
pub enum MigrationStatus {
    Applied,
    Pending,
    AppliedButMissingLocally,
    Unknown,
}

#[derive(Serialize, Debug, Clone)]
pub struct CreateRustAppMigration {
    name: String,
    version: String,
    status: MigrationStatus,
}

impl DevServerEvent {
    pub fn json(self) -> String {
        match self {
            DevServerEvent::CHECK_MIGRATIONS => json!({
                "type": "_",
            })
            .to_string(),
            DevServerEvent::PendingMigrations(migrations_pending, migrations) => json!({
                "type": "migrationsPending",
                "status": migrations_pending,
                "migrations": migrations
            })
            .to_string(),
            DevServerEvent::MigrationResponse(success, error_message) => json!({
                "type": "migrateResponse",
                "status": success,
                "error": error_message,
            })
            .to_string(),
            DevServerEvent::FeaturesList(list) => json!({
                "type": "featuresList",
                "features": list
            })
            .to_string(),
            DevServerEvent::ViteJSStatus(b) => json!({
                "type": "viteStatus",
                "status": b
            })
            .to_string(),
            DevServerEvent::CompileSuccess(b) => json!({
                "type": "compileStatus",
                "compiled": b
            })
            .to_string(),
            DevServerEvent::BackendCompiling(b) => json!({
                "type": "backendCompiling",
                "compiling": b
            })
            .to_string(),
            DevServerEvent::BackendStatus(b) => json!({
                "type": "backendStatus",
                "status": b
            })
            .to_string(),
            DevServerEvent::BackendRestarting(b) => json!({
                "type": "backendRestarting",
                "status": b
            })
            .to_string(),
            DevServerEvent::SHUTDOWN => json!({
                "type": "backendStatus",
                "status": "false"
            })
            .to_string(),
            DevServerEvent::CompileMessages(msgs) => {
                let messages = serde_json::to_value(&msgs).unwrap();
                json!({
                    "type": "compilerMessages",
                    "messages": messages
                })
                .to_string()
            }
        }
    }
}

#[derive(Debug)]
pub struct DevState {
    pub frontend_server_running: bool,
    pub backend_server_running: bool,
    pub watchexec_running: bool,
}

fn get_features(project_dir: &'static str) -> Vec<String> {
    let cargo_toml = Manifest::from_path(PathBuf::from_iter([project_dir, "Cargo.toml"]))
        .unwrap_or_else(|_| panic!("Could not find \"{}\"", project_dir));
    // .expect(&format!("Could not find \"{project_dir}\""));
    let deps = cargo_toml.dependencies;
    let dep = deps.get("create-rust-app").unwrap_or_else(|| {
        panic!(
            "Expected \"{}\" to list 'create-rust-app' as a dependency.",
            project_dir
        )
    });
    let dep = dep.clone();

    dep.req_features().to_vec()
}

pub fn run_server(project_dir: &'static str) {
    clearscreen::clear().expect("failed to clear screen");

    let features = get_features(project_dir);

    println!("..................................");
    println!(".. Starting development server ...");
    println!("..................................");
    let rt = tokio::runtime::Runtime::new().unwrap();

    let dev_port = std::env::var("DEV_SERVER_PORT")
        .map(|p| {
            p.parse::<u16>()
                .expect("Could not parse DEV_SERVER_PORT to u16")
        })
        .unwrap_or_else(|_| {
            find_free_port(60012..65535)
                .expect("FATAL: Could not find a free port for the development server.")
        });

    rt.block_on(async move {
        let state = Arc::new(Mutex::new(DevState {
            backend_server_running: false,
            frontend_server_running: false,
            watchexec_running: false,
        }));
        let state2 = state.clone();

        // used for shutdown only (TODO: merge this with next broadcast channel)
        let (signal_tx, signal_rx) = tokio::sync::broadcast::channel::<DevServerEvent>(64);
        let signal_rx2 = signal_tx.subscribe();

        // used for websocket events
        let (dev_server_events_s, dev_server_events_r) =
            tokio::sync::broadcast::channel::<DevServerEvent>(64);
        let dev_server_events_s2 = dev_server_events_s.clone();
        let dev_server_events_s3 = dev_server_events_s.clone();

        // HACK: used to ignore some file modification events as a result of interaction with the dev server
        let (file_events_s, _) = tokio::sync::broadcast::channel::<String>(64);
        let file_events_s2 = file_events_s.clone();

        tokio::spawn(async move {
            dev_server::start(
                project_dir,
                dev_port,
                dev_server_events_r,
                dev_server_events_s3,
                file_events_s2,
                features,
            )
            .await
        });
        tokio::spawn(async move {
            backend_compiling_server::start(
                project_dir,
                dev_port,
                signal_rx2,
                dev_server_events_s2,
                state2,
                file_events_s,
            )
            .await
        });
        tokio::spawn(async move {
            frontend_dev_server::start(
                project_dir,
                dev_port,
                signal_rx,
                dev_server_events_s.clone(),
                state,
            )
            .await
        });

        listen_for_signals(signal_tx).await
    });
}

fn check_exit(state: &DevState) {
    // println!("Checking exit status {:#?}", state);
    if !state.backend_server_running && !state.frontend_server_running && !state.watchexec_running {
        exit(0);
    }
}

async fn listen_for_signals(signal_tx: tokio::sync::broadcast::Sender<DevServerEvent>) {
    let (ev_s, ev_r) = priority::bounded::<Event, Priority>(1024);
    let (er_s, mut er_r) = tokio::sync::mpsc::channel(64);

    // panic on errors
    tokio::spawn(async move {
        while let Some(error) = er_r.recv().await {
            panic!(
                "Error handling process signal:\n==============================\n{:#?}",
                error
            );
        }
    });

    // broadcast signals
    tokio::spawn(async move {
        while let Ok((event, _)) = ev_r.recv().await {
            if event.tags.contains(&Tag::Signal(MainSignal::Terminate))
                || event.tags.contains(&Tag::Signal(MainSignal::Interrupt))
            {
                signal_tx.send(DevServerEvent::SHUTDOWN).unwrap();
            }
        }
    });

    worker(er_s, ev_s).await.unwrap();
}