servio 0.7.0

HTTP server for static files, with live reload for local development and a production mode for finished sites
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
//! `--production`, `--no-reload` and `--cache-assets`: what changes when a
//! finished site is served rather than worked on.

mod common;

use common::{PAGE, Response, Server, TempDir, get, get_page, request};
use std::time::{Duration, SystemTime};

fn site(name: &str) -> TempDir {
    let dir = TempDir::new(name);
    dir.write("index.html", "<html>the app</html>");
    dir.write("assets/app-abc123.css", "body {}");
    dir
}

/// Writes a file and sets the time it says it was written.
fn write_at(dir: &TempDir, relative: &str, contents: &str, written: SystemTime) {
    dir.write(relative, contents);
    std::fs::File::options()
        .write(true)
        .open(dir.join(relative))
        .and_then(|file| file.set_modified(written))
        .expect("could not set when the file was written");
}

/// What a browser sends to check a copy it kept.
fn check(server: &Server, address: &str, kept: &Response) -> Response {
    let mut headers = vec![("Accept", PAGE)];
    headers.extend(kept.header("etag").map(|tag| ("If-None-Match", tag)));
    headers.extend(
        kept.header("last-modified")
            .map(|date| ("If-Modified-Since", date)),
    );
    request(server.port, "GET", address, &headers)
}

#[test]
fn a_missing_asset_is_never_answered_with_the_app() {
    // Nothing under /assets/ is a route: those names carry a hash of the
    // file's contents. Answering with the app page there would leave the
    // browser holding HTML at that address for a year, so the real file, once
    // the deploy has finished, would never be asked for again.
    let dir = site("shell");
    let server = Server::start(dir.path(), &["--spa", "--cache-assets"]);

    let response = request(
        server.port,
        "GET",
        "/assets/not-copied-yet-abc123.js",
        &[("Accept", PAGE)],
    );

    assert_eq!(response.status, 404);
    assert!(!response.text().contains("the app"));
    assert_eq!(response.header("cache-control"), Some("no-cache"));
}

#[test]
fn a_refused_file_is_answered_like_anything_else() {
    let dir = site("refused");
    dir.write(".env", "API_KEY=secret");
    let server = Server::start(dir.path(), &["--cache-assets"]);

    let response = get(server.port, "/.env");
    assert_eq!(response.status, 404);
    assert_eq!(response.header("cache-control"), Some("no-cache"));
    assert_eq!(response.header("x-content-type-options"), Some("nosniff"));
}

#[test]
fn a_browser_that_already_has_the_file_is_told_so() {
    // Without this, "check each time" would still send the whole file back.
    let dir = site("revalidate");
    let server = Server::start(dir.path(), &["--cache-assets"]);

    let modified = get(server.port, "/assets/app-abc123.css")
        .header("last-modified")
        .expect("no last-modified to test with")
        .to_string();

    let response = request(
        server.port,
        "GET",
        "/assets/app-abc123.css",
        &[("If-Modified-Since", &modified)],
    );

    assert_eq!(response.status, 304);
    assert!(response.body.is_empty());

    // A browser takes the headers on this answer as the file's own, replacing
    // the ones it stored. Leave the year off and one check turns the file back
    // into one checked on every visit.
    assert_eq!(
        response.header("cache-control"),
        Some("public, max-age=31536000, immutable")
    );
}

#[test]
fn each_mode_tells_the_browser_what_it_may_keep() {
    const NOTHING: &str = "no-store";
    const CHECKED: &str = "no-cache";
    const YEAR: &str = "public, max-age=31536000, immutable";

    let dir = site("modes");
    dir.write("assets/logo.png", "png");
    dir.write("assets/docs/index.html", "<html>docs</html>");

    let addresses = [
        ("/", 200),
        // A build puts a hash of the contents in the name.
        ("/assets/app-abc123.css", 200),
        // Kept all the same, though its name has no hash: servio does not check.
        ("/assets/logo.png", 200),
        // Missing during a deploy. Kept for a year, it would never be asked for
        // again once the deploy finished.
        ("/assets/not-copied-yet-abc123.js", 404),
        // A folder's page can change, whatever the folder is called.
        ("/assets/docs/", 200),
    ];
    let assets = "files under /assets/ for a year, the rest checked each time";
    // The flags, the banner, what each address may be kept for, and whether a
    // file sent carries a tag to check it by.
    let modes: [(&[&str], &str, [&str; 5], bool); 4] = [
        (&[], "off", [NOTHING; 5], false),
        (
            &["--production"],
            "on, checked for changes each time",
            [CHECKED; 5],
            true,
        ),
        (
            &["--cache-assets"],
            assets,
            [CHECKED, YEAR, YEAR, CHECKED, CHECKED],
            true,
        ),
        (
            &["--production", "--cache-assets"],
            assets,
            [CHECKED, YEAR, YEAR, CHECKED, CHECKED],
            true,
        ),
    ];

    for (flags, banner, kept, tagged) in modes {
        let server = Server::start(dir.path(), flags);
        assert!(
            server.said(&format!("Caching        : {banner}")),
            "{flags:?}:\n{}",
            server.lines().join("\n")
        );

        for ((address, status), kept) in addresses.into_iter().zip(kept) {
            let response = get(server.port, address);
            let context = format!("{address} with {flags:?}");
            assert_eq!(response.status, status, "{context}");
            assert_eq!(response.header("cache-control"), Some(kept), "{context}");
            assert_eq!(
                response.header("etag").is_some(),
                tagged && status == 200,
                "{context}"
            );
        }
    }
}

