summaryrefslogtreecommitdiffstats
path: root/src/http/sse.rs
blob: bceba9fee4e7b329c46cf07998bef05e02a138f3 (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
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use crate::db::builds;

const MAX_LIFETIME: Duration = Duration::from_secs(30 * 60);
const KEEPALIVE: Duration = Duration::from_secs(10);
const POLL: Duration = Duration::from_millis(200);

pub struct LogTail {
    path: PathBuf,
    build_id: String,
    db: crate::db::Db,
    offset: u64,
    out: std::collections::VecDeque<u8>,
    started: Instant,
    since_keepalive: Duration,
    ended: bool,
}

impl LogTail {
    pub fn new(cfg: &crate::config::Config, db: crate::db::Db, build_id: &str) -> Self {
        Self {
            path: cfg.build_log_path(build_id),
            build_id: build_id.to_string(),
            db,
            offset: 0,
            out: std::collections::VecDeque::new(),
            started: Instant::now(),
            since_keepalive: Duration::ZERO,
            ended: false,
        }
    }

    fn terminal(&self) -> bool {
        match builds::get(&self.db, &self.build_id) {
            Ok(Some(b)) => b.state.is_terminal(),
            Ok(None) => true,
            Err(_) => false,
        }
    }

    fn pump(&mut self) {
        let (bytes, grew) = read_from(&self.path, self.offset);
        if grew {
            self.offset += bytes.len() as u64;
            for line in String::from_utf8_lossy(&bytes).lines() {
                self.out.extend(format!("data: {line}\n\n").as_bytes());
            }
            self.since_keepalive = Duration::ZERO;
        }
    }

    fn finish(&mut self) {
        if self.ended {
            return;
        }
        self.ended = true;
        self.out.extend(b"event: end\ndata: done\n\n");
    }
}

impl Read for LogTail {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        loop {
            if !self.out.is_empty() {
                let n = buf.len().min(self.out.len());
                for (i, b) in self.out.drain(..n).enumerate() {
                    buf[i] = b;
                }
                return Ok(n);
            }
            if self.ended {
                return Ok(0);
            }
            self.pump();
            if !self.out.is_empty() {
                continue;
            }
            if self.terminal() {
                // One more pump in case the last lines landed with the state
                // change; a race here would silently drop the end of a log.
                self.pump();
                if self.out.is_empty() {
                    self.finish();
                }
                continue;
            }
            if self.started.elapsed() > MAX_LIFETIME {
                self.finish();
                continue;
            }
            crate::time::sleep(POLL);
            self.since_keepalive += POLL;
            if self.since_keepalive >= KEEPALIVE {
                self.since_keepalive = Duration::ZERO;
                self.out.extend(b": keepalive\n\n");
            }
        }
    }
}

fn read_from(path: &Path, offset: u64) -> (Vec<u8>, bool) {
    let mut f = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return (Vec::new(), false),
    };
    use std::io::Seek;
    if f.seek(std::io::SeekFrom::Start(offset)).is_err() {
        return (Vec::new(), false);
    }
    let mut buf = Vec::new();
    if f.read_to_end(&mut buf).is_err() {
        return (Vec::new(), false);
    }
    let grew = !buf.is_empty();
    (buf, grew)
}