thirdshift 0.34.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Log pages and their independent append-only HTML stream.
use std::convert::Infallible;

use anyhow::{Context, Result, ensure};
use askama::Template;
use axum::extract::Path;
use axum::http::{HeaderMap, StatusCode};
use axum::response::{
    IntoResponse, Response, Sse,
    sse::{Event, KeepAlive},
};
use axum::{Extension, Json};
use serde::Serialize;

use super::conversation;
use super::subscription::{Readiness, Subscription};
use crate::config::UserConfig;
use crate::logs::Framing;
use crate::logs::catalog::{self, Log};
use crate::logs::status::GitHubTarget;

#[derive(Template)]
#[template(path = "console/logs.html")]
struct LogsPage {
    page: super::PageContext,
    groups: Vec<LogGroup>,
    owner: String,
}

/// One repository's logs, in catalog order; the page folds each group.
struct LogGroup {
    repository: String,
    logs: Vec<Log>,
}

impl LogGroup {
    fn live(&self) -> usize {
        self.logs.iter().filter(|log| log.live).count()
    }
}

/// Logs grouped by repository, the groups in order of their first log.
fn by_repository(logs: Vec<Log>) -> Vec<LogGroup> {
    let mut groups: Vec<LogGroup> = Vec::new();
    for log in logs {
        match groups
            .iter_mut()
            .find(|group| group.repository == log.repository)
        {
            Some(group) => group.logs.push(log),
            None => groups.push(LogGroup {
                repository: log.repository.clone(),
                logs: vec![log],
            }),
        }
    }
    groups
}

#[derive(Template)]
#[template(path = "console/reader.html")]
struct ReaderPage {
    page: super::PageContext,
    log: ReaderLog,
    target: Option<GitHubTarget>,
    html: String,
    offset: u64,
    live: bool,
    cli: String,
    details_url: String,
    stream: String,
    snapshot: bool,
    owning_console: Option<String>,
}

/// Presentation facts carry no filesystem reader. Remote logs use the same
/// template without manufacturing a local Log or opening an owning path.
struct ReaderLog {
    account: Option<String>,
    kind: catalog::Kind,
    name: String,
    selector: String,
}

pub(super) fn remote(
    remote: &super::fleet::read::Remote,
    config: &UserConfig,
    viewer: &super::auth::Viewer,
    format: super::api::Format,
    command: &str,
    session: &str,
) -> Result<Response> {
    let session = (!session.is_empty()).then(|| std::path::Path::new(session));
    let route = crate::logs::status::inspect::url("/log", command, session);
    let value = remote.get(&route)?;
    format.render(value, |value| {
        let contents = value["contents"]
            .as_str()
            .context("incompatible remote log")?;
        let target = (!command.is_empty())
            .then(|| {
                let peek_route = crate::logs::status::inspect::url("/peek", command, None);
                remote
                    .get(&peek_route)
                    .ok()
                    .and_then(|details| GitHubTarget::from_details(&details["command"]))
            })
            .flatten();
        let kind = if session.is_some() {
            catalog::Kind::Session
        } else {
            catalog::Kind::Command
        };
        let cli = format!(
            "thirdshift logs '{}'{} --machine '{}' --json",
            command.replace('\'', "'\\''"),
            session
                .map(|session| format!(
                    " --session '{}'",
                    session.display().to_string().replace('\'', "'\\''")
                ))
                .unwrap_or_default(),
            remote.entry.name.replace('\'', "'\\''")
        );
        Ok(ReaderPage {
            page: super::PageContext::new(config, &viewer.scopes),
            log: ReaderLog {
                account: None,
                kind,
                name: session.map_or_else(
                    || command.to_owned(),
                    |session| session.display().to_string(),
                ),
                selector: command.into(),
            },
            target,
            html: conversation::render(contents, kind),
            offset: 0,
            live: false,
            snapshot: true,
            stream: String::new(),
            cli,
            details_url: remote.command_url("/peek", command, None),
            owning_console: Some(super::fleet::read::owning_url(&remote.entry, &route)),
        }
        .render()?)
    })
}

/// A small, plain-text tail through the same confined reader as Full Command log.
pub(super) fn preview(config: &UserConfig, path: &std::path::Path) -> Result<String> {
    const BUDGET: usize = 4 * 1024;
    let log = catalog::load(config, None)?
        .into_iter()
        .find(|log| log.path == path)
        .context("Command log is unavailable")?;
    Ok(recent_output(&log.reader.tail(BUDGET)?))
}

pub(super) fn recent_output(bytes: &[u8]) -> String {
    // The reader applies the raw byte budget before UTF-8 normalization.
    // Applying it again to decoded text can discard readable output when
    // replacement characters expanded invalid bytes in the owning tail.
    let text = String::from_utf8_lossy(bytes);
    // The byte window can cut the oldest line; keep that suffix too, so a
    // complete line at the window boundary and very long lines stay visible.
    let mut lines: Vec<_> = text.lines().rev().take(5).collect();
    lines.reverse();
    lines.join("\n")
}

