zuzu-rust 0.1.1

Rust implementation of ZuzuScript
Documentation
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use std::fs;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

fn repo_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

fn temp_dir(name: &str) -> PathBuf {
    let dir =
        std::env::temp_dir().join(format!("zuzu-rust-server-{}-{}", name, std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).expect("temp dir should be created");
    dir
}

fn write_app(dir: &Path, name: &str, source: &str) -> PathBuf {
    let path = dir.join(name);
    fs::write(&path, source).expect("app should be written");
    path
}

fn request_text_with_retry(client: &reqwest::blocking::Client, url: &str) -> String {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        match client.get(url).send() {
            Ok(response) => return response.text().expect("body should decode"),
            Err(err) if Instant::now() < deadline => {
                let _ = err;
                std::thread::sleep(Duration::from_millis(25));
            }
            Err(err) => panic!("server did not accept request: {err}"),
        }
    }
}

fn wait_for_body(client: &reqwest::blocking::Client, url: &str, expected: &str) {
    let deadline = Instant::now() + Duration::from_secs(8);
    loop {
        let body = client
            .get(url)
            .send()
            .expect("request should receive response")
            .text()
            .expect("body should decode");
        if body == expected {
            return;
        }
        if Instant::now() >= deadline {
            panic!("expected body {expected:?}, got {body:?}");
        }
        std::thread::sleep(Duration::from_millis(100));
    }
}

fn run_server(args: &[String], cwd: &Path) -> std::process::Output {
    Command::new(env!("CARGO_BIN_EXE_zuzu-rust-server"))
        .args(args)
        .current_dir(cwd)
        .output()
        .expect("zuzu-rust-server should run")
}

fn run_server_str(args: &[&str], cwd: &Path) -> std::process::Output {
    let args = args.iter().map(|arg| (*arg).to_owned()).collect::<Vec<_>>();
    run_server(&args, cwd)
}

#[test]
fn server_cli_help_lists_core_options() {
    let output = run_server_str(&["--help"], &repo_root());

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("zuzu-rust-server"));
    assert!(stdout.contains("--listen"));
    assert!(stdout.contains("--workers"));
    assert!(stdout.contains("--access-log"));
    assert!(stdout.contains("--access-log-format"));
    assert!(stdout.contains("--reload"));
    assert!(stdout.contains("--check"));
}

#[test]
fn server_cli_reports_missing_app_path() {
    let output = run_server_str(&[], &repo_root());

    assert!(!output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout), "");
    assert!(String::from_utf8_lossy(&output.stderr).contains("usage: zuzu-rust-server"));
}

#[test]
fn server_cli_reports_invalid_numeric_options() {
    for args in [
        vec!["--workers", "0"],
        vec!["--queue-depth", "nope"],
        vec!["--max-requests-per-worker", "nope"],
    ] {
        let output = run_server_str(&args, &repo_root());
        assert!(!output.status.success(), "{args:?} should fail");
    }
}

#[test]
fn server_cli_reports_invalid_access_log_format() {
    let dir = temp_dir("bad-access-log-format");
    let app = write_app(
        &dir,
        "app.zzs",
        r#"
        function __request__ ( env ) {
            return [ 200, {{}}, [] ];
        }
        "#,
    );
    let app = app.to_string_lossy().to_string();
    let output = run_server_str(
        &["--access-log-format", "xml", "--check", &app],
        &repo_root(),
    );

    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("--access-log-format"));
}

#[test]
fn server_cli_check_accepts_valid_app() {
    let dir = temp_dir("check-valid");
    let app = write_app(
        &dir,
        "app.zzs",
        r#"
        function __request__ ( env ) {
            return [ 200, {{}}, [ "ok" ] ];
        }
        "#,
    );
    let app = app.to_string_lossy().to_string();
    let output = run_server_str(&["--check", &app], &repo_root());

    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout), "");
    assert_eq!(String::from_utf8_lossy(&output.stderr), "");
}

#[test]
fn server_cli_check_rejects_missing_request_handler() {
    let dir = temp_dir("check-missing-request");
    let app = write_app(&dir, "app.zzs", "function helper () { return 1; }");
    let app = app.to_string_lossy().to_string();
    let output = run_server_str(&["--check", &app], &repo_root());

    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("__request__"));
}

#[test]
fn server_cli_check_allows_disabled_worker_recycling() {
    let dir = temp_dir("check-no-recycle");
    let app = write_app(
        &dir,
        "app.zzs",
        r#"
        function __request__ ( env ) {
            return [ 200, {{}}, [] ];
        }
        "#,
    );
    let app = app.to_string_lossy().to_string();
    let output = run_server_str(
        &["--max-requests-per-worker", "0", "--check", &app],
        &repo_root(),
    );

    assert!(output.status.success());
}

