Cotton code
322 lines · 14.9 KB · RustRaw
//! `feedback.send` — a shaken report to Cotton's own database (owner, 13 Nov//! 2026). Every Cotton app's "Report a problem" screen, on the iPhone and on//! Android, hands the core one sentence and the screenshot it took; the core//! adds what it knows (the app, the build, the platform, the tail of its own//! log) and posts it to the open host's `POST /v1/feedback`//! (`apps/business/src/feedback.ts`), which writes one `app_report` row in//! the `cotton-product` object — never in anyone's Personal.//!//! ```text//! feedback.send  { sentence, screenshotPath?, route?, device?, os?, log?: [text], server? }//!     → { id, state: "sent", sender: "signed_in"|"anonymous", pushed }//!     → { id, state: "kept", code, message }      nothing answered, or "later" (429, 5xx): sent by a later flush//!     ✗ the Worker's refusal (bad_sentence, screenshot_too_large, …): the report is dropped, and said//! feedback.flush {} → { sent, kept, refused }     every kept report tried again, oldest first//! ```//!//! **Never lost silently.** The report is written to this phone's outbox//! (`<data dir>/feedback-outbox/<id>.json`, the whole request with the//! picture's bytes) BEFORE anything is sent, and leaves it only when the Worker//! took it or refused it in words the answer carries. A kept report is tried//! again on the next `feedback.send` and on every `feedback.flush` (the shell//! calls it at launch and when the app comes to the front).//!//! **Who sent it is the sign-in, never the body.** Signed in at the open host//! (the personal object's door), the post carries the device credential and//! the Worker asks the sender's object for the number and name; signed out, or//! signed in at a business object's own address, it goes with no bearer to the//! open host the shell names (`server`, the address `personal.code` takes) and//! is anonymous. A report made signed out stays anonymous when it is sent after//! a sign-in. A credential the Worker no longer takes (401) is sent again at//! once with none: the report arrives, without a number.//!//! The id is made here, so a retry is the same report: the Worker answers a//! second post of an id it holds as the first, and writes nothing twice.use std::path::{Path, PathBuf};use std::sync::Arc;use base64::{engine::general_purpose::STANDARD, Engine};use serde_json::{json, Map, Value};use cotton_client::transport::object::{bearer, ObjectAddress, ObjectRefusal};use cotton_client::transport::{Exchange, SocketExchange};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;use crate::shell::log_ring::LogLevel;pub const METHODS: [&str; 2] = ["feedback.flush", "feedback.send"];pub const PATH: &str = "/v1/feedback";/// The outbox folder under the data directory.pub const OUTBOX: &str = "feedback-outbox";/// The platform this build is, decided when the crate is compiled.pub const PLATFORM: &str = if cfg!(target_os = "android") {    "android"} else if cfg!(target_os = "macos") {    "macos"} else {    "ios"};/// The Worker's caps (src/feedback.ts `CAPS`), held here too so a report that/// could never arrive is refused before it is kept.pub const SENTENCE_MAX: usize = 2000;pub const SCREENSHOT_MAX: u64 = 4 * 1024 * 1024;pub const LOG_MAX_BYTES: usize = 256 * 1024;/// How many of the core's own log lines, and of the shell's, a report carries.const LOG_LINES: usize = 200;/// What the core knows about this app, gathered at send.#[derive(Debug, Clone)]pub struct Facts {    /// The app's slug: its manifest's `flavour` (`notes`, `books`), `cotton` for Cotton.    pub app: String,    /// The build, as the shell opened the core with it.    pub build: String,    /// The newest lines of the core's own log, oldest first.    pub core_log: Vec<String>,}pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    let facts = Facts {        app: handle.app_slug().to_string(),        build: handle.app_version().to_string(),        core_log: handle.log().lines().into_iter().map(|line| format!("{} {} {}: {}", line.at, level_word(line.level), line.source, line.text)).collect(),    };    over(&handle.client(), &handle.data_dir().join(OUTBOX), &facts, Arc::new(SocketExchange), method, request)}/// The level as the log file says it.fn level_word(level: LogLevel) -> &'static str {    match level {        LogLevel::Info => "info",        LogLevel::Warn => "warn",        LogLevel::Error => "error",    }}/// The same over a named controller, outbox and exchange (the suite's)./// `exchange` carries a signed-out post; a signed-in one goes through the door's own.pub fn over(client: &ClientController, outbox: &Path, facts: &Facts, exchange: Arc<dyn Exchange>, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "feedback.send" => send(client, outbox, facts, exchange.as_ref(), request),        "feedback.flush" => {            let tally = flush(client, outbox, exchange.as_ref(), None)?;            Ok(json!({ "sent": tally.sent, "kept": tally.kept, "refused": tally.refused }))        }        other => Err(MethodError::new("unknown_method", format!("no method {other}"))),    }}fn send(client: &ClientController, outbox: &Path, facts: &Facts, exchange: &dyn Exchange, request: &Value) -> Result<Value, MethodError> {    let id = new_id();    let body = report(&id, facts, request)?;    let door = open_door(client);    let server = text(request, "server")        .map(str::to_string)        .or_else(|| door.as_ref().map(|door| door.address.origin().text.clone()));    let entry = json!({ "body": body, "signedIn": door.is_some(), "server": server });    keep(outbox, &id, &entry)?;    let tally = flush(client, outbox, exchange, Some(&id))?;    match tally.this {        Some(Outcome::Sent(answer)) => Ok(json!({ "id": id, "state": "sent", "sender": answer["sender"], "pushed": answer["pushed"].as_bool().unwrap_or(false) })),        Some(Outcome::Kept(why)) => Ok(json!({ "id": id, "state": "kept", "code": why.code, "message": why.message })),        Some(Outcome::Refused(why)) => Err(MethodError::new(&why.code, why.message)),        None => Ok(json!({ "id": id, "state": "kept", "code": "kept", "message": "the report is kept on this phone and sent later" })),    }}/// The request the Worker reads, refused here when it never could arrive.fn report(id: &str, facts: &Facts, request: &Value) -> Result<Value, MethodError> {    for inline in ["bytes", "image", "png", "data", "screenshot"] {        if request.get(inline).is_some() {            return Err(MethodError::new("bad_request", format!("`{inline}` is not accepted: write the screenshot to a file and send its path")));        }    }    let sentence = text(request, "sentence").ok_or_else(|| MethodError::new("bad_request", "a report needs a sentence: `sentence` is empty"))?;    if sentence.chars().count() > SENTENCE_MAX {        return Err(MethodError::new("bad_request", format!("`sentence` is over {SENTENCE_MAX} characters")));    }    let mut body = Map::new();    body.insert("id".into(), json!(id));    body.insert("sentence".into(), json!(sentence));    body.insert("app".into(), json!(facts.app));    body.insert("platform".into(), json!(PLATFORM));    if !facts.build.trim().is_empty() {        body.insert("build".into(), json!(facts.build.trim()));    }    for key in ["route", "device", "os"] {        if let Some(value) = text(request, key) {            body.insert(key.into(), json!(value));        }    }    if let Some(path) = text(request, "screenshotPath") {        body.insert("screenshot".into(), screenshot(Path::new(path))?);    }    let log = log_of(&facts.core_log, request.get("log"));    if !log.is_empty() {        body.insert("log".into(), json!(log));    }    Ok(Value::Object(body))}fn screenshot(path: &Path) -> Result<Value, MethodError> {    let ext = path.extension().and_then(|ext| ext.to_str()).map(str::to_ascii_lowercase);    let kind = match ext.as_deref() {        Some("png") => "image/png",        Some("jpg" | "jpeg") => "image/jpeg",        _ => return Err(MethodError::new("bad_request", "`screenshotPath` must name a .png or .jpg")),    };    let size = std::fs::metadata(path).map_err(|_| MethodError::new("unreadable", "`screenshotPath` names a file that is not there"))?.len();    if size > SCREENSHOT_MAX {        return Err(MethodError::new("too_large", format!("the screenshot is {size} bytes, over the {SCREENSHOT_MAX}-byte ceiling")));    }    let bytes = std::fs::read(path).map_err(|error| MethodError::new("unreadable", format!("the screenshot could not be read: {error}")))?;    Ok(json!({ "type": kind, "base64": STANDARD.encode(bytes) }))}/// The core's own tail, then the shell's, each at most [`LOG_LINES`], cut from/// the oldest end until the whole is under the Worker's cap.fn log_of(core: &[String], shell: Option<&Value>) -> Vec<String> {    let tail = |lines: Vec<String>| -> Vec<String> { lines[lines.len().saturating_sub(LOG_LINES)..].to_vec() };    let shell: Vec<String> = shell.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(|line| line.chars().take(500).collect()).collect();    let mut lines = tail(core.iter().map(|line| line.chars().take(500).collect()).collect());    lines.extend(tail(shell));    while !lines.is_empty() && lines.iter().map(|line| line.len() + 1).sum::<usize>() > LOG_MAX_BYTES {        lines.remove(0);    }    lines}/// A version-4 UUID, made here so a retry posts the same report.fn new_id() -> String {    let mut bytes: [u8; 16] = rand::random();    bytes[6] = (bytes[6] & 0x0f) | 0x40;    bytes[8] = (bytes[8] & 0x3f) | 0x80;    let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();    format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])}fn text<'a>(request: &'a Value, key: &str) -> Option<&'a str> {    request.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty())}/// The personal object's door at the open host, when this phone is signed in/// there; a business object's own address is no door for a report.fn open_door(client: &ClientController) -> Option<Arc<crate::phone::personal_object::ObjectDoor>> {    client.object_door().filter(|door| door.address.slug().is_empty())}fn keep(outbox: &Path, id: &str, entry: &Value) -> Result<(), MethodError> {    std::fs::create_dir_all(outbox).map_err(|error| MethodError::new("unwritable", format!("the report could not be kept on this phone: {error}")))?;    let path = outbox.join(format!("{id}.json"));    let partial = outbox.join(format!("{id}.json.partial"));    // not a copy: feedback attachments.    std::fs::write(&partial, entry.to_string()).and_then(|()| std::fs::rename(&partial, &path)).map_err(|error| MethodError::new("unwritable", format!("the report could not be kept on this phone: {error}")))}enum Outcome {    Sent(Value),    Kept(ObjectRefusal),    Refused(ObjectRefusal),}#[derive(Default)]struct Tally {    sent: usize,    kept: usize,    refused: usize,    /// What became of the report `send` just kept.    this: Option<Outcome>,}/// Every kept report, oldest first, posted; each leaves the outbox only when/// it was taken or refused in words.fn flush(client: &ClientController, outbox: &Path, exchange: &dyn Exchange, this: Option<&str>) -> Result<Tally, MethodError> {    let mut tally = Tally::default();    let Ok(dir) = std::fs::read_dir(outbox) else { return Ok(tally) };    let mut kept: Vec<(std::time::SystemTime, PathBuf)> = dir        .filter_map(Result::ok)        .map(|entry| entry.path())        .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("json"))        .map(|path| (std::fs::metadata(&path).and_then(|meta| meta.modified()).unwrap_or(std::time::UNIX_EPOCH), path))        .collect();    kept.sort();    let door = open_door(client);    for (_, path) in kept {        let id = path.file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_string();        let Some(entry) = std::fs::read(&path).ok().and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok()) else {            // A file that does not read is no report anyone can send: it goes, and is counted.            // not a copy: feedback attachments.            let _ = std::fs::remove_file(&path);            tally.refused += 1;            continue;        };        let outcome = post(door.as_deref(), exchange, &entry);        match &outcome {            Outcome::Sent(_) => {                // not a copy: feedback attachments.                let _ = std::fs::remove_file(&path);                tally.sent += 1;            }            Outcome::Refused(_) => {                // not a copy: feedback attachments.                let _ = std::fs::remove_file(&path);                tally.refused += 1;            }            Outcome::Kept(_) => tally.kept += 1,        }        if this == Some(id.as_str()) {            tally.this = Some(outcome);        }    }    Ok(tally)}fn post(door: Option<&crate::phone::personal_object::ObjectDoor>, exchange: &dyn Exchange, entry: &Value) -> Outcome {    let body = &entry["body"];    if entry["signedIn"] == json!(true) {        if let Some(door) = door {            match door.address.send(door.exchange.as_ref(), "POST", PATH, bearer(&door.credential), Some(body)) {                Ok(answer) => return Outcome::Sent(answer),                // The credential is no good any more: the report goes on without it, at once.                Err(refusal) if refusal.status == 401 => return anonymous(door.address.origin().text.as_str(), door.exchange.as_ref(), body),                Err(refusal) => return judged(refusal),            }        }    }    let Some(server) = entry["server"].as_str() else {        return Outcome::Kept(ObjectRefusal { status: 0, code: "no_server".into(), message: "kept until the app names where to send it".into() });    };    match door {        // Signed in at the same host since: the door's own exchange reaches it.        Some(door) if door.address.origin().text == server => anonymous(server, door.exchange.as_ref(), body),        _ => anonymous(server, exchange, body),    }}fn anonymous(server: &str, exchange: &dyn Exchange, body: &Value) -> Outcome {    let address = match ObjectAddress::open(server) {        Ok(address) => address,        Err(reason) => return Outcome::Kept(ObjectRefusal { status: 0, code: "bad_server".into(), message: reason }),    };    match address.send(exchange, "POST", PATH, Vec::new(), Some(body)) {        Ok(answer) => Outcome::Sent(answer),        Err(refusal) => judged(refusal),    }}/// Nothing answered, too many, or the Worker not ready: kept for later. Any other refusal is final.fn judged(refusal: ObjectRefusal) -> Outcome {    if refusal.status == 0 || refusal.status == 429 || refusal.status >= 500 {        Outcome::Kept(refusal)    } else {        Outcome::Refused(refusal)    }}#[cfg(test)]#[path = "feedback_send_tests.rs"]mod tests;