pub(super) async fn index(
    Extension(viewer): Extension<super::auth::Viewer>,
    Extension(format): Extension<super::api::Format>,
) -> Response {
    inventory(viewer, format, None).await
}
pub(super) async fn command(
    Path(id): Path<String>,
    Extension(viewer): Extension<super::auth::Viewer>,
    Extension(format): Extension<super::api::Format>,
) -> Response {
    inventory(viewer, format, Some(id)).await
}

async fn inventory(
    viewer: super::auth::Viewer,
    format: super::api::Format,
    owner: Option<String>,
) -> Response {
    super::api::read(format, move || {
        let config = UserConfig::load()?;
        let logs = catalog::load(&config, owner.as_deref())?;
        let value = serde_json::json!({"version": 1, "logs": logs});
        format.render(value, |_| {
            Ok(LogsPage {
                page: super::PageContext::new(&config, &viewer.scopes),
                groups: by_repository(logs),
                owner: owner.unwrap_or_default(),
            }
            .render()?)
        })
    })
    .await
}

enum OpenTarget {
    Id(String),
    Command {
        command: String,
        session: Option<String>,
    },
}

enum HtmlOutcome {
    Page(String),
    Forbidden,
    NotFound,
}

pub(super) async fn reader(
    Path(id): Path<String>,
    Extension(viewer): Extension<super::auth::Viewer>,
    Extension(format): Extension<super::api::Format>,
) -> Response {
    let allow_security = viewer.scopes.contains(&super::Scope::Security);
    if format == super::api::Format::Json {
        return super::api::read(format, move || {
            let config = UserConfig::load()?;
            match catalog::open(
                &config,
                catalog::OpenRequest::Id(&id),
                allow_security,
                false,
            )? {
                catalog::OpenOutcome::Opened(opened) => {
                    Ok(Json(catalog::contents(&opened.log.reader)?).into_response())
                }
                catalog::OpenOutcome::Forbidden => Ok(super::api::error(
                    StatusCode::FORBIDDEN,
                    "Missing scope: security",
                )),
                catalog::OpenOutcome::NotFound => Ok(super::api::error(
                    StatusCode::UNPROCESSABLE_ENTITY,
                    catalog::UNLISTED,
                )),
            }
        })
        .await;
    }
    render_html_reader(OpenTarget::Id(id), viewer).await
}

pub(super) async fn reader_for_command(
    command: String,
    session: Option<String>,
    viewer: super::auth::Viewer,
) -> Response {
    render_html_reader(OpenTarget::Command { command, session }, viewer).await
}

async fn render_html_reader(target: OpenTarget, viewer: super::auth::Viewer) -> Response {
    let allow_security = viewer.scopes.contains(&super::Scope::Security);
    let result = tokio::task::spawn_blocking(move || -> Result<HtmlOutcome> {
        let config = UserConfig::load()?;
        let outcome = match &target {
            OpenTarget::Id(id) => {
                catalog::open(&config, catalog::OpenRequest::Id(id), allow_security, true)?
            }
            OpenTarget::Command { command, session } => catalog::open(
                &config,
                catalog::OpenRequest::Command {
                    command,
                    session: session.as_deref(),
                },
                allow_security,
                true,
            )?,
        };
        let opened = match outcome {
            catalog::OpenOutcome::Opened(opened) => opened,
            catalog::OpenOutcome::Forbidden => return Ok(HtmlOutcome::Forbidden),
            catalog::OpenOutcome::NotFound => return Ok(HtmlOutcome::NotFound),
        };
        let log = opened.log;
        let lines = log.reader.read(0, Framing::Lines, usize::MAX)?;
        let html = conversation::render(&String::from_utf8_lossy(&lines.bytes), log.kind);
        Ok(HtmlOutcome::Page(
            ReaderPage {
                page: super::PageContext::new(&config, &viewer.scopes),
                cli: format!("thirdshift logs --file {}", log.id),
                details_url: crate::logs::status::inspect::url("/peek", &log.selector, None),
                stream: format!("/logs/{}/stream/{}", log.id, lines.offset),
                log: ReaderLog {
                    account: log.account,
                    kind: log.kind,
                    name: log.name,
                    selector: log.selector,
                },
                target: opened.target,
                html,
                offset: lines.offset,
                live: !lines.done,
                snapshot: false,
                owning_console: None,
            }
            .render()?,
        ))
    })
    .await;
    match result {
        Ok(Ok(HtmlOutcome::Page(html))) => super::page(Ok(Ok(html))),
        Ok(Ok(HtmlOutcome::Forbidden)) => {
            super::api::error(StatusCode::FORBIDDEN, "Missing scope: security")
        }
        Ok(Ok(HtmlOutcome::NotFound)) => {
            (StatusCode::NOT_FOUND, "Log is unavailable.").into_response()
        }
        Ok(Err(error)) => super::page(Ok(Err(error))),
        Err(error) => super::page(Err(error)),
    }
}

#[derive(Debug, Serialize)]
struct Batch {
    html: String,
    offset: u64,
    done: bool,
}

