aboutsummaryrefslogtreecommitdiff
path: root/src/manager/updater.rs
blob: ca04ce9dc24adca061f08587418ecbbe64edf950 (plain) (blame)
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
// SPDX-License-Identifier: LGPL-3.0-or-later
//
// Copyright 2019 Hristo Venev

use super::Source;
use crate::{config, fileutil, proto};
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;
use std::time::{Duration, Instant};
use std::{fs, io};

pub(super) struct Updater {
    config: config::UpdaterConfig,
}

impl Updater {
    pub fn new(config: config::UpdaterConfig) -> Self {
        Self { config }
    }

    fn cache_path(&self, s: &Source) -> Option<PathBuf> {
        let mut p = self.config.cache_directory.as_ref()?.clone();
        p.push(&s.config.name);
        Some(p)
    }

    fn cache_update(&self, src: &Source) {
        let path = match self.cache_path(src) {
            Some(v) => v,
            None => return,
        };

        let data = serde_json::to_vec(&src.data).unwrap();
        match fileutil::update(&path, &data) {
            Ok(()) => {}
            Err(e) => {
                eprintln!("<4>Failed to cache [{}]: {}", &src.config.name, e);
            }
        }
    }

    pub fn cache_load(&self, src: &mut Source) -> bool {
        let path = match self.cache_path(src) {
            Some(v) => v,
            None => return false,
        };

        let data = match fileutil::load(&path) {
            Ok(data) => data,
            Err(e) => {
                if e.kind() != io::ErrorKind::NotFound {
                    eprintln!("<3>Failed to read [{}] from cache: {}", &src.config.name, e);
                }
                return false;
            }
        };

        let mut de = serde_json::Deserializer::from_slice(&data);
        src.data = match serde::Deserialize::deserialize(&mut de) {
            Ok(r) => r,
            Err(e) => {
                eprintln!("<3>Failed to load [{}] from cache: {}", &src.config.name, e);
                return false;
            }
        };

        true
    }

    pub fn update(&self, src: &mut Source) -> (bool, Instant) {
        let refresh = self.refresh_time();

        let r = fetch_source(&src.config.url);
        let now = Instant::now();
        let r = match r {
            Ok(r) => {
                eprintln!("<6>Updated [{}]", &src.config.url);
                src.data = r;
                src.backoff = None;
                src.next_update = now + refresh;
                self.cache_update(src);
                return (true, now);
            }
            Err(r) => r,
        };

        let b = src
            .backoff
            .unwrap_or_else(|| Duration::from_secs(10).min(refresh / 10));
        src.next_update = now + b;
        src.backoff = Some((b + b / 3).min(refresh / 3));
        eprintln!(
            "<3>Failed to update [{}], retrying after {:.1?}: {}",
            &src.config.url, b, &r
        );
        (false, now)
    }

    pub fn refresh_time(&self) -> Duration {
        Duration::from_secs(u64::from(self.config.refresh_sec))
    }
}

fn fetch_source(url: &str) -> io::Result<proto::Source> {
    use std::env;
    use std::process::{Command, Stdio};

    let curl = match env::var_os("CURL") {
        None => OsString::new(),
        Some(v) => v,
    };
    let mut proc = Command::new(if curl.is_empty() {
        OsStr::new("curl")
    } else {
        curl.as_os_str()
    });

    proc.stdin(Stdio::null());
    proc.stdout(Stdio::piped());
    proc.stderr(Stdio::piped());
    proc.arg("-gsSfL");
    proc.arg("--fail-early");
    proc.arg("--max-time");
    proc.arg("10");
    proc.arg("--max-filesize");
    proc.arg("1M");
    proc.arg("--");
    proc.arg(url);

    let out = proc.output()?;

    if !out.status.success() {
        let msg = String::from_utf8_lossy(&out.stderr);
        let msg = msg.replace('\n', "; ");
        return Err(io::Error::new(io::ErrorKind::Other, msg));
    }

    let mut de = serde_json::Deserializer::from_slice(&out.stdout);
    let r = serde::Deserialize::deserialize(&mut de)?;
    Ok(r)
}

pub fn load_source(path: &OsStr) -> io::Result<proto::Source> {
    let mut data = Vec::new();
    {
        use std::io::Read;
        let mut f = fs::File::open(&path)?;
        f.read_to_end(&mut data)?;
    }

    let mut de = serde_json::Deserializer::from_slice(&data);
    let r = serde::Deserialize::deserialize(&mut de)?;
    Ok(r)
}