Skip to main content

isothrum_runner/store/db/
downloads.rs

1//! What the runs' own downloads fetched: one row per image a Compose start's pull pulled and per
2//! box a Vagrant `up` added, each recorded once (a second fetch of the same one keeps the first
3//! row), forgotten once it is removed or found gone.
4
5use rusqlite::{Row, params};
6
7use super::{Tx, failed, now};
8use crate::Result;
9use crate::downloads::{Download, DownloadId, DownloadItem};
10use crate::name::RunName;
11
12/// The columns a [`Download`] is read from, in [`raw_download`]'s order.
13const DOWNLOAD_COLUMNS: &str = "id, kind, name, image_id, docker_context, provider, version, architecture, run, fetched_at";
14
15/// The text columns of a download's row, before they are parsed.
16struct RawDownload {
17    id: i64,
18    kind: String,
19    name: String,
20    image_id: Option<String>,
21    docker_context: Option<String>,
22    provider: Option<String>,
23    version: Option<String>,
24    architecture: Option<String>,
25    run: Option<String>,
26    fetched_at: String,
27}
28
29fn raw_download(r: &Row<'_>) -> rusqlite::Result<RawDownload> {
30    Ok(RawDownload {
31        id: r.get(0)?,
32        kind: r.get(1)?,
33        name: r.get(2)?,
34        image_id: r.get(3)?,
35        docker_context: r.get(4)?,
36        provider: r.get(5)?,
37        version: r.get(6)?,
38        architecture: r.get(7)?,
39        run: r.get(8)?,
40        fetched_at: r.get(9)?,
41    })
42}
43
44fn download(raw: RawDownload) -> Result<Download> {
45    let missing = |column: &str| super::corrupt(column, "nothing");
46    let item = match raw.kind.as_str() {
47        "image" => DownloadItem::Image {
48            reference: raw.name,
49            image_id: raw.image_id.ok_or_else(|| missing("download's image id"))?,
50            docker_context: raw.docker_context,
51        },
52        "box" => DownloadItem::Box {
53            name: raw.name,
54            provider: raw.provider.ok_or_else(|| missing("download's provider"))?,
55            version: raw.version.ok_or_else(|| missing("download's version"))?,
56            architecture: raw.architecture,
57        },
58        other => return Err(super::corrupt("download kind", other)),
59    };
60    Ok(Download {
61        id: DownloadId(raw.id),
62        item,
63        run: raw
64            .run
65            .map(|run| RunName::new(&run).map_err(|_| super::corrupt("run name", &run)))
66            .transpose()?,
67        fetched_at: raw.fetched_at,
68        size_bytes: None,
69    })
70}
71
72impl Tx<'_> {
73    /// Records that run `run`'s tool fetched `item` (no run: adopted); one recorded already keeps
74    /// its row. Whether it was new to the record.
75    ///
76    /// # Errors
77    ///
78    /// The store can't be written.
79    pub fn record_download(&mut self, run: Option<&RunName>, item: &DownloadItem) -> Result<bool> {
80        let (kind, name, image_id, context, provider, version, arch) = match item {
81            DownloadItem::Image {
82                reference,
83                image_id,
84                docker_context,
85            } => ("image", reference, Some(image_id), docker_context.as_ref(), None, None, None),
86            DownloadItem::Box {
87                name,
88                provider,
89                version,
90                architecture,
91            } => ("box", name, None, None, Some(provider), Some(version), architecture.as_ref()),
92        };
93        let added = self
94            .tx
95            .execute(
96                "INSERT OR IGNORE INTO downloads (kind, name, image_id, docker_context, provider, version, architecture, run, fetched_at)
97                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
98                params![kind, name, image_id, context, provider, version, arch, run.map(RunName::as_str), now()],
99            )
100            .map_err(failed("written"))?;
101        Ok(added > 0)
102    }
103
104    /// Every recorded download, oldest first (its size unread).
105    ///
106    /// # Errors
107    ///
108    /// The store can't be read, or a row holds what this runner doesn't write.
109    pub fn downloads(&self) -> Result<Vec<Download>> {
110        let sql = format!("SELECT {DOWNLOAD_COLUMNS} FROM downloads ORDER BY id");
111        let mut stmt = self.tx.prepare(&sql).map_err(failed("read"))?;
112        let found = stmt.query_map([], raw_download).map_err(failed("read"))?;
113        let mut rows = Vec::new();
114        for raw in found {
115            rows.push(download(raw.map_err(failed("read"))?)?);
116        }
117        Ok(rows)
118    }
119
120    /// Forgets download `id` (removed, or found gone); one not recorded is fine.
121    ///
122    /// # Errors
123    ///
124    /// The store can't be written.
125    pub fn forget_download(&mut self, id: DownloadId) -> Result<()> {
126        self.tx.execute("DELETE FROM downloads WHERE id = ?1", [id.0]).map_err(failed("written"))?;
127        Ok(())
128    }
129}