use std::io;
use std::path::Path;
use serde::{Deserialize, Serialize};
use super::super::fingerprint::digest;
use crate::remote::selection::Selection;
use crate::store::fileio::atomic_write;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
pub enum Destination {
File {
root: String,
},
Postgres {
schema: String,
dsn_sha256: String,
},
Remote {
url: String,
credential_sha256: String,
},
Profile {
name: String,
project: String,
source: Option<String>,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct State {
pub draft: String,
pub next_seq: u64,
#[serde(deserialize_with = "Option::deserialize")]
pub fingerprint: Option<String>,
#[serde(deserialize_with = "Option::deserialize")]
pub destination: Option<Destination>,
pub attempt: u8,
pub closed_at: String,
pub bytes: u64,
pub agent: String,
pub actor: String,
pub session: String,
pub conversation_id: String,
#[serde(deserialize_with = "Option::deserialize")]
pub scope: Option<String>,
#[serde(deserialize_with = "Option::deserialize")]
pub mount: Option<String>,
#[serde(deserialize_with = "Option::deserialize")]
pub provenance: Option<String>,
#[serde(deserialize_with = "Option::deserialize")]
pub parent: Option<String>,
#[serde(deserialize_with = "Option::deserialize")]
pub project: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub sealing: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Reason {
pub reason: &'static str,
#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub answered: Option<Answered>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub may_be_stored: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Answered {
pub status: Option<u16>,
pub code: Option<String>,
}
pub const POLICY_CHANGED: &str = "policy_changed";
pub const UNREADABLE: &str = "unreadable";
pub const REFUSED: &str = "refused";
pub const MISMATCH: &str = "mismatch";
pub const ACTOR_CHANGED: &str = "actor_changed";
impl Reason {
pub fn of(reason: &'static str) -> Self {
Self {
reason,
answered: None,
may_be_stored: false,
message: None,
}
}
pub fn unreadable(message: String) -> Self {
Self {
message: Some(message),
..Self::of(UNREADABLE)
}
}
pub fn may_be_stored(message: String) -> Self {
Self {
may_be_stored: true,
..Self::unreadable(message)
}
}
pub fn refused(status: Option<u16>, code: Option<String>, message: String) -> Self {
Self::answered(REFUSED, status, code, message)
}
pub fn answered(
reason: &'static str,
status: Option<u16>,
code: Option<String>,
message: String,
) -> Self {
Self {
answered: Some(Answered { status, code }),
message: Some(message),
..Self::of(reason)
}
}
pub fn text(&self) -> String {
let mut kept = self.clone();
kept.message = kept.message.map(|message| super::kept::cut(&message));
let mut text = serde_json::to_string(&kept).expect("a reason serializes");
text.push('\n');
text
}
}
impl State {
pub fn text(&self) -> String {
let mut text = serde_json::to_string(self).expect("a state serializes");
text.push('\n');
text
}
pub fn write(&self, file: &Path) -> io::Result<()> {
atomic_write(file, &self.text(), false)
}
pub fn write_synced(&self, file: &Path) -> io::Result<()> {
atomic_write(file, &self.text(), true)?;
super::files::sync_directory(file.parent().unwrap_or(Path::new(".")))
}
pub fn read(file: &Path) -> io::Result<Self> {
let text = std::fs::read_to_string(file)?;
serde_json::from_str(&text).map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("state {} is unreadable: {error}", file.display()),
)
})
}
}
pub fn public_url(url: &str) -> String {
let (scheme, rest) = url.split_once("://").unwrap_or(("", url));
let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let (authority, tail) = rest.split_at(end);
let host = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host);
let path = &tail[..tail.find(['?', '#']).unwrap_or(tail.len())];
let shown = match scheme {
"" => format!("{host}{path}"),
_ => format!("{scheme}://{host}{path}"),
};
shown.trim_end_matches('/').to_string()
}
pub fn credential_digest(url: &str, token: &str) -> String {
let both = (url.trim_end_matches('/'), token);
digest(&serde_json::to_vec(&both).expect("strings serialize"))
}
fn shown(path: &Path) -> String {
let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
let mut existing = absolute.as_path();
let mut rest = Vec::new();
let resolved = loop {
if let Ok(real) = std::fs::canonicalize(existing) {
break rest.iter().rev().fold(real, |full, name| full.join(name));
}
match (existing.parent(), existing.file_name()) {
(Some(parent), Some(name)) => {
rest.push(name);
existing = parent;
}
_ => break absolute.clone(),
}
};
resolved.to_string_lossy().into_owned()
}
pub fn describe(selection: &Selection) -> Destination {
match selection {
Selection::File(root) => Destination::File { root: shown(root) },
Selection::Postgres { dsn, schema } => Destination::Postgres {
schema: schema.clone(),
dsn_sha256: digest(dsn.as_bytes()),
},
Selection::Remote { url, token } => Destination::Remote {
url: public_url(url),
credential_sha256: credential_digest(url, token),
},
Selection::Profile(resolved) => Destination::Profile {
name: resolved.name.clone(),
project: shown(&resolved.project),
source: resolved.profile.history.as_ref().map(|h| h.source.clone()),
},
}
}