Cotton code
134 lines · 6.0 KB · RustRaw
//! THE OPEN BUNDLE, laid into a folder — a library leaves Cotton in shapes//! other apps open.//!//! The tree itself is [`cotton_rules::open_bundle`]'s: the one writer the//! phone and the Worker share, handed rows and what is known of their media,//! answering each file as its text or the media key whose bytes it is. This//! module is the store's side of it: it reads the kit's live rows from a copy,//! answers the rule's media questions from a [`MediaSource`], and writes the//! tree into a folder.//!//! The store holds no bytes: they are read through a [`MediaSource`], the same//! door [`crate::cottonpkg::export_package`] reads by.use std::collections::BTreeMap;use std::path::Path;use cotton_rules::open_bundle::{lay, Entry, Held, Laid, Library, Row, LISTS, LIST_MEMBERS};pub use cotton_rules::open_bundle::Kit;use serde_json::Value as JsonValue;use crate::cottonpkg::MediaSource;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::schema::codecs::decode_row;use crate::schema::package_shape::spec_on;/// What a bundle laid.#[derive(Debug, Clone, PartialEq, Default)]pub struct Written {    /// Every file written, relative to the bundle's folder, `/`-separated and    /// sorted.    pub files: Vec<String>,    /// Keys a row names whose bytes the media source does not hold: the row's    /// metadata is written, its file is not.    pub missing_media: Vec<String>,}/// Lay `kit`'s open tree from `copy` into `out_dir/<kit root>/`.////// `exported_at` is the caller's clock (an RFC 3339 instant): the store reads/// none, and the formats that must say when they were made (an Atom feed's/// `updated`, OPML's `dateCreated`) say this. Refuses a kit root that is/// already there and not empty, rather than writing into someone's folder, and/// a copy that does not hold the kit's tables.pub fn write_open_bundle(    copy: &Driver,    kit: Kit,    out_dir: &Path,    media: &mut dyn MediaSource,    exported_at: &str,) -> Result<Written> {    let root = out_dir.join(kit.root());    if std::fs::read_dir(&root).map(|mut entries| entries.next().is_some()).unwrap_or(false) {        return Err(refuse(format!("{} is already there and holds files: an open bundle is laid into an empty folder", root.display())));    }    let mut library = Library {        kit,        tables: library_rows(copy, kit)?,        database: crate::file_identity::read_file_identity(copy)?.map(|identity| identity.id().as_str().to_string()).unwrap_or_default(),        exported_at: exported_at.to_string(),        media: true,        known: BTreeMap::new(),    };    let (entries, missing_media) = loop {        match lay(&library).map_err(refuse)? {            Laid::Asks(asks) => {                for ask in asks {                    let held = if ask.read {                        media.read(&ask.key)?.map_or(Held::Missing, |bytes| Held::Text(String::from_utf8_lossy(&bytes).into_owned()))                    } else if media.has(&ask.key)? {                        Held::Held                    } else {                        Held::Missing                    };                    library.known.insert(ask.key, held);                }            }            Laid::Tree { entries, missing_media } => break (entries, missing_media),        }    };    let mut files = Vec::with_capacity(entries.len());    for entry in entries {        let path = out_dir.join(entry.path());        if let Some(parent) = path.parent() {            std::fs::create_dir_all(parent).map_err(|error| refuse(format!("{} could not be made: {error}", parent.display())))?;        }        let bytes = match &entry {            Entry::Text { text, .. } => text.clone().into_bytes(),            Entry::Media { media: stored, .. } => {                media.read(stored)?.ok_or_else(|| refuse(format!("{stored} was held and is gone: the bundle was not finished")))?            }        };        // not a copy: a bundle's file.        std::fs::write(&path, bytes).map_err(|error| refuse(format!("{} could not be written: {error}", path.display())))?;        files.push(entry.path().to_string());    }    Ok(Written { files, missing_media })}fn refuse(message: impl Into<String>) -> StoreError {    StoreError::refused(message.into())}/// The kit's live rows by table id, as the rule reads them; music's lists/// from the tables the build compiles for them (`cotton_groups`,/// `cotton_group_members`), each member's `group_id` said as `group`.pub fn library_rows(copy: &Driver, kit: Kit) -> Result<BTreeMap<String, Vec<Row>>> {    let mut tables = BTreeMap::new();    for id in kit.tables() {        let table = format!("cotton_{id}");        let spec = spec_on(copy, &table)?.ok_or_else(|| refuse(format!("this copy holds no {id} table")))?;        tables.insert((*id).to_string(), read(copy, &table, spec.columns, "WHERE deleted_at IS NULL")?);    }    if kit == Kit::Music {        let lists = crate::schema::specs::spec_for("cotton_groups").ok_or_else(|| refuse("this build compiles no cotton_groups table"))?;        let members = crate::schema::specs::spec_for("cotton_group_members").ok_or_else(|| refuse("this build compiles no cotton_group_members table"))?;        tables.insert(LISTS.to_string(), read(copy, "cotton_groups", lists.columns, "WHERE deleted_at IS NULL")?);        let mut rows = read(copy, "cotton_group_members", members.columns, "")?;        for row in &mut rows {            if let Some(group) = row.remove("group_id") {                row.insert("group".into(), group);            }        }        tables.insert(LIST_MEMBERS.to_string(), rows);    }    Ok(tables)}fn read(copy: &Driver, table: &str, columns: &[(&str, crate::schema::decl::Codec)], filter: &str) -> Result<Vec<Row>> {    copy.all(&format!("SELECT * FROM \"{table}\" {filter} ORDER BY id"), &[])?        .iter()        .map(|row| decode_row(columns, row.columns()).map(|row| row.into_iter().filter(|(_, value)| !value.is_null()).collect::<serde_json::Map<String, JsonValue>>()))        .collect()}