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
|
//! The live surfaces: the SSE log tail and the htmx-refreshed builds table
//! (§13). The budget matters here — the whole point of "htmx and thirty lines of
//! glue" is that a reviewer can audit everything the browser runs.
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::*;
/// Approve a fixture's candidate and enqueue its build without running it.
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()
}
/// Read a streaming response until EOF or the deadline, whichever comes first.
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();
// A producer appends while the stream is open, then finishes the build. If
// the endpoint buffered its response, everything would arrive only after the
// build ended and the "live" claim would be false.
let db = web.env.db.clone();
let id2 = id.clone();
let log2 = log.clone();
let producer = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(400));
append(&log2, "==> step build\n");
std::thread::sleep(Duration::from_millis(400));
append(&log2, "==> step publish\n");
std::thread::sleep(Duration::from_millis(200));
// Walk the machine the way a real build does: a queued build runs
// before it succeeds.
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(15));
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}");
// It ends when the build does, rather than holding the connection forever.
assert!(body.contains("event: end"), "the stream never ended: {body}");
// SSE framing: each log line is its own event, so a client can append.
assert!(body.contains("\n\n"), "not event-framed: {body}");
}
#[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");
// One queued build so the table has a row: the empty state is a paragraph,
// and asserting on it would prove nothing about server rendering.
queued(&web.env, "plain-make");
let page = ureq::get(&base).call().unwrap().into_string().unwrap();
// The refresh is an attribute on the table, not a script we wrote.
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");
// And with JavaScript switched off the same HTML already contains the table:
// the refresh is an enhancement, not a requirement.
assert!(page.contains("<table>"), "no server-rendered table");
// The fragment endpoint returns the table on its own, so htmx can swap it in
// without dragging the whole document along.
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);
// Served bytes are what a browser actually downloads, and that is the budget
// with any meaning: the file on disk is 48 KB, the wire copy is not.
// Read the wire bytes directly: an HTTP client would transparently
// decompress, which is exactly the thing this budget is about.
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()
);
// The compressed copy really is htmx, not a stub pretending to be it.
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());
// A client that cannot take gzip still gets working JavaScript, just larger.
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");
// Nothing else is JavaScript: there is no place to hide a bundle.
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");
// The review flow is the one that must work with scripting disabled, so it
// deliberately does not load htmx at all.
assert!(!page.contains("<script"), "the review surface ships JavaScript");
}
/// Ask for a path over a bare socket so the response is seen as it goes over the
/// wire, before any client-side content negotiation undoes it.
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
}
|