perk-cli 0.1.0

The `perk` command: create apps, add pages, check them, and run a development server that reloads on save
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! `perk dev`: rebuilds the application when a file changes, restarts it,
//! and tells open pages to reload.
//!
//! This process owns the listening socket and hands it to each new copy of
//! the application, so browsers never see "connection refused" during a
//! restart; their connections wait in the socket's backlog. While no copy is
//! running (the first build failed, or the app exited), this process answers
//! requests itself with a page that explains why.

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use crate::cargo::{self, Workspace};
use crate::{CliError, value};

pub const USAGE: &str = "\
usage: perk dev [-p <package>] [--addr <host:port>] [--release] [--offline] [-- <app args>]

Builds the package, runs it, and on every change under the workspace rebuilds
it, restarts it and reloads open pages. Sessions survive restarts.

  -p, --package   the application to run (default: the one binary package
                  in the workspace that depends on perk)
  --addr          where to listen (default: `[server] addr` in perk.toml
                  or $PERK_SERVER_ADDR, or 127.0.0.1:3000)
  --release       build with the release profile
  --offline       pass --offline to cargo
  -- <args>       arguments for the application (default: serve)
";

struct Options {
    package: Option<String>,
    /// `--addr`; when empty, `run` fills it from `perk.toml`.
    addr: String,
    cargo_flags: Vec<String>,
    app_args: Vec<String>,
}

pub fn main(args: Vec<String>) -> Result<(), CliError> {
    let mut args = args.into_iter();
    let mut opts = Options {
        package: None,
        addr: String::new(),
        cargo_flags: Vec::new(),
        app_args: Vec::new(),
    };
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-p" | "--package" => opts.package = Some(value(&mut args, "--package")?),
            "--addr" => opts.addr = value(&mut args, "--addr")?,
            "--release" | "--offline" => opts.cargo_flags.push(arg),
            "--" => opts.app_args.extend(args.by_ref()),
            "-h" | "--help" => return Err(CliError::Help),
            other => return Err(CliError::Usage(format!("unknown option `{other}`"))),
        }
    }
    if opts.app_args.is_empty() {
        opts.app_args.push("serve".into());
    }
    run(opts).map_err(CliError::Failed)
}

struct Built {
    exe: PathBuf,
    /// Cargo didn't need to rebuild the executable.
    fresh: bool,
}

/// Runs `cargo build`, streaming its output to the terminal. On failure,
/// returns that output without colours, for the browser overlay.
fn build(ws: &Workspace, flags: &[String]) -> Result<Built, String> {
    let mut child = Command::new("cargo")
        .args(["build", "-p", &ws.package, "--message-format=json-render-diagnostics", "--color=always"])
        .args(flags)
        // Builds the page runtime with the hooks the dev client uses.
        .env("PERK_DEV", "1")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("running cargo: {e}"))?;
    let mut stderr = child.stderr.take().unwrap();
    let tee = thread::spawn(move || {
        let mut all = Vec::new();
        let mut buf = [0u8; 8192];
        while let Ok(n) = stderr.read(&mut buf) {
            if n == 0 {
                break;
            }
            let _ = std::io::stderr().write_all(&buf[..n]);
            all.extend_from_slice(&buf[..n]);
        }
        String::from_utf8_lossy(&all).into_owned()
    });
    let mut built = None;
    for line in BufReader::new(child.stdout.take().unwrap()).lines().map_while(Result::ok) {
        let Ok(msg) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
        if msg["reason"] == "compiler-artifact"
            && msg["manifest_path"] == ws.manifest.as_str()
            && let Some(exe) = msg["executable"].as_str()
        {
            built = Some(Built { exe: exe.into(), fresh: msg["fresh"] == true });
        }
    }
    let status = child.wait().map_err(|e| e.to_string())?;
    let log = tee.join().unwrap_or_default();
    match built {
        Some(b) if status.success() => Ok(b),
        _ if status.success() => Err(format!("cargo built no executable for `{}`", ws.package)),
        _ => Err(failure_text(&log)),
    }
}