fn appended(log: &Log, offset: u64) -> Result<Batch> {
    let lines = log.reader.read(offset, Framing::Lines, 256 * 1024)?;
    Ok(Batch {
        html: conversation::render(&String::from_utf8_lossy(&lines.bytes), log.kind),
        offset: lines.offset,
        done: lines.done,
    })
}

pub(super) async fn stream(
    Path((id, offset)): Path<(String, u64)>,
    Extension(changes): Extension<super::changes::Receiver>,
    Extension(notifier): Extension<super::changes::Notifier>,
    Extension(viewer): Extension<super::auth::Viewer>,
    headers: HeaderMap,
) -> Response {
    // A finite request uses the same reader and offset as SSE when a proxy
    // cannot keep streams open. It still crosses the normal account guard.
    let allow_security = viewer.scopes.contains(&super::Scope::Security);
    if headers
        .get("accept")
        .is_some_and(|value| value == "application/json")
    {
        return match tokio::task::spawn_blocking(move || -> Result<_> {
            let config = UserConfig::load()?;
            match catalog::open(
                &config,
                catalog::OpenRequest::Id(&id),
                allow_security,
                false,
            )? {
                catalog::OpenOutcome::Opened(opened) => Ok(Ok(appended(&opened.log, offset)?)),
                catalog::OpenOutcome::Forbidden => Ok(Err(true)),
                catalog::OpenOutcome::NotFound => Ok(Err(false)),
            }
        })
        .await
        {
            Ok(Ok(Ok(batch))) => Json(batch).into_response(),
            Ok(Ok(Err(true))) => {
                super::api::error(StatusCode::FORBIDDEN, "Missing scope: security")
            }
            Ok(Ok(Err(false))) => {
                super::api::error(StatusCode::UNPROCESSABLE_ENTITY, catalog::UNLISTED)
            }
            Ok(Err(error)) => super::page(Ok(Err(error))),
            Err(error) => super::page(Err(error)),
        };
    }
    let offset = headers
        .get("last-event-id")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.parse().ok())
        .unwrap_or(offset);
    let checked = tokio::task::spawn_blocking(move || -> Result<_> {
        let config = UserConfig::load()?;
        match catalog::open(
            &config,
            catalog::OpenRequest::Id(&id),
            allow_security,
            false,
        )? {
            catalog::OpenOutcome::Opened(opened) => {
                ensure!(
                    offset <= std::fs::metadata(&opened.log.path)?.len(),
                    "invalid log offset"
                );
                Ok(Ok(opened.log))
            }
            catalog::OpenOutcome::Forbidden => Ok(Err(true)),
            catalog::OpenOutcome::NotFound => Ok(Err(false)),
        }
    })
    .await;
    let state = match checked {
        Ok(Ok(Ok(log))) => LogStream {
            log: std::sync::Arc::new(log),
            offset,
            done: false,
            subscription: Subscription::new(changes, viewer, &notifier),
        },
        Ok(Ok(Err(true))) => {
            return super::api::error(StatusCode::FORBIDDEN, "Missing scope: security");
        }
        _ => return StatusCode::NOT_FOUND.into_response(),
    };
    let events = futures_util::stream::unfold(state, |mut state| async move {
        if state.done {
            return None;
        }
        // Buffered output drains without another notification; only an
        // empty unfinished read sleeps until the next change.
        let mut mode = Readiness::Drain;
        loop {
            let result = match state.subscription.ready(mode).await {
                Ok(true) => {
                    let selected = state.log.clone();
                    let offset = state.offset;
                    // The captured reader rejects a file that leaves the inventory.
                    match tokio::task::spawn_blocking(move || appended(&selected, offset)).await {
                        Ok(read) => read,
                        Err(error) => Err(error.into()),
                    }
                }
                Ok(false) => return None,
                Err(error) => Err(error),
            };
            match result {
                Ok(batch) if batch.offset != state.offset || batch.done => {
                    state.offset = batch.offset;
                    state.done = batch.done;
                    let event = Event::default()
                        .event("lines")
                        .id(state.offset.to_string())
                        .data(serde_json::to_string(&batch).expect("serializable log batch"));
                    return Some((Ok::<_, Infallible>(event), state));
                }
                Ok(_) => mode = Readiness::Wait,
                Err(error) => {
                    eprintln!("thirdshift Console: log stream: {error:?}");
                    let event = Event::default()
                        .event("log-error")
                        .data("Can't read log; reopen the reader. Check the Console's stderr.");
                    state.done = true;
                    return Some((Ok(event), state));
                }
            }
        }
    });
    let mut response = Sse::new(events)
        .keep_alive(KeepAlive::default())
        .into_response();
    response
        .headers_mut()
        .insert("x-accel-buffering", "no".parse().unwrap());
    response
        .headers_mut()
        .insert("cache-control", "no-store".parse().unwrap());
    response
}

struct LogStream {
    log: std::sync::Arc<Log>,
    offset: u64,
    done: bool,
    subscription: Subscription,
}