#[test]
fn server_cli_reports_invalid_access_log_path() {
    let dir = temp_dir("bad-access-log");
    let app = write_app(
        &dir,
        "app.zzs",
        r#"
        function __request__ ( env ) {
            return [ 200, {{}}, [] ];
        }
        "#,
    );
    let app = app.to_string_lossy().to_string();
    let bad_log = dir.join("missing").join("access.log");
    let bad_log = bad_log.to_string_lossy().to_string();
    let output = run_server_str(&["--access-log", &bad_log, "--check", &app], &repo_root());

    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("could not open access log"));
}

#[test]
fn server_cli_smoke_serves_request_and_writes_access_log() {
    let dir = temp_dir("smoke");
    let app = write_app(
        &dir,
        "app.zzs",
        r#"
        function __request__ ( env ) {
            return [ 202, { "X-App": env{method} }, [ "hello:", env{path} ] ];
        }
        "#,
    );
    let log = dir.join("access.log");
    let mut child = Command::new(env!("CARGO_BIN_EXE_zuzu-rust-server"))
        .arg("--listen")
        .arg("127.0.0.1:0")
        .arg("--access-log")
        .arg(&log)
        .arg(app)
        .current_dir(repo_root())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("zuzu-rust-server should start");
    let stdout = child.stdout.take().expect("stdout should be piped");
    let mut stdout = BufReader::new(stdout);
    let mut line = String::new();
    stdout
        .read_line(&mut line)
        .expect("server should print listen address");
    assert!(
        line.starts_with("listening on http://"),
        "stdout was {line:?}"
    );
    let base_url = line
        .trim()
        .strip_prefix("listening on ")
        .expect("listen line should include prefix")
        .to_owned();

    let client = reqwest::blocking::Client::new();
    let deadline = Instant::now() + Duration::from_secs(5);
    let response = loop {
        match client.get(format!("{base_url}/smoke")).send() {
            Ok(response) => break response,
            Err(err) if Instant::now() < deadline => {
                let _ = err;
                std::thread::sleep(Duration::from_millis(25));
            }
            Err(err) => panic!("server did not accept request: {err}"),
        }
    };
    assert_eq!(response.status().as_u16(), 202);
    assert_eq!(
        response
            .headers()
            .get("x-app")
            .and_then(|value| value.to_str().ok()),
        Some("GET")
    );
    assert_eq!(response.text().expect("body should decode"), "hello:/smoke");

    child.kill().expect("server should be killable");
    let _ = child.wait().expect("server should exit after kill");

    let log_text = fs::read_to_string(log).expect("access log should be written");
    assert!(log_text.contains("\"GET /smoke\""));
    assert!(log_text.contains(" 202 "));
    assert!(!log_text.contains("hello:/smoke"));
}

