summaryrefslogtreecommitdiffstats
path: root/tests/live.rs
blob: b891b7ead686539e2e981924462f55fcc7dec2d2 (plain)
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
mod common;

use std::io::Read;
use std::time::{Duration, Instant};

use aur_build::db::model::BuildState;
use aur_build::db::builds;
use aur_build::pipeline;
use aur_build::review::{candidates, diff};
use common::*;

fn queued(env: &Env, name: &str) -> String {
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
    let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
    let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
    let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
    aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
    let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
    pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap()
}

fn drain(mut r: impl Read, deadline: Duration) -> String {
    let mut buf = [0u8; 4096];
    let mut out = Vec::new();
    let start = Instant::now();
    loop {
        if start.elapsed() > deadline {
            break;
        }
        match r.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => out.extend_from_slice(&buf[..n]),
            Err(_) => break,
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

#[test]
fn the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends() {
    let (env, fx) = env_with_fixture("plain-make");
    let web = Web::attach(env, fx);
    let id = queued(&web.env, "plain-make");
    let log = web.env.cfg.build_log_path(&id);
    std::fs::create_dir_all(log.parent().unwrap()).unwrap();
    std::fs::write(&log, "==> step materialize\n").unwrap();

    let db = web.env.db.clone();
    let id2 = id.clone();
    let log2 = log.clone();
    let producer = std::thread::spawn(move || {
        append(&log2, "==> step build\n");
        append(&log2, "==> step publish\n");
        builds::set_state(&db, &id2, BuildState::Running, None).unwrap();
        builds::set_state(&db, &id2, BuildState::Succeeded, None).unwrap();
    });

    let resp = ureq::get(&web.url(&format!("/builds/{id}/log.stream"))).call().expect("stream");
    assert_eq!(resp.header("content-type").unwrap_or(""), "text/event-stream");
    assert_eq!(resp.header("cache-control").unwrap_or(""), "no-cache");
    let body = drain(resp.into_reader(), Duration::from_secs(30));
    producer.join().unwrap();

    assert!(body.contains("data: ==> step materialize"), "the first line is missing: {body}");
    assert!(body.contains("data: ==> step build"), "appended bytes never arrived: {body}");
    assert!(body.contains("data: ==> step publish"), "the tail stopped early: {body}");
    assert!(body.contains("event: end"), "the stream never ended: {body}");
    assert!(body.contains("\n\n"), "not event-framed: {body}");
}

fn read_event(tail: &mut aur_build::http::sse::LogTail) -> String {
    let mut buf = [0u8; 4096];
    let n = tail.read(&mut buf).expect("tail");
    String::from_utf8_lossy(&buf[..n]).into_owned()
}

#[test]
fn the_tail_hands_over_each_append_as_it_lands_and_then_ends() {
    let (env, _fx) = env_with_fixture("plain-make");
    let id = queued(&env, "plain-make");
    let log = env.cfg.build_log_path(&id);
    std::fs::create_dir_all(log.parent().unwrap()).unwrap();
    std::fs::write(&log, "==> step materialize\n").unwrap();

    // Driven directly rather than over the socket, because the response is
    // buffered until it ends: over HTTP every line lands in one read whatever
    // the tail is doing, so the socket cannot show delivery per append.
    let mut tail = aur_build::http::sse::LogTail::new(&env.cfg, env.db.clone(), &id);
    assert_eq!(read_event(&mut tail), "data: ==> step materialize\n\n");
    append(&log, "==> step build\n");
    assert_eq!(
        read_event(&mut tail),
        "data: ==> step build\n\n",
        "the second append did not arrive as an event of its own"
    );
    append(&log, "==> step publish\n");
    assert_eq!(read_event(&mut tail), "data: ==> step publish\n\n");

    builds::set_state(&env.db, &id, BuildState::Running, None).unwrap();
    builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap();
    assert!(read_event(&mut tail).contains("event: end"), "the tail never ended");
}

#[test]
fn the_log_stream_is_404_for_a_build_that_does_not_exist() {
    let (env, fx) = env_with_fixture("plain-make");
    let web = Web::attach(env, fx);
    let resp = ureq::get(&web.url("/builds/nope/log.stream")).call();
    match resp {
        Err(ureq::Error::Status(404, _)) => {}
        other => panic!("expected 404, got {other:?}"),
    }
}

#[test]
fn the_builds_table_refreshes_via_htmx_and_still_works_without_js() {
    let (env, fx) = env_with_fixture("plain-make");
    let web = Web::attach(env, fx);
    let base = web.url("/builds");

    queued(&web.env, "plain-make");
    let page = ureq::get(&base).call().unwrap().into_string().unwrap();
    assert!(page.contains("hx-trigger=\"every 3s\""), "no htmx refresh: {}", &page[..400.min(page.len())]);
    assert!(page.contains("hx-get=\"/builds?fragment=1\""), "the refresh has no target");
    assert!(page.contains("<script src=\"/static/htmx.min.js\""), "htmx is not loaded");
    assert!(page.contains("<table>"), "no server-rendered table");

    let frag = ureq::get(&format!("{base}?fragment=1")).call().unwrap().into_string().unwrap();
    assert!(frag.starts_with("<div id=\"builds\""), "fragment is not the table: {}", &frag[..120.min(frag.len())]);
    assert!(!frag.contains("<!doctype"), "the fragment is a whole page");
    assert!(!frag.contains("<nav"), "the fragment carries the chrome");
}

#[test]
fn htmx_is_the_only_javascript_and_what_is_shipped_fits_the_budget() {
    let (env, fx) = env_with_fixture("plain-make");
    let web = Web::attach(env, fx);
    let (headers, served) = raw_get(&web, "/static/htmx.min.js", true);
    assert!(headers.to_lowercase().contains("content-encoding: gzip"), "the vendored js is not compressed: {headers}");
    assert!(
        served.len() < 20 * 1024,
        "vendored JavaScript is {} bytes on the wire, over the 20 KB budget",
        served.len()
    );
    let raw = gunzip(&served);
    assert!(raw.starts_with(b"(function"), "the decompressed file is not htmx");
    assert!(raw.len() > 40_000, "decompressed htmx looks truncated: {}", raw.len());

    let (plain_headers, plain_bytes) = raw_get(&web, "/static/htmx.min.js", false);
    assert!(!plain_headers.to_lowercase().contains("content-encoding"), "served gzip to a client that did not ask");
    assert_eq!(plain_bytes, raw, "the two copies disagree");

    let other = ureq::get(&web.url("/static/anything-else.js")).call();
    assert!(matches!(other, Err(ureq::Error::Status(404, _))), "we serve arbitrary js");
}

#[test]
fn the_stylesheet_is_served_and_the_review_surface_needs_no_javascript() {
    let (env, fx) = env_with_fixture("plain-make");
    let web = Web::attach(env, fx);
    let css = ureq::get(&web.url("/static/app.css")).call().unwrap().into_string().unwrap();
    assert!(css.contains("body"), "app.css is a placeholder");
    let page = web.get("/reviews").body;
    assert!(page.contains("<link rel=\"stylesheet\" href=\"/static/app.css\">"), "the page does not load it");
    assert!(!page.contains("<script"), "the review surface ships JavaScript");
}

fn raw_get(web: &Web, path: &str, gzip: bool) -> (String, Vec<u8>) {
    use std::io::{BufRead, BufReader, Write};
    let addr = web.server.addr.clone();
    let mut sock = std::net::TcpStream::connect(&addr).unwrap();
    let enc = if gzip { "gzip" } else { "identity" };
    write!(
        sock,
        "GET {path} HTTP/1.1\r\nHost: {addr}\r\nAccept-Encoding: {enc}\r\nConnection: close\r\n\r\n"
    )
    .unwrap();
    let mut br = BufReader::new(sock);
    let mut headers = String::new();
    loop {
        let mut line = String::new();
        br.read_line(&mut line).unwrap();
        if line.trim_end() == "" {
            break;
        }
        headers.push_str(&line);
    }
    let mut body = Vec::new();
    br.read_to_end(&mut body).unwrap();
    (headers, body)
}

fn append(path: &std::path::Path, s: &str) {
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).unwrap();
    f.write_all(s.as_bytes()).unwrap();
    f.flush().unwrap();
}

fn gunzip(bytes: &[u8]) -> Vec<u8> {
    use flate2::read::GzDecoder;
    let mut out = Vec::new();
    GzDecoder::new(bytes).read_to_end(&mut out).unwrap();
    out
}