/// Cargo's error output, minus colours and progress lines. A failing build
/// script (where the page compiler reports) has its own stderr unindented.
fn failure_text(log: &str) -> String {
    let plain = strip_ansi(log);
    if let Some((_, script)) = plain.split_once("--- stderr\n") {
        let lines: Vec<&str> = script.lines().map(|l| l.strip_prefix("  ").unwrap_or(l)).collect();
        return lines.join("\n").trim().to_owned();
    }
    let lines: Vec<&str> = plain
        .lines()
        .filter(|l| {
            let t = l.trim_start();
            !(t.starts_with("Compiling ") || t.starts_with("Building ") || t.starts_with("Checking "))
        })
        .collect();
    lines.join("\n").trim().to_owned()
}

fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // CSI: ESC [ params final-byte
            if chars.next() == Some('[') {
                for c in chars.by_ref() {
                    if ('@'..='~').contains(&c) {
                        break;
                    }
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// A fingerprint of every source file in the workspace.
fn scan(ws: &Workspace) -> u64 {
    fn walk(dir: &Path, skip: &Path, h: &mut DefaultHasher) {
        let Ok(entries) = std::fs::read_dir(dir) else { return };
        let mut entries: Vec<_> = entries.filter_map(Result::ok).collect();
        entries.sort_by_key(|e| e.file_name());
        for e in entries {
            let name = e.file_name();
            let name = name.to_string_lossy();
            let path = e.path();
            if name.starts_with('.') || matches!(&*name, "target" | "dist" | "node_modules") || path == skip {
                continue;
            }
            let Ok(meta) = e.metadata() else { continue };
            if meta.is_dir() {
                walk(&path, skip, h);
            } else {
                path.hash(h);
                meta.len().hash(h);
                meta.modified().ok().hash(h);
            }
        }
    }
    let mut h = DefaultHasher::new();
    walk(&ws.root, &ws.target, &mut h);
    h.finish()
}

/// The running application.
struct App {
    child: Child,
    stdin: ChildStdin,
}

impl App {
    fn tell(&mut self, msg: serde_json::Value) {
        let _ = writeln!(self.stdin, "{msg}");
        let _ = self.stdin.flush();
    }

    fn stop(mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

struct Session<'a> {
    ws: &'a Workspace,
    opts: &'a Options,
    listener: TcpListener,
    build_no: u64,
    app: Option<App>,
    fallback: Option<Fallback>,
    fallback_no: u64,
}

impl Session<'_> {
    fn spawn(&mut self, exe: &Path) -> Result<(), String> {
        self.build_no += 1;
        if let Some(mut app) = self.app.take() {
            // Let open pages' event streams end cleanly first.
            app.tell(serde_json::json!({ "status": "restarting" }));
            thread::sleep(Duration::from_millis(50));
            app.stop();
        }
        if let Some(f) = self.fallback.take() {
            f.stop();
        }
        let fd = listener_fd(&self.listener);
        let sessions = self.ws.target.join("perk-dev").join(&self.ws.package).join("sessions.json");
        let mut cmd = Command::new(exe);
        cmd.args(&self.opts.app_args)
            .env("PERK_DEV", "1")
            .env("PERK_DEV_BUILD", self.build_no.to_string())
            .env("PERK_DEV_LISTEN_FD", fd.to_string())
            .env("PERK_DEV_SESSIONS", sessions)
            .stdin(Stdio::piped());
        inherit_fd(&mut cmd, fd);
        let mut child = cmd.spawn().map_err(|e| format!("starting {}: {e}", exe.display()))?;
        let stdin = child.stdin.take().unwrap();
        self.app = Some(App { child, stdin });
        Ok(())
    }

    fn show_error(&mut self, title: &str, text: &str) {
        if let Some(app) = &mut self.app {
            app.tell(serde_json::json!({ "status": "failed", "output": text }));
            return;
        }
        if let Some(f) = self.fallback.take() {
            f.stop();
        }
        self.fallback_no += 1;
        self.fallback = Some(Fallback::start(&self.listener, self.fallback_no, title, text));
    }

    fn rebuild(&mut self) {
        if let Some(app) = &mut self.app {
            app.tell(serde_json::json!({ "status": "building" }));
        }
        let started = Instant::now();
        match build(self.ws, &self.opts.cargo_flags) {
            Ok(b) if b.fresh && self.app.is_some() => {
                if let Some(app) = &mut self.app {
                    app.tell(serde_json::json!({ "status": "idle" }));
                }
            }
            Ok(b) => match self.spawn(&b.exe) {
                Ok(()) => eprintln!(
                    "\x1b[32mperk\x1b[0m build {} running ({:.1}s) on http://{}",
                    self.build_no,
                    started.elapsed().as_secs_f64(),
                    self.opts.addr
                ),
                Err(e) => {
                    eprintln!("perk: {e}");
                    self.show_error("Couldn't start the app", &e);
                }
            },
            Err(text) => {
                eprintln!("\x1b[31mperk\x1b[0m build failed; still serving the last good build");
                self.show_error("Build failed", &text);
            }
        }
    }

    /// Notices an application that exited on its own (a panic at startup, say).
    fn check_app(&mut self) {
        let exited = match &mut self.app {
            Some(app) => app.child.try_wait().ok().flatten(),
            None => None,
        };
        if let Some(status) = exited {
            self.app = None;
            eprintln!("\x1b[31mperk\x1b[0m the app exited ({status}); waiting for a change");
            self.show_error("The app exited", &format!("It exited with {status}. Its output is in the terminal running `perk dev`."));
        }
    }
}

fn run(mut opts: Options) -> Result<(), String> {
    let ws = cargo::app(opts.package.as_deref())?;
    if opts.addr.is_empty() {
        opts.addr = ws.config()?.server.addr;
    }
    let listener = TcpListener::bind(&opts.addr).map_err(|e| format!("binding {}: {e}", opts.addr))?;
    eprintln!("\x1b[32mperk\x1b[0m dev: `{}` on http://{}, watching {}", ws.package, opts.addr, ws.root.display());
    let mut s = Session { ws: &ws, opts: &opts, listener, build_no: 0, app: None, fallback: None, fallback_no: 0 };
    s.rebuild();
    let mut seen = scan(&ws);
    loop {
        thread::sleep(Duration::from_millis(200));
        s.check_app();
        let mut now = scan(&ws);
        if now == seen {
            continue;
        }
        // Wait for editors that write in several steps to finish.
        loop {
            thread::sleep(Duration::from_millis(80));
            let again = scan(&ws);
            if again == now {
                break;
            }
            now = again;
        }
        seen = now;
        s.rebuild();
    }
}

#[cfg(unix)]
fn listener_fd(l: &TcpListener) -> i32 {
    use std::os::fd::AsRawFd;
    l.as_raw_fd()
}

/// Lets the child inherit the listening socket. Rust opens sockets
/// close-on-exec; this clears the flag in the child only, after the fork.
#[cfg(unix)]
fn inherit_fd(cmd: &mut Command, fd: i32) {
    use std::os::unix::process::CommandExt;
    // SAFETY: fcntl is async-signal-safe, which is all pre_exec requires.
    unsafe {
        cmd.pre_exec(move || {
            if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
}

#[cfg(not(unix))]
fn listener_fd(_: &TcpListener) -> i32 {
    compile_error!("perk dev needs a Unix platform to hand its socket to the app");
}

#[cfg(not(unix))]
fn inherit_fd(_: &mut Command, _: i32) {}

/// Answers requests while no application is running.
struct Fallback {
    stop: Arc<AtomicBool>,
    thread: JoinHandle<()>,
}

impl Fallback {
    fn start(listener: &TcpListener, generation: u64, title: &str, text: &str) -> Self {
        let listener = listener.try_clone().expect("cloning the listening socket");
        listener.set_nonblocking(true).expect("non-blocking socket");
        let page = fallback_page(generation, title, text);
        let stop = Arc::new(AtomicBool::new(false));
        let flag = stop.clone();
        let thread = thread::spawn(move || {
            while !flag.load(Ordering::Relaxed) {
                match listener.accept() {
                    Ok((stream, _)) => respond(stream, generation, &page),
                    Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(30)),
                    Err(_) => thread::sleep(Duration::from_millis(100)),
                }
            }
        });
        Fallback { stop, thread }
    }

    fn stop(self) {
        self.stop.store(true, Ordering::Relaxed);
        let _ = self.thread.join();
    }
}

fn respond(mut stream: TcpStream, generation: u64, page: &str) {
    // Accepted sockets inherit non-blocking mode on some platforms.
    let _ = stream.set_nonblocking(false);
    let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
    let mut req = Vec::new();
    let mut buf = [0u8; 2048];
    while !req.windows(4).any(|w| w == b"\r\n\r\n") && req.len() < 16 * 1024 {
        match stream.read(&mut buf) {
            Ok(0) | Err(_) => break,
            Ok(n) => req.extend_from_slice(&buf[..n]),
        }
    }
    let head = format!(
        "HTTP/1.1 503 Service Unavailable\r\ncontent-type: text/html; charset=utf-8\r\ncache-control: no-store\r\nx-perk-dev-fallback: {generation}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
        page.len()
    );
    let _ = stream.write_all(head.as_bytes());
    let _ = stream.write_all(page.as_bytes());
}

fn fallback_page(generation: u64, title: &str, text: &str) -> String {
    let esc = |s: &str| s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
    format!(
        r#"<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>{title}</title>
<style>
body{{margin:0;background:#1b1b1f;color:#eee;font:13px/1.5 ui-monospace,Menlo,monospace;padding:4vh 4vw}}
h1{{font:600 16px system-ui,sans-serif;color:#ff8080;margin:0 0 12px}}
pre{{white-space:pre-wrap;margin:0}}
p{{font:12px system-ui,sans-serif;color:#aaa}}
</style></head>
<body><h1>{title}</h1><pre>{text}</pre>
<p>Nothing is running yet. Fix the problem and save; this page reloads when the app is up.</p>
<script>
setInterval(async () => {{
  try {{
    const res = await fetch("/_perk/dev/ping", {{ cache: "no-store" }});
    if (res.headers.get("x-perk-dev-fallback") !== "{generation}") location.reload();
  }} catch {{}}
}}, 400);
</script></body></html>
"#,
        title = esc(title),
        text = esc(text),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn failure_text_unwraps_build_script_stderr() {
        let log = "\x1b[1m\x1b[32m   Compiling\x1b[0m account-demo v0.1.0\n\x1b[1m\x1b[31merror\x1b[0m: failed to run custom build command for `account-demo`\n\nCaused by:\n  process didn't exit successfully\n  --- stderr\n  error: `formatDate(…)` cannot be rendered\n   --> src/routes/account.perk:3:15\n";
        assert_eq!(failure_text(log), "error: `formatDate(…)` cannot be rendered\n --> src/routes/account.perk:3:15");
    }

    #[test]
    fn failure_text_drops_progress_lines() {
        let log = "   Compiling perk v0.1.0\nerror[E0425]: cannot find value `x`\n --> src/lib.rs:1:1\n";
        assert_eq!(failure_text(log), "error[E0425]: cannot find value `x`\n --> src/lib.rs:1:1");
    }

    #[test]
    fn fallback_page_escapes_output() {
        let page = fallback_page(3, "Build failed", "<script>alert(1)</script>");
        assert!(page.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
        assert!(page.contains(r#"!== "3""#));
    }
}