//! THE COTTON PACKAGE — one exchange format for anything a database holds.
//!
//! A `.cottonpkg` is a zip:
//!
//! - `manifest.json` — `{format, schemaVersion, sourceDatabase, exportedAt,
//! tables: [{table, rows}], media: [{key, hash, table, id}]}`;
//! - `
.jsonl` — one record per line, in the core's own column names and
//! with the record's own id, each value in its domain form (what an op's
//! patch carries, [`crate::schema::codecs::decode_row`]);
//! - `media/` — the bytes a record names, once per content.
//!
//! **An import is a write like any other.** Every record goes through
//! [`crate::mint::mint`] as the caller's actor, so the receipts, the link
//! rule, the owning parents and the search rows are exactly what a tap would
//! have made; nothing is written into a replicated table by hand.
//!
//! **Records keep their ids, and importing twice changes nothing.** A record
//! the file does not hold is created at its id; one it holds is changed in the
//! columns that differ, and one that differs in nothing is left alone — no
//! receipt, no history. Its `created_at` never moves, and `updated_at` only
//! with a real change, so a file read again at a later hour is still nothing new.
//!
//! **The source database's own id becomes this one's.** A record carries the
//! id of the database it was written in — `workspace_id`, and the `{file}/`
//! prefix every media key starts with ([`crate::link_rule`] refuses a key under
//! another database's prefix). On import, a value that IS the source's id, or
//! starts with `{source}/`, is rewritten to this database's; the bytes land at
//! the rewritten key ([`MediaSink`]). A reader that makes a package from
//! another format (a vCard, a calendar) names any source it likes and writes
//! that name where a record names its database.
//!
//! **The store holds no bytes.** Media is read through a [`MediaSource`] on
//! export and written through a [`MediaSink`] on import; the shell that holds
//! the bytes implements both. A key whose bytes the source does not have is
//! reported ([`Exported::missing_media`]), never silently dropped.
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Cursor, Read, Write};
use rusqlite::types::Value as SqlValue;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value as JsonValue};
use sha2::{Digest, Sha256};
use crate::actor::Actor;
use crate::driver::Driver;
use crate::error::{Result, StoreError};
use crate::file_identity::read_file_identity;
use crate::mint::{mint, Act, Change, Clock, Held, History, IdSource, Kind};
use crate::protocol::types::CottonOp;
use crate::schema::codecs::{decode_row, encode_value};
use crate::schema::decl::TableSpec;
use crate::schema::ddl::SCHEMA_VERSION;
use crate::schema::package_shape::spec_on;
use crate::schema::table_specs::{is_handed_over, OWNING_REFS};
/// The format this build writes and reads.
pub const FORMAT: u32 = 1;
/// The file extension a package is saved under.
pub const EXTENSION: &str = "cottonpkg";
const MANIFEST: &str = "manifest.json";
const MEDIA_DIR: &str = "media/";
/// The columns that stamp a record rather than say what it holds: an import
/// never changes them on a record the file holds, unless (`updated_at`) it
/// changes something else.
const STAMPS: [&str; 2] = ["created_at", "updated_at"];
/// How many records one act of an import mints.
const BATCH: usize = 200;
/// The tables a package never carries, each with why. A system table
/// (`_`-prefixed) and a table one device or the serving Mac keeps to itself
/// ([`is_handed_over`]) are refused beside these.
pub const NOT_PACKAGED: &[(&str, &str)] = &[
("cotton_workspaces", "a database's own row is what the database is, and it is never moved into another"),
("cotton_databases", "the list of databases is the server's registry, not a record"),
("cotton_database_departures", "a departure is a fact of who left this database"),
("cotton_devices", "a device belongs to the database it was admitted to"),
("cotton_device_keep", "what a device keeps is that device's own setting"),
("cotton_device_relay_keys", "a relay key is a device's credential"),
("cotton_device_statements", "a device statement is a signed fact of this database"),
("cotton_mcp_tokens", "a token is a credential for this database"),
("cotton_oauth_clients", "an OAuth client is a credential for this database"),
("cotton_oauth_grants", "an OAuth grant is a credential for this database"),
("cotton_grant_rotations", "a grant rotation is a fact of this database's credentials"),
("cotton_code_credentials", "a code credential is a credential for this database"),
("cotton_google_accounts", "a connected account is a credential for this database"),
("cotton_agent_accounts", "an agent account is a credential for this database"),
("cotton_secrets", "a secret is sealed under this database's vault key and opens nowhere else"),
("cotton_secret_placements", "a secret's placement names a secret of this database's vault"),
("cotton_placement_proposals", "a placement proposal names a secret of this database's vault"),
("cotton_vault_keys", "a vault key is this database's own"),
("cotton_vault_state", "the vault's state is this database's own"),
("cotton_vault_retired_keys", "a retired vault key is this database's own"),
("cotton_authors", "an author is a device's stream in this database"),
("cotton_revocations", "a revocation is a fact of this database's devices and credentials"),
("cotton_serving_machine", "which Mac serves a database is that database's own fact"),
("cotton_person_keys", "a person's key is a membership credential"),
("cotton_admissions", "an admission is a fact of who may open this database"),
("cotton_member_person_claims", "a member's claim is a signed fact of this database"),
("cotton_invites", "an invite admits people to this database"),
("cotton_joined_places", "a joined place is a membership of this database"),
("cotton_audiences", "an audience is this database's own sharing rule"),
("cotton_undos", "an undo names receipts of this database"),
("cotton_changes", "a change is this database's history of its own receipts"),
("cotton_media_erasures", "an erasure is a fact of bytes this database let go"),
("cotton_media_holdings", "a holding says which device holds which bytes"),
("cotton_media_backups", "a backup record says where this database's bytes were copied"),
("cotton_media_sightings", "a sighting is a device's own reading of its library"),
("cotton_repo_clones", "a clone is one Mac's copy of a repository"),
("cotton_machine_runners", "a runner is a process on one machine"),
];
/// What a package says about itself.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Manifest {
pub format: u32,
/// The schema the records were read at. A package from a newer build is
/// refused: it may name columns this one does not hold.
pub schema_version: u32,
/// The id of the database the records were written in (or the name a
/// reader gave its source) — what an import rewrites to its own.
pub source_database: String,
pub exported_at: String,
pub tables: Vec,
#[serde(default)]
pub media: Vec,
}
/// One table's file in the package.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PackagedTable {
pub table: String,
pub rows: u64,
}
/// One media object a record names: the key as the source wrote it, the
/// sha256 of its bytes (`media/`), and the record that names it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PackagedMedia {
pub key: String,
pub hash: String,
pub table: String,
pub id: String,
}
/// A package in memory: what [`Package::to_bytes`] writes and
/// [`Package::from_bytes`] reads, and what a reader of another format makes.
#[derive(Debug, Clone, PartialEq)]
pub struct Package {
pub manifest: Manifest,
/// Each table's records, in the manifest's order.
pub records: Vec<(String, Vec