#[test]
fn production_turns_off_reload_and_lists() {
    let dir = site("production");
    dir.write("docs/notes.txt", "notes");
    let server = Server::start(dir.path(), &["--production"]);

    let page = get_page(server.port, "/?list");
    assert!(page.text().contains("the app"), "{}", page.text());
    assert!(!page.text().contains("tower-livereload"));
    assert_eq!(get_page(server.port, "/docs/").status, 404);

    assert!(server.said("Live reload    : off"));
    assert!(server.said("File lists     : off"));
}

#[test]
fn with_production_an_unchanged_file_is_not_sent_again() {
    // The browser checks before every use, so an unchanged file must not be
    // sent again.
    let dir = site("production-revalidate");
    let server = Server::start(dir.path(), &["--production"]);

    let modified = get(server.port, "/")
        .header("last-modified")
        .expect("no last-modified to test with")
        .to_string();

    let response = request(server.port, "GET", "/", &[("If-Modified-Since", &modified)]);

    assert_eq!(response.status, 304);
    assert!(response.body.is_empty());
    assert_eq!(response.header("cache-control"), Some("no-cache"));
}

#[test]
fn a_file_rolled_back_to_an_older_copy_is_sent_again() {
    // A rollback by `rsync -a` or `tar x` brings the older file back with its
    // older date, which a check by date alone takes for no change.
    let dir = site("rollback");
    let now = SystemTime::now();
    write_at(&dir, "index.html", "<html>version 2</html>", now);
    let server = Server::start(dir.path(), &["--production"]);

    let kept = get(server.port, "/");
    write_at(
        &dir,
        "index.html",
        "<html>version 1</html>",
        now - Duration::from_secs(3600),
    );

    let checked = check(&server, "/", &kept);
    assert_eq!(checked.status, 200);
    assert!(checked.text().contains("version 1"), "{}", checked.text());

    // Asked by date alone, only the very same second counts as unchanged.
    let date = kept.header("last-modified").expect("no date to check with");
    let by_date = request(server.port, "GET", "/", &[("If-Modified-Since", date)]);
    assert_eq!(by_date.status, 200);
}

#[test]
fn a_file_changed_twice_within_a_second_is_sent_again() {
    let dir = site("same-second");
    let second = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);
    write_at(
        &dir,
        "index.html",
        "<html>first</html>",
        second + Duration::from_millis(100),
    );

    // A disk that keeps whole seconds cannot tell the two apart.
    let written = std::fs::metadata(dir.join("index.html")).and_then(|file| file.modified());
    if written.is_ok_and(|written| written == second) {
        return;
    }

    let server = Server::start(dir.path(), &["--production"]);
    let kept = get(server.port, "/");

    // As long as the first, and in the same second.
    write_at(
        &dir,
        "index.html",
        "<html>again</html>",
        second + Duration::from_millis(600),
    );

    let checked = check(&server, "/", &kept);
    assert_eq!(checked.status, 200);
    assert!(checked.text().contains("again"), "{}", checked.text());
}

#[test]
fn a_new_file_of_the_same_size_and_time_is_sent_again() {
    // Some builds give every file one fixed time, so a change that keeps the
    // length is told apart only by being a different file.
    let dir = site("pinned-time");
    let pinned = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000_000);
    write_at(&dir, "index.html", "<html>release 1.2.3</html>", pinned);
    let server = Server::start(dir.path(), &["--production"]);
    let kept = get(server.port, "/");

    // Written beside the page and moved over it, as a deploy does.
    write_at(&dir, "next.html", "<html>release 1.2.4</html>", pinned);
    std::fs::rename(dir.join("next.html"), dir.join("index.html"))
        .expect("could not move the new page into place");

    let checked = check(&server, "/", &kept);
    assert_eq!(checked.status, 200);
    assert!(
        checked.text().contains("release 1.2.4"),
        "{}",
        checked.text()
    );
}

