Skip to content
360 linesCodeBlameRaw
1//! Telling g1t how a job is going: its steps, its log in batches, its
2//! annotations, and how it ended. Every report carries the job's token.
3
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::time::{Duration, Instant};
6
7use anyhow::Result;
8use g1t_actions::mask;
9use serde_json::{Value, json};
10
11/// How long log lines wait before they are sent.
12const FLUSH_EVERY: Duration = Duration::from_millis(1500);
13/// How much log is sent at once.
14const FLUSH_BYTES: usize = 64 * 1024;
15/// The most one step may add to the job's summary, as on GitHub.
16pub(crate) const MAX_SUMMARY_BYTES: usize = 1024 * 1024;
17/// How long the runner goes without a report before it asks whether the
18/// job was cancelled.
19const PING_EVERY: Duration = Duration::from_secs(10);
20
21/// Whether the job was cancelled, as g1t's answers to its reports say.
22struct Cancel {
23 /// g1t said so.
24 said: AtomicBool,
25 /// The job has taken it in: the step it was on was stopped, and the
26 /// cleanup steps that follow are not stopped for it again.
27 taken: AtomicBool,
28}
29
30impl Cancel {
31 const fn new() -> Cancel {
32 Cancel { said: AtomicBool::new(false), taken: AtomicBool::new(false) }
33 }
34
35 /// Reads an answer to a report: `cancelled` when the run was cancelled.
36 fn hear(&self, answer: &Value) {
37 if answer["cancelled"].as_bool() == Some(true) {
38 self.said.store(true, Ordering::Relaxed);
39 }
40 }
41
42 fn cancelled(&self) -> bool {
43 self.said.load(Ordering::Relaxed)
44 }
45
46 fn interrupt(&self) -> bool {
47 self.cancelled() && !self.taken.load(Ordering::Relaxed)
48 }
49
50 fn take(&self) {
51 self.taken.store(true, Ordering::Relaxed);
52 }
53}
54
55/// This job's (one runs per process).
56static CANCEL: Cancel = Cancel::new();
57
58/// Whether g1t said the job was cancelled.
59pub(crate) fn cancelled() -> bool {
60 CANCEL.cancelled()
61}
62
63/// Whether a running step should be stopped: cancelled, and not yet taken in.
64pub(crate) fn interrupt() -> bool {
65 CANCEL.interrupt()
66}
67
68/// The job has seen the cancellation: what runs from here is its cleanup.
69pub(crate) fn take_cancel() {
70 CANCEL.take();
71}
72
73pub(crate) struct Api {
74 pub(crate) base: String,
75 pub(crate) job: String,
76 pub(crate) token: String,
77}
78
79impl Api {
80 pub(crate) fn spec(&self) -> Result<Value> {
81 let response = ureq::post(&format!("{}/actions/jobs/{}/spec", self.base, self.job))
82 .timeout(Duration::from_secs(60))
83 .send_json(json!({ "token": self.token }))?;
84 Ok(response.into_json()?)
85 }
86
87 /// Where to fetch another repository's action from: `{"source": "g1t",
88 /// "url", "ref", "token"}` or `{"source": "github"}`. Err holds why g1t
89 /// refused (`true`: the repository is private and may not be used
90 /// here), or that it could not be asked (`false`).
91 pub(crate) fn action(&self, repository: &str, git_ref: &str) -> std::result::Result<Value, (bool, String)> {
92 let sent = ureq::post(&format!("{}/actions/jobs/{}/action", self.base, self.job))
93 .timeout(Duration::from_secs(30))
94 .send_json(json!({ "token": self.token, "report": { "repository": repository, "ref": git_ref } }));
95 match sent {
96 Ok(response) => response.into_json().map_err(|error| (false, error.to_string())),
97 Err(ureq::Error::Status(code, response)) => {
98 let body: Value = response.into_json().unwrap_or(Value::Null);
99 let message = body["error"]["message"].as_str().unwrap_or("g1t did not answer.").to_owned();
100 Err((code == 403, message))
101 }
102 Err(error) => Err((false, error.to_string())),
103 }
104 }
105
106 /// An API with no address, which sends nothing: what the tests use, so
107 /// a step's run is not held up by reports that go nowhere (each one
108 /// tried three times, with waits between, over a second and a half).
109 #[cfg(test)]
110 pub(crate) fn offline() -> Api {
111 Api { base: String::new(), job: "job_1".into(), token: "t".into() }
112 }
113
114 pub(crate) fn report(&self, report: Value) {
115 // No address: nowhere to send it (Api::offline).
116 if self.base.is_empty() {
117 return;
118 }
119 // A report that cannot be sent is tried a few times, then dropped:
120 // the job goes on, and g1t notices a silent job by itself.
121 for attempt in 0..3 {
122 let sent = ureq::post(&format!("{}/actions/jobs/{}", self.base, self.job))
123 .timeout(Duration::from_secs(30))
124 .send_json(json!({ "token": self.token, "report": report }));
125 match sent {
126 Ok(response) => {
127 if let Ok(answer) = response.into_json::<Value>() {
128 CANCEL.hear(&answer);
129 }
130 return;
131 }
132 // Refused: the job was cancelled or finished; nothing to retry.
133 Err(ureq::Error::Status(code, _)) if (400..500).contains(&code) => return,
134 Err(_) => std::thread::sleep(Duration::from_millis(500 * (attempt + 1))),
135 }
136 }
137 }
138}
139
140/// The job's log, masked, sent in batches. `masks` holds every form of
141/// every secret (`g1t_actions::mask`), longest first.
142pub(crate) struct Log {
143 pub(crate) api: Api,
144 pub(crate) masks: Vec<String>,
145 step: u32,
146 buffer: String,
147 last: Instant,
148 /// When anything was last sent, for the ping.
149 sent: Instant,
150 /// Everything sent so far, so a test reads the whole log however its
151 /// batches fell (`buffered`).
152 #[cfg(test)]
153 flushed: String,
154}
155
156impl Log {
157 pub(crate) fn new(api: Api, mut masks: Vec<String>) -> Log {
158 masks.retain(|mask| !mask.is_empty());
159 masks.sort_by_key(|mask| std::cmp::Reverse(mask.len()));
160 Log {
161 api,
162 masks,
163 step: 0,
164 buffer: String::new(),
165 last: Instant::now(),
166 sent: Instant::now(),
167 #[cfg(test)]
168 flushed: String::new(),
169 }
170 }
171
172 /// The log so far: what was sent and what waits to be.
173 #[cfg(all(test, unix))]
174 pub(crate) fn buffered(&self) -> String {
175 format!("{}{}", self.flushed, self.buffer)
176 }
177
178 /// Starts writing to step `number` (0 for the job's setup).
179 pub(crate) fn step(&mut self, number: u32) {
180 self.flush();
181 self.step = number;
182 }
183
184 pub(crate) fn mask(&self, text: &str) -> String {
185 mask::apply(text, &self.masks)
186 }
187
188 /// `::add-mask::`: masks `value` from here on, in every form it can
189 /// take (each line, base64, JSON-escaped), as a secret is.
190 pub(crate) fn add_mask(&mut self, value: &str) {
191 let mut added = false;
192 for variant in mask::variants(value) {
193 if !self.masks.contains(&variant) {
194 self.masks.push(variant);
195 added = true;
196 }
197 }
198 if added {
199 self.masks.sort_by_key(|mask| std::cmp::Reverse(mask.len()));
200 }
201 }
202
203 pub(crate) fn line(&mut self, text: &str) {
204 let masked = self.mask(text);
205 self.buffer.push_str(&masked);
206 self.buffer.push('\n');
207 if self.buffer.len() >= FLUSH_BYTES || self.last.elapsed() >= FLUSH_EVERY {
208 self.flush();
209 }
210 }
211
212 /// Sends what is waiting if it has waited long enough, and asks after
213 /// the job when nothing has been sent for a while, so a cancellation
214 /// reaches a step that prints nothing.
215 pub(crate) fn tick(&mut self) {
216 if !self.buffer.is_empty() && self.last.elapsed() >= FLUSH_EVERY {
217 self.flush();
218 } else if self.sent.elapsed() >= PING_EVERY {
219 self.sent = Instant::now();
220 self.api.report(json!({ "kind": "ping" }));
221 }
222 }
223
224 pub(crate) fn flush(&mut self) {
225 self.last = Instant::now();
226 if self.buffer.is_empty() {
227 return;
228 }
229 self.sent = Instant::now();
230 let text = std::mem::take(&mut self.buffer);
231 #[cfg(test)]
232 self.flushed.push_str(&text);
233 self.api.report(json!({ "kind": "log", "step": self.step, "text": text }));
234 }
235
236 pub(crate) fn steps(&self, names: &[String]) {
237 self.api.report(json!({ "kind": "steps", "steps": names }));
238 }
239
240 pub(crate) fn step_state(&mut self, number: u32, name: &str, status: &str, conclusion: Option<&str>) {
241 self.flush();
242 let name = self.mask(name);
243 self.api.report(json!({ "kind": "step", "number": number, "name": name, "status": status, "conclusion": conclusion }));
244 }
245
246 /// What a step wrote to `$GITHUB_STEP_SUMMARY`, masked, for the run's
247 /// page. More than 1 MiB is refused, as on GitHub, with an error in the
248 /// log.
249 pub(crate) fn summary(&mut self, markdown: &str) {
250 if markdown.trim().is_empty() {
251 return;
252 }
253 if markdown.len() > MAX_SUMMARY_BYTES {
254 self.line(&format!(
255 "##[error]$GITHUB_STEP_SUMMARY upload aborted: a step's summary may be up to 1024k, and this one is {}k.",
256 markdown.len().div_ceil(1024)
257 ));
258 return;
259 }
260 let markdown = self.mask(markdown);
261 self.flush();
262 self.api.report(json!({ "kind": "summary", "step": self.step, "markdown": markdown }));
263 }
264
265 pub(crate) fn annotation(&mut self, level: &str, message: &str, properties: &serde_json::Map<String, Value>) {
266 let message = self.mask(message);
267 let title = properties.get("title").and_then(Value::as_str).map(|title| self.mask(title));
268 self.api.report(json!({
269 "kind": "annotation",
270 "level": level,
271 "message": message,
272 "title": title,
273 "file": properties.get("file"),
274 "line": properties.get("line").and_then(|l| l.as_str()).and_then(|l| l.parse::<u32>().ok()),
275 }));
276 }
277
278 pub(crate) fn done(&mut self, conclusion: &str, outputs: &serde_json::Map<String, Value>, reason: Option<&str>) {
279 let outputs = self.withhold_secrets(outputs);
280 self.flush();
281 self.api.report(json!({ "kind": "done", "conclusion": conclusion, "outputs": outputs, "reason": reason }));
282 }
283
284 /// The job's outputs without any that hold a secret, as on GitHub: an
285 /// output goes to other jobs and to the run's page, where no mask
286 /// reaches. Each one left out is warned of in the log.
287 pub(crate) fn withhold_secrets(&mut self, outputs: &serde_json::Map<String, Value>) -> serde_json::Map<String, Value> {
288 let mut kept = serde_json::Map::new();
289 for (name, value) in outputs {
290 let text = match value {
291 Value::String(text) => text.clone(),
292 other => other.to_string(),
293 };
294 if mask::reveals(&text, &self.masks) {
295 self.line(&format!("##[warning]The output `{name}` was left out: it holds a secret."));
296 continue;
297 }
298 kept.insert(name.clone(), value.clone());
299 }
300 kept
301 }
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 fn log(secrets: &[&str]) -> Log {
309 Log::new(Api::offline(), mask::all_variants(secrets.iter().copied()))
310 }
311
312 #[test]
313 fn outputs_holding_a_secret_are_left_out() {
314 let mut log = log(&["s3cr3t-token"]);
315 let mut outputs = serde_json::Map::new();
316 outputs.insert("version".into(), json!("1.2.0"));
317 outputs.insert("leak".into(), json!("token=s3cr3t-token"));
318 outputs.insert("encoded".into(), json!("czNjcjN0LXRva2Vu"));
319 let kept = log.withhold_secrets(&outputs);
320 assert_eq!(kept.keys().collect::<Vec<_>>(), ["version"]);
321 assert!(log.buffer.contains("The output `leak` was left out"));
322 assert!(log.buffer.contains("The output `encoded` was left out"));
323 }
324
325 #[test]
326 fn a_cancelled_answer_is_heard_once_and_taken_in() {
327 let cancel = Cancel::new();
328 cancel.hear(&json!({ "ok": true }));
329 assert!(!cancel.cancelled());
330 cancel.hear(&json!({ "ok": true, "cancelled": true }));
331 assert!(cancel.cancelled() && cancel.interrupt());
332 cancel.take();
333 assert!(cancel.cancelled() && !cancel.interrupt(), "cleanup steps are not stopped again");
334 cancel.hear(&json!({ "ok": true, "cancelled": false }));
335 assert!(cancel.cancelled(), "a cancelled job stays cancelled");
336 }
337
338 #[test]
339 fn a_summary_past_its_limit_is_refused_in_the_log() {
340 let mut log = log(&[]);
341 log.summary("
342");
343 assert!(log.buffer.is_empty(), "an empty summary is not sent");
344 log.summary(&"x".repeat(MAX_SUMMARY_BYTES + 1));
345 assert!(log.buffer.contains("$GITHUB_STEP_SUMMARY upload aborted"));
346 assert!(log.buffer.contains("1025k"));
347 }
348
349 #[test]
350 fn added_masks_cover_every_form() {
351 let mut log = log(&[]);
352 log.add_mask("line one\nline two");
353 assert_eq!(log.mask("first: line one"), "first: ***");
354 assert_eq!(log.mask("then line two"), "then ***");
355 // Longest first: the whole value, not its pieces.
356 log.add_mask("abc");
357 log.add_mask("abcdef");
358 assert_eq!(log.mask("abcdef"), "***");
359 }
360}