forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

flow.rs558 lines, 18.3 KiBHistoryRawDownload
1//! The runner against a mock forge (hyper on a local TCP port) with `HostExecutor`.
2//!
3//! Enabled for `cargo test` by the self dev-dependency in Cargo.toml, which turns on the
4//! `test-host-executor` feature. There is no cfg gate here, so a build without the feature fails
5//! to compile instead of silently skipping these tests.
6
7use std::collections::{BTreeMap, HashMap};
8use std::convert::Infallible;
9use std::path::{Path, PathBuf};
10use std::process::Command as StdCommand;
11use std::sync::{Arc, Mutex};
12use std::time::{Duration, Instant};
13
14use bytes::Bytes;
15use forge_ci::proto::{FinishRequest, JobAssignment, Outcome, RegisterResponse};
16use forge_runner::config::{Limits, RunnerConfig};
17use forge_runner::executor::HostExecutor;
18use forge_runner::logs::PumpConfig;
19use forge_runner::runner::{RunEnd, RunOptions, Runner};
20use http_body_util::{BodyExt, Full};
21use hyper::body::Incoming;
22use hyper::header::{AUTHORIZATION, HeaderMap};
23use hyper::server::conn::http1;
24use hyper::service::service_fn;
25use hyper::{Method, Request, Response, StatusCode};
26use hyper_util::rt::TokioIo;
27use tokio::net::TcpListener;
28use tokio_util::sync::CancellationToken;
29
30const RUNNER_SECRET: &str = "runner-secret-for-tests";
31const SECRET_VALUE: &str = "s3cr3t-value-echoed-by-job";
32const LOG_SIZE: &str = "X-Forge-Log-Size";
33const LOG_OFFSET: &str = "X-Forge-Log-Offset";
34
35/// What the mock forge saw and what it should do.
36#[derive(Default)]
37struct MockState {
38 /// Jobs handed out by claim, in order.
39 pending: Vec<JobAssignment>,
40 /// Every job by id, so job calls can check the job token.
41 by_id: HashMap<String, JobAssignment>,
42 /// The stored log, exactly as the forge would keep it.
43 log: Vec<u8>,
44 log_posts: usize,
45 conflicts: usize,
46 /// On log POST number `.0`, the forge first stores the first `.1` bytes of the body and then
47 /// answers 409, as if an earlier attempt had been applied but its response was lost.
48 ghost: Option<(usize, usize)>,
49 /// On log POST number `n`, the forge answers 200 but stores nothing, as if the batch was
50 /// dropped after it was acknowledged. A later POST then gets 409 with the smaller size.
51 drop_post: Option<usize>,
52 heartbeats: usize,
53 /// Heartbeats from number `n` on answer `cancel: true`.
54 cancel_from_heartbeat: Option<usize>,
55 artifacts: BTreeMap<String, Vec<u8>>,
56 finished: HashMap<String, FinishRequest>,
57}
58
59type Shared = Arc<Mutex<MockState>>;
60
61struct Reply {
62 status: StatusCode,
63 log_size: Option<u64>,
64 body: Vec<u8>,
65}
66
67impl Reply {
68 fn empty(status: StatusCode) -> Self {
69 Self {
70 status,
71 log_size: None,
72 body: Vec::new(),
73 }
74 }
75
76 fn json<T: serde::Serialize>(value: &T) -> Self {
77 Self {
78 status: StatusCode::OK,
79 log_size: None,
80 body: serde_json::to_vec(value).unwrap_or_default(),
81 }
82 }
83}
84
85fn bearer(headers: &HeaderMap) -> String {
86 headers
87 .get(AUTHORIZATION)
88 .and_then(|v| v.to_str().ok())
89 .and_then(|v| v.strip_prefix("Bearer "))
90 .unwrap_or_default()
91 .to_owned()
92}
93
94fn route(
95 st: &mut MockState,
96 method: &Method,
97 path: &str,
98 auth: &str,
99 offset: Option<u64>,
100 body: &[u8],
101) -> Reply {
102 let parts: Vec<&str> = path.trim_matches('/').split('/').collect();
103 match (method.as_str(), parts.as_slice()) {
104 ("POST", ["api", "v1", "ci", "runners", "register"]) => Reply::json(&RegisterResponse {
105 runner_id: "runner-1".to_owned(),
106 runner_secret: RUNNER_SECRET.to_owned(),
107 }),
108 ("POST", ["api", "v1", "ci", "runners", "claim"]) => {
109 if auth != RUNNER_SECRET {
110 return Reply::empty(StatusCode::UNAUTHORIZED);
111 }
112 if st.pending.is_empty() {
113 return Reply::empty(StatusCode::NO_CONTENT);
114 }
115 let job = st.pending.remove(0);
116 Reply::json(&job)
117 }
118 ("POST" | "PUT" | "GET", ["api", "v1", "ci", "jobs", job_id, rest @ ..]) => {
119 let Some(job) = st.by_id.get(*job_id) else {
120 return Reply::empty(StatusCode::NOT_FOUND);
121 };
122 if auth != job.job_token {
123 return Reply::empty(StatusCode::UNAUTHORIZED);
124 }
125 match (method.as_str(), rest) {
126 ("POST", ["logs"]) => log_post(st, offset, body),
127 ("POST", ["heartbeat"]) => {
128 st.heartbeats += 1;
129 let cancel = st.cancel_from_heartbeat.is_some_and(|n| st.heartbeats >= n);
130 Reply::json(&forge_ci::proto::HeartbeatResponse {
131 cancel,
132 concurrency: None,
133 restart: None,
134 })
135 }
136 ("PUT", ["artifacts", name]) => {
137 let valid = !name.is_empty()
138 && name.len() <= 128
139 && !name.starts_with('.')
140 && name
141 .bytes()
142 .all(|b| b.is_ascii_alphanumeric() || b"._+-".contains(&b));
143 if !valid {
144 return Reply::empty(StatusCode::BAD_REQUEST);
145 }
146 st.artifacts.insert((*name).to_owned(), body.to_vec());
147 Reply::empty(StatusCode::OK)
148 }
149 ("POST", ["finish"]) => match serde_json::from_slice::<FinishRequest>(body) {
150 Ok(req) => {
151 st.finished.insert((*job_id).to_owned(), req);
152 Reply::empty(StatusCode::OK)
153 }
154 Err(_) => Reply::empty(StatusCode::BAD_REQUEST),
155 },
156 _ => Reply::empty(StatusCode::NOT_FOUND),
157 }
158 }
159 _ => Reply::empty(StatusCode::NOT_FOUND),
160 }
161}
162
163/// The forge's log rules: append at size, accept an idempotent retry, otherwise 409 with the size.
164fn log_post(st: &mut MockState, offset: Option<u64>, body: &[u8]) -> Reply {
165 let Some(offset) = offset else {
166 return Reply::empty(StatusCode::BAD_REQUEST);
167 };
168 st.log_posts += 1;
169 if st.drop_post == Some(st.log_posts) {
170 return Reply::empty(StatusCode::OK);
171 }
172 if let Some((nth, prefix)) = st.ghost
173 && st.log_posts == nth
174 {
175 let n = prefix.min(body.len());
176 st.log.extend_from_slice(&body[..n]);
177 }
178 let size = st.log.len() as u64;
179 if offset == size {
180 st.log.extend_from_slice(body);
181 return Reply::empty(StatusCode::OK);
182 }
183 let end = offset + body.len() as u64;
184 if end == size && st.log[offset as usize..] == *body {
185 return Reply::empty(StatusCode::OK);
186 }
187 st.conflicts += 1;
188 Reply {
189 status: StatusCode::CONFLICT,
190 log_size: Some(size),
191 body: Vec::new(),
192 }
193}
194
195async fn handle(
196 state: Shared,
197 req: Request<Incoming>,
198) -> Result<Response<Full<Bytes>>, Infallible> {
199 let method = req.method().clone();
200 let path = req.uri().path().to_owned();
201 let auth = bearer(req.headers());
202 let offset = req
203 .headers()
204 .get(LOG_OFFSET)
205 .and_then(|v| v.to_str().ok())
206 .and_then(|v| v.parse::<u64>().ok());
207 let body = req
208 .into_body()
209 .collect()
210 .await
211 .map(|c| c.to_bytes().to_vec())
212 .unwrap_or_default();
213 // Slow claims down a little so an idle runner does not spin.
214 if path.ends_with("/claim") {
215 tokio::time::sleep(Duration::from_millis(20)).await;
216 }
217 let reply = {
218 let mut st = match state.lock() {
219 Ok(st) => st,
220 Err(poisoned) => poisoned.into_inner(),
221 };
222 route(&mut st, &method, &path, &auth, offset, &body)
223 };
224 let mut builder = Response::builder().status(reply.status);
225 if let Some(size) = reply.log_size {
226 builder = builder.header(LOG_SIZE, size.to_string());
227 }
228 let response = builder
229 .header("content-type", "application/json")
230 .body(Full::new(Bytes::from(reply.body)))
231 .unwrap_or_else(|_| Response::new(Full::new(Bytes::new())));
232 Ok(response)
233}
234
235/// Starts the mock forge on a random local port and returns its base URL.
236async fn start_mock(state: Shared) -> String {
237 let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
238 let addr = listener.local_addr().expect("addr");
239 tokio::spawn(async move {
240 loop {
241 let Ok((stream, _)) = listener.accept().await else {
242 break;
243 };
244 let st = state.clone();
245 tokio::spawn(async move {
246 let _ = http1::Builder::new()
247 .serve_connection(
248 TokioIo::new(stream),
249 service_fn(move |req| handle(st.clone(), req)),
250 )
251 .await;
252 });
253 }
254 });
255 format!("http://{addr}")
256}
257
258/// A git repo with one commit. Returns the commit id.
259fn make_repo(dir: &Path) -> String {
260 let repo = dir.join("repo");
261 std::fs::create_dir_all(&repo).expect("mkdir");
262 std::fs::write(repo.join("README.md"), "hello\n").expect("write");
263 let git = |args: &[&str]| {
264 let status = StdCommand::new("git")
265 .arg("-C")
266 .arg(&repo)
267 .args(args)
268 .status()
269 .expect("run git");
270 assert!(status.success(), "git {args:?} failed");
271 };
272 git(&["init", "-q"]);
273 git(&["add", "-A"]);
274 git(&[
275 "-c",
276 "user.name=test",
277 "-c",
278 "user.email=test@example.com",
279 "commit",
280 "-q",
281 "-m",
282 "init",
283 ]);
284 // Let a file:// fetch ask for the exact commit by id.
285 git(&["config", "uploadpack.allowAnySHA1InWant", "true"]);
286 let out = StdCommand::new("git")
287 .arg("-C")
288 .arg(&repo)
289 .args(["rev-parse", "HEAD"])
290 .output()
291 .expect("rev-parse");
292 String::from_utf8_lossy(&out.stdout).trim().to_owned()
293}
294
295fn job(job_id: &str, commit: &str, clone_url: &str, run: &str) -> JobAssignment {
296 JobAssignment {
297 job_id: job_id.to_owned(),
298 job_token: format!("token-for-{job_id}"),
299 repo: "owner/repo".to_owned(),
300 clone_url: clone_url.to_owned(),
301 commit: commit.to_owned(),
302 git_ref: "refs/heads/main".to_owned(),
303 job_name: "build".to_owned(),
304 image: "docker.io/library/alpine:3".to_owned(),
305 run: run.to_owned(),
306 env: BTreeMap::from([("GREETING".to_owned(), "hello-env".to_owned())]),
307 secrets: BTreeMap::from([("MY_TOKEN".to_owned(), SECRET_VALUE.to_owned())]),
308 artifacts: vec!["dist/**".to_owned()],
309 timeout_minutes: 5,
310 network: false,
311 cache: Vec::new(),
312 cache_key: String::new(),
313 cache_restore_keys: Vec::new(),
314 memory_bytes: None,
315 }
316}
317
318fn config(url: &str, work_dir: PathBuf) -> RunnerConfig {
319 RunnerConfig {
320 url: url.to_owned(),
321 runner_id: "runner-1".to_owned(),
322 runner_secret: RUNNER_SECRET.to_owned(),
323 name: "test-runner".to_owned(),
324 labels: vec!["linux".to_owned()],
325 work_dir,
326 concurrency: 1,
327 limits: Limits::default(),
328 executor: forge_runner::config::ExecutorKind::default(),
329 images: forge_runner::config::ImagesConfig::default(),
330 sandbox: forge_runner::config::SandboxConfig::default(),
331 registries: Vec::new(),
332 auto_update: true,
333 cache_max_gib: 0,
334 }
335}
336
337fn fast_options() -> RunOptions {
338 RunOptions {
339 heartbeat_every: Duration::from_millis(50),
340 claim_backoff: Duration::from_millis(50),
341 pump: PumpConfig {
342 flush_every: Duration::from_millis(50),
343 retries: 3,
344 retry_delay: Duration::from_millis(10),
345 },
346 timeout_override: None,
347 }
348}
349
350/// Polls `check` until it returns true or the deadline passes.
351async fn wait_until(what: &str, mut check: impl FnMut() -> bool) {
352 let deadline = Instant::now() + Duration::from_secs(60);
353 while !check() {
354 assert!(Instant::now() < deadline, "timed out waiting for {what}");
355 tokio::time::sleep(Duration::from_millis(20)).await;
356 }
357}
358
359struct Harness {
360 state: Shared,
361 stop: CancellationToken,
362 runner_task: tokio::task::JoinHandle<RunEnd>,
363 _dir: tempfile::TempDir,
364}
365
366/// Starts the mock, a runner with HostExecutor, and queues one job.
367async fn start(
368 run: &str,
369 mut options: RunOptions,
370 setup: impl FnOnce(&mut MockState),
371 timeout: Option<Duration>,
372) -> (Harness, String) {
373 let dir = tempfile::tempdir().expect("tempdir");
374 let commit = make_repo(dir.path());
375 let clone_url = format!("file://{}", dir.path().join("repo").display());
376 let job_id = "job-1";
377 let state: Shared = Arc::new(Mutex::new(MockState::default()));
378 {
379 let mut st = state.lock().expect("lock");
380 let j = job(job_id, &commit, &clone_url, run);
381 st.by_id.insert(j.job_id.clone(), j.clone());
382 st.pending.push(j);
383 setup(&mut st);
384 }
385 let url = start_mock(state.clone()).await;
386 options.timeout_override = timeout;
387 let cfg = config(&url, dir.path().join("work"));
388 let runner = Runner::new(cfg, Arc::new(HostExecutor), options).expect("runner");
389 let stop = CancellationToken::new();
390 let runner_task = {
391 let stop = stop.clone();
392 tokio::spawn(async move { runner.run(stop).await })
393 };
394 (
395 Harness {
396 state,
397 stop,
398 runner_task,
399 _dir: dir,
400 },
401 job_id.to_owned(),
402 )
403}
404
405async fn finish_of(h: &Harness, job_id: &str) -> FinishRequest {
406 let state = h.state.clone();
407 let id = job_id.to_owned();
408 wait_until("the job to finish", || {
409 state
410 .lock()
411 .map(|st| st.finished.contains_key(&id))
412 .unwrap_or(false)
413 })
414 .await;
415 h.state
416 .lock()
417 .expect("lock")
418 .finished
419 .get(job_id)
420 .cloned()
421 .expect("finish recorded")
422}
423
424async fn shut_down(h: Harness) {
425 h.stop.cancel();
426 let _ = tokio::time::timeout(Duration::from_secs(20), h.runner_task).await;
427}
428
429fn log_text(h: &Harness) -> String {
430 String::from_utf8_lossy(&h.state.lock().expect("lock").log).into_owned()
431}
432
433#[tokio::test]
434async fn full_flow_masks_secrets_and_uploads_artifacts() {
435 let run = "mkdir -p dist && echo built > dist/out.txt && echo \"token is $MY_TOKEN\" && \
436 echo \"b64 $(printf %s \"$MY_TOKEN\" | base64)\" && echo \"env is $GREETING\"";
437 let (h, job_id) = start(run, fast_options(), |_| {}, None).await;
438
439 let finish = finish_of(&h, &job_id).await;
440 assert_eq!(finish.outcome, Outcome::Success, "{finish:?}");
441 assert_eq!(finish.exit_code, Some(0));
442
443 let log = log_text(&h);
444 assert!(log.starts_with("forge-runner "), "info line first: {log:?}");
445 assert!(log.contains("token is ***"), "masked: {log:?}");
446 assert!(log.contains("env is hello-env"), "{log:?}");
447 assert!(!log.contains(SECRET_VALUE), "secret leaked into the log");
448 let b64 = base64_of(SECRET_VALUE);
449 assert!(
450 !log.contains(&b64),
451 "base64 of the secret leaked into the log"
452 );
453
454 let artifact = h
455 .state
456 .lock()
457 .expect("lock")
458 .artifacts
459 .get("dist_out.txt")
460 .cloned();
461 assert_eq!(artifact.as_deref(), Some(&b"built\n"[..]));
462
463 shut_down(h).await;
464}
465
466fn base64_of(text: &str) -> String {
467 use base64::Engine;
468 base64::engine::general_purpose::STANDARD.encode(text)
469}
470
471#[tokio::test]
472async fn heartbeat_cancel_stops_the_job() {
473 let mut options = fast_options();
474 options.heartbeat_every = Duration::from_millis(50);
475 let (h, job_id) = start(
476 "echo start; sleep 60",
477 options,
478 |st| st.cancel_from_heartbeat = Some(2),
479 None,
480 )
481 .await;
482
483 let started = Instant::now();
484 let finish = finish_of(&h, &job_id).await;
485 assert_eq!(finish.outcome, Outcome::Cancelled, "{finish:?}");
486 assert!(
487 started.elapsed() < Duration::from_secs(30),
488 "the job was not stopped"
489 );
490 shut_down(h).await;
491}
492
493#[tokio::test]
494async fn timeout_fails_the_job() {
495 let (h, job_id) = start(
496 "sleep 60",
497 fast_options(),
498 |_| {},
499 Some(Duration::from_millis(400)),
500 )
501 .await;
502
503 let finish = finish_of(&h, &job_id).await;
504 assert_eq!(finish.outcome, Outcome::Failure, "{finish:?}");
505 assert!(
506 finish
507 .message
508 .as_deref()
509 .unwrap_or_default()
510 .starts_with("timed out"),
511 "{finish:?}"
512 );
513 shut_down(h).await;
514}
515
516#[tokio::test]
517async fn log_offset_mismatch_resyncs_without_loss_or_duplicates() {
518 // Log POST #2 is applied by the forge for its first 3 bytes, then answered 409. The runner
519 // must drop those 3 bytes and continue, so the stored log has every line exactly once.
520 let run = "echo first; sleep 0.3; echo second; sleep 0.3; echo third";
521 let (h, job_id) = start(run, fast_options(), |st| st.ghost = Some((2, 3)), None).await;
522
523 let finish = finish_of(&h, &job_id).await;
524 assert_eq!(finish.outcome, Outcome::Success, "{finish:?}");
525
526 let log = log_text(&h);
527 assert!(log.ends_with("first\nsecond\nthird\n"), "log was {log:?}");
528 assert_eq!(
529 log.matches("second").count(),
530 1,
531 "duplicate or lost bytes: {log:?}"
532 );
533 let conflicts = h.state.lock().expect("lock").conflicts;
534 assert!(conflicts >= 1, "the 409 path never ran");
535 shut_down(h).await;
536}
537
538#[tokio::test]
539async fn acknowledged_batch_the_forge_lost_is_resent_in_order() {
540 // Log POST #2 is acknowledged but never stored. The next POST gets 409 with the smaller size,
541 // and the runner must resend the lost bytes from its retained buffer, with no gap marker.
542 let run = "echo first; sleep 0.3; echo second; sleep 0.3; echo third";
543 let (h, job_id) = start(run, fast_options(), |st| st.drop_post = Some(2), None).await;
544
545 let finish = finish_of(&h, &job_id).await;
546 assert_eq!(finish.outcome, Outcome::Success, "{finish:?}");
547
548 let log = log_text(&h);
549 assert!(log.ends_with("first\nsecond\nthird\n"), "log was {log:?}");
550 assert_eq!(log.matches("second").count(), 1, "duplicate bytes: {log:?}");
551 assert!(
552 !log.contains("[log gap]"),
553 "resend should not need a gap: {log:?}"
554 );
555 let conflicts = h.state.lock().expect("lock").conflicts;
556 assert!(conflicts >= 1, "the 409 path never ran");
557 shut_down(h).await;
558}