#[test]
fn a_copy_named_by_its_tag_is_not_sent_again() {
    let dir = site("tag");
    let server = Server::start(dir.path(), &["--production"]);

    let kept = get(server.port, "/assets/app-abc123.css");
    let tag = kept.header("etag").expect("no tag to check with");
    let checked = request(
        server.port,
        "GET",
        "/assets/app-abc123.css",
        &[("If-None-Match", tag)],
    );

    assert_eq!(checked.status, 304);
    assert!(checked.body.is_empty());
    assert_eq!(checked.header("etag"), Some(tag));
    assert_eq!(checked.header("cache-control"), Some("no-cache"));
}

#[test]
fn a_file_asked_for_with_a_slash_after_it_is_not_found_even_by_its_tag() {
    // The file service finds nothing at that address, so there is no copy to
    // be current.
    let dir = site("slash-after-file");
    let server = Server::start(dir.path(), &["--production"]);

    let kept = get(server.port, "/assets/app-abc123.css");
    let tag = kept.header("etag").expect("no tag to check with");
    let checked = request(
        server.port,
        "GET",
        "/assets/app-abc123.css/",
        &[("If-None-Match", tag)],
    );

    assert_eq!(checked.status, 404);
}

#[test]
fn a_tag_is_one_number_that_stays_when_the_server_starts_again() {
    // Parts of a tag such as an inode number are read as a leak, as they were
    // for Apache. A tag that changed with every start would send every file
    // again after it.
    let dir = site("opaque-tag");
    let tag_after_a_start = || {
        let server = Server::start(dir.path(), &["--production"]);
        get(server.port, "/")
            .header("etag")
            .expect("no tag")
            .to_string()
    };

    let tag = tag_after_a_start();
    let number = tag
        .strip_prefix("W/\"")
        .and_then(|rest| rest.strip_suffix('"'))
        .unwrap_or_default();
    assert!(
        number.len() == 16 && number.chars().all(|digit| digit.is_ascii_hexdigit()),
        "{tag} is not one number"
    );
    assert_eq!(tag_after_a_start(), tag);
}

#[test]
fn the_rest_of_a_file_that_changed_is_sent_whole() {
    // A browser resuming a download asks for the rest only of the file it
    // began with.
    let dir = site("if-range");
    let server = Server::start(dir.path(), &["--production"]);

    let kept = get(server.port, "/assets/app-abc123.css");
    let date = kept
        .header("last-modified")
        .expect("no date to check with")
        .to_string();
    let rest = [("Range", "bytes=4-"), ("If-Range", date.as_str())];
    assert_eq!(
        request(server.port, "GET", "/assets/app-abc123.css", &rest).status,
        206
    );

    write_at(
        &dir,
        "assets/app-abc123.css",
        "main { color: red }",
        SystemTime::now() + Duration::from_secs(5),
    );
    let changed = request(server.port, "GET", "/assets/app-abc123.css", &rest);
    assert_eq!(changed.status, 200);
    assert_eq!(changed.text(), "main { color: red }");
}

#[test]
fn with_production_a_route_is_not_sent_the_app_again_while_it_is_unchanged() {
    let dir = site("app-version");
    let server = Server::start(dir.path(), &["--production", "--spa"]);

    let kept = get_page(server.port, "/users/123");
    assert!(kept.text().contains("the app"));
    assert_eq!(check(&server, "/users/123", &kept).status, 304);

    write_at(
        &dir,
        "index.html",
        "<html>the new app</html>",
        SystemTime::now() + Duration::from_secs(5),
    );
    let changed = check(&server, "/users/123", &kept);
    assert_eq!(changed.status, 200);
    assert!(changed.text().contains("the new app"));
}

#[test]
fn no_reload_leaves_the_page_alone() {
    let dir = site("quiet");
    let server = Server::start(dir.path(), &["--no-reload"]);

    assert!(
        !get_page(server.port, "/")
            .text()
            .contains("tower-livereload")
    );
    assert!(server.said("Live reload    : off"));
}

#[test]
fn no_reload_stops_watching_altogether() {
    let dir = site("unwatched");
    let server = Server::start(dir.path(), &["--no-reload"]);
    server.settle();

    dir.write("index.html", "<html>edited</html>");
    server.settle();

    // Without live reload there is no browser to tell, so a watch left on
    // would show only in what the server prints.
    assert!(
        !server.said("reloading"),
        "the files were still watched:\n{}",
        server.lines().join("\n")
    );
}

#[test]
fn a_published_site_still_refuses_hidden_files_and_serves_its_routes() {
    let dir = site("published");
    dir.write(".env", "API_KEY=secret");
    let server = Server::start(
        dir.path(),
        &[
            "--spa",
            "--production",
            "--cache-assets",
            "--host",
            "0.0.0.0",
        ],
    );

    assert_eq!(get_page(server.port, "/.env").status, 404);

    let route = request(server.port, "GET", "/users/123", &[("Accept", PAGE)]);
    assert_eq!(route.status, 200);
    assert!(route.text().contains("the app"));
    assert!(!route.text().contains("tower-livereload"));
}