#[test]
fn server_cli_json_access_log_and_startup_diagnostics() {
    let dir = temp_dir("json-observability");
    let app = write_app(
        &dir,
        "app.zzs",
        r#"
        function __request__ ( env ) {
            if ( env{path} == "/fail" ) {
                throw new Exception( message: "observability-boom" );
            }
            return [ 200, {{}}, [ "secret response body" ] ];
        }
        "#,
    );
    let log = dir.join("access.jsonl");
    let mut child = Command::new(env!("CARGO_BIN_EXE_zuzu-rust-server"))
        .arg("--listen")
        .arg("127.0.0.1:0")
        .arg("--workers")
        .arg("1")
        .arg("--queue-depth")
        .arg("4")
        .arg("--max-requests-per-worker")
        .arg("2")
        .arg("--deny")
        .arg("fs")
        .arg("--denymodule")
        .arg("std/net/http")
        .arg("-I")
        .arg(&dir)
        .arg("--access-log")
        .arg(&log)
        .arg("--access-log-format")
        .arg("json")
        .arg(app)
        .current_dir(repo_root())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("zuzu-rust-server should start");
    let stdout = child.stdout.take().expect("stdout should be piped");
    let mut stderr = child.stderr.take().expect("stderr should be piped");
    let mut stdout = BufReader::new(stdout);
    let mut line = String::new();
    stdout
        .read_line(&mut line)
        .expect("server should print listen address");
    let base_url = line
        .trim()
        .strip_prefix("listening on ")
        .expect("listen line should include prefix")
        .to_owned();
    let client = reqwest::blocking::Client::new();
    let deadline = Instant::now() + Duration::from_secs(5);

    let ok = loop {
        match client
            .post(format!("{base_url}/ok"))
            .body("secret request body")
            .send()
        {
            Ok(response) => break response,
            Err(err) if Instant::now() < deadline => {
                let _ = err;
                std::thread::sleep(Duration::from_millis(25));
            }
            Err(err) => panic!("server did not accept request: {err}"),
        }
    };
    let fail = client
        .get(format!("{base_url}/fail"))
        .send()
        .expect("failing request should receive response");

    assert_eq!(ok.status().as_u16(), 200);
    assert_eq!(fail.status().as_u16(), 500);
    assert_eq!(
        fail.text().expect("failure body should decode"),
        "Internal Server Error\n"
    );

    child.kill().expect("server should be killable");
    let _ = child.wait().expect("server should exit after kill");
    let mut stderr_text = String::new();
    stderr
        .read_to_string(&mut stderr_text)
        .expect("stderr should be readable");

    let log_text = fs::read_to_string(log).expect("access log should be written");
    let lines = log_text.lines().collect::<Vec<_>>();
    assert_eq!(lines.len(), 2);
    let first: serde_json::Value =
        serde_json::from_str(lines[0]).expect("first access log line should be JSON");
    let second: serde_json::Value =
        serde_json::from_str(lines[1]).expect("second access log line should be JSON");
    assert_eq!(first["method"], "POST");
    assert_eq!(first["path"], "/ok");
    assert_eq!(first["status"], 200);
    assert_eq!(first["worker_id"], 0);
    assert_eq!(second["method"], "GET");
    assert_eq!(second["path"], "/fail");
    assert_eq!(second["status"], 500);
    assert_eq!(second["worker_id"], 0);

    assert!(stderr_text.contains("startup app_path="));
    assert!(stderr_text.contains("startup listener=http://"));
    assert!(stderr_text.contains("startup workers=1"));
    assert!(stderr_text.contains("startup module_roots="));
    assert!(stderr_text.contains("startup denied_capabilities=fs"));
    assert!(stderr_text.contains("startup denied_modules=std/net/http"));
    assert!(stderr_text.contains("startup max_requests_per_worker=2"));
    assert!(stderr_text.contains("format=json"));
    assert!(!stderr_text.contains("secret request body"));
    assert!(!stderr_text.contains("secret response body"));
    assert!(!log_text.contains("secret request body"));
    assert!(!log_text.contains("secret response body"));
}

#[test]
fn server_cli_reload_replaces_app_and_keeps_old_app_on_failure() {
    let dir = temp_dir("reload");
    let app = write_app(
        &dir,
        "app.zzs",
        r#"
        function __request__ ( env ) {
            return [ 200, {{}}, [ "one" ] ];
        }
        "#,
    );
    let mut child = Command::new(env!("CARGO_BIN_EXE_zuzu-rust-server"))
        .arg("--listen")
        .arg("127.0.0.1:0")
        .arg("--workers")
        .arg("1")
        .arg("--reload")
        .arg(&app)
        .current_dir(repo_root())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("zuzu-rust-server should start");
    let stdout = child.stdout.take().expect("stdout should be piped");
    let mut stderr = child.stderr.take().expect("stderr should be piped");
    let mut stdout = BufReader::new(stdout);
    let mut line = String::new();
    stdout
        .read_line(&mut line)
        .expect("server should print listen address");
    let base_url = line
        .trim()
        .strip_prefix("listening on ")
        .expect("listen line should include prefix")
        .to_owned();
    let client = reqwest::blocking::Client::new();

    assert_eq!(request_text_with_retry(&client, &base_url), "one");
    fs::write(
        &app,
        r#"
        function __request__ ( env ) {
            return [ 200, {{}}, [ "two" ] ];
        }
        "#,
    )
    .expect("updated app should be written");
    wait_for_body(&client, &base_url, "two");

    fs::write(&app, "function helper () { return 1; }").expect("bad app should be written");
    std::thread::sleep(Duration::from_millis(1200));
    assert_eq!(
        client
            .get(&base_url)
            .send()
            .expect("request should receive response")
            .text()
            .expect("body should decode"),
        "two"
    );

    fs::write(
        &app,
        r#"
        function __request__ ( env ) {
            return [ 200, {{}}, [ "three" ] ];
        }
        "#,
    )
    .expect("fixed app should be written");
    wait_for_body(&client, &base_url, "three");

    child.kill().expect("server should be killable");
    let _ = child.wait().expect("server should exit after kill");
    let mut stderr_text = String::new();
    stderr
        .read_to_string(&mut stderr_text)
        .expect("stderr should be readable");
    assert!(stderr_text.contains("startup reload=true"));
    assert!(stderr_text.contains("reload detected"));
    assert!(stderr_text.contains("reload activated"));
    assert!(stderr_text.contains("reload failed"));
}