//! The pictures a record shows — one mechanism, two owners.//!//! `cotton_note_attachments` (schema v32) and `cotton_thought_attachments`//! (schema v36) are the same table with the owner column renamed: an ORDERED//! CHILD of one record naming a photo, a video or a document that already//! exists with its own bytes, plus a caption that overrides the record's own.//! Everything that reads or writes either table goes through here, keyed by an//! [`AttachmentOwner`], so the two can never drift on what an attachment is —//! how a list is diffed onto the file, how a new reference is held honest, and//! what a reader answers for a picture that has since been removed.//!//! The owner is a value rather than a trait because there is nothing to//! implement: a table name, the column the owner id sits in, the word the//! refusals say, and the function that derives a row's id from its natural key.usecrate::mcp::writer::Retract;use cotton_store::protocol::derived_id::{note_attachment_id, thought_attachment_id};use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{ insert_row, int, maybe_row, now_iso, quoted, rows, text, update_row,};usecrate::mcp::handlers::records_1::validate::AttachmentArg;usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::{Filter, Order, Query};/// Which record's pictures — the table, the owner column, the noun the/// refusals use, and the id derivation.#[derive(Debug, Clone, Copy)]pubstructAttachmentOwner {pub table: &'static str,pub owner_column: &'static str,pub noun: &'static str,pub derive: fn(&str, &str, &str) -> String,}/// A note's pictures (schema v32).pubconst NOTE: AttachmentOwner = AttachmentOwner { table: "cotton_note_attachments", owner_column: "note_id", noun: "note", derive: note_attachment_id,};/// A thought's pictures (schema v36).pubconst THOUGHT: AttachmentOwner = AttachmentOwner { table: "cotton_thought_attachments", owner_column: "thought_id", noun: "thought", derive: thought_attachment_id,};/// Make the owner's attachment rows say exactly what `wanted` says, and touch/// nothing else.////// THE LIST IS THE AUTHORITY, and it is DIFFED rather than rewritten. A/// delete-all-then-insert would be correct on one device and wrong on two: an/// attachment's id is derived from `(owner, kind, record)`, so re-inserting a/// row that was already there restamps its clock, and a phone that had the/// same picture in the same place would see a change arrive that changed/// nothing. So a picture already in the list at the same position with the same/// caption is LEFT ALONE, one whose place or caption moved is updated in those/// columns only, one that is new is inserted, and one the list no longer names/// is a replicated row delete.////// Every NEW target is checked FIRST, before a single write is collected: a/// list naming one picture that is not in this database refuses whole, rather/// than half-attaching and leaving the caller to work out which half.////// A pair the owner ALREADY holds is not checked at all, and that is the/// missing rule's other half: a target that is not here (a document deleted,/// a picture not yet arrived) leaves its attachment row standing — only an/// erased picture takes its rows with it — and the list REPLACES — so the phone re-sends the whole list,/// missing rows included, to add one picture or move one. Checking those would/// make a record holding a removed picture uneditable from the only screen that/// edits it, which is the exact opposite of the rule that kept the row. A pair/// the owner does not hold is new, and new references are held honest.pubfn apply_attachments( ctx: &mutCtx<'_>, owner: &AttachmentOwner, owner_id: &str, wanted: &[AttachmentArg],) -> Result<(), ToolFailure> {let held = rows( ctx, &Query::on(owner.table) .columns(&["id", "position", "caption"]) .eq(owner.owner_column, owner_id.to_string()), )?;let holds = |id: &str| held.iter().any(|row| text(row, "id").as_deref() == Some(id));for attachment in wanted {let id = (owner.derive)(owner_id, &attachment.kind, &attachment.id);if !holds(&id) { require_attachment_target(ctx, owner, attachment)?; } }let stamp = now_iso(ctx);letmut keeping: Vec<String> = Vec::with_capacity(wanted.len());for (position, attachment) in wanted.iter().enumerate() {let id = (owner.derive)(owner_id, &attachment.kind, &attachment.id); keeping.push(id.clone());let position = position as i64;let existing = held.iter().find(|row| text(row, "id").as_deref() == Some(&id));match existing {Some(row) => {letmut patch = Map::new();if int(row, "position") != position { patch.insert("position".to_string(), Value::from(position)); }// THE CAPTION KEY LEFT OUT LEAVES THE CAPTION ALONE. The phone// sends `{ kind, id }` — the read collapses the owner's// override with the record's own caption, so the phone has no// way to tell which it is holding and must not be read as// saying "no caption". `caption: null` is the instruction.ifletSome(caption) = attachment.caption.patch_value() {if text(row, "caption") != caption.as_str().map(str::to_string) { patch.insert("caption".to_string(), caption); } }// Nothing moved: the row keeps the clock it already had.if patch.is_empty() {continue; } patch.insert("updated_at".to_string(), Value::from(stamp.clone())); update_row(ctx, owner.table, &id, patch)?; }None => {letmut patch = Map::new(); patch.insert(owner.owner_column.to_string(), Value::from(owner_id)); patch.insert("record_kind".to_string(), Value::from(attachment.kind.clone())); patch.insert("record_id".to_string(), Value::from(attachment.id.clone())); patch.insert("position".to_string(), Value::from(position));// A brand-new attachment has no caption of the owner's own to// leave alone, so `Unchanged` and `Cleared` are the same NULL —// and the picture's own caption is what reads. patch.insert("caption".to_string(), attachment.caption.patch_value().unwrap_or(Value::Null), ); insert_row(ctx, owner.table, &id, patch)?; } } }for row in &held {letSome(id) = text(row, "id") else { continue };if !keeping.contains(&id) { ctx.writer()?.retract(owner.table, &id, Retract::Relation); } }Ok(())}/// The picture a record names has to BE in this database.////// There is no foreign key on `record_id` — it names one of three tables — so/// this is where the reference is held honest. The refusal says the kind and/// the id back, because the two id shapes are easy to swap and the caller is/// usually holding both.fn require_attachment_target( ctx: &Ctx<'_>, owner: &AttachmentOwner, attachment: &AttachmentArg,) -> Result<(), ToolFailure> {let table = match attachment.kind.as_str() {"photo" => "cotton_photos","video" => "cotton_videos", _ => "cotton_documents", };let found = maybe_row( ctx, &Query::on(table) .columns(&["id"]) .eq("id", attachment.id.clone()), )?;if found.is_none() {returnErr(ToolFailure::new(format!("no {} with id {} in this database — a {} names a picture that already exists, it \ does not carry one", attachment.kind, quoted(&attachment.id), owner.noun ))); }Ok(())}/// Whether one picture is attached to one owner — the comments path's question.pubfn is_attached( ctx: &Ctx<'_>, owner: &AttachmentOwner, owner_id: &str, kind: &str, record_id: &str,) -> Result<bool, ToolFailure> {let id = (owner.derive)(owner_id, kind, record_id);Ok(maybe_row( ctx, &Query::on(owner.table).columns(&["id"]).eq("id", id), )? .is_some())}/// [`attachment_refs`] for a page of owners in ONE query, keyed by owner id;/// an owner with no pictures has no entry.pubfn attachment_refs_by_owner( ctx: &Ctx<'_>, owner: &AttachmentOwner, owner_ids: &[String],) -> Result<std::collections::HashMap<String, Vec<Value>>, ToolFailure> {letmut out: std::collections::HashMap<String, Vec<Value>> = std::collections::HashMap::new();if owner_ids.is_empty() {returnOk(out); }let held = rows( ctx, &Query::on(owner.table) .columns(&[owner.owner_column, "record_kind", "record_id", "caption"]) .filter(Filter::In( owner.owner_column.to_string(), owner_ids.iter().cloned().map(SqlValue::Text).collect(), )) .order_by(owner.owner_column, Order::Asc) .order_by("position", Order::Asc) .order_by("created_at", Order::Asc) .order_by("id", Order::Asc), )?;for row in &held {letSome(owner_id) = text(row, owner.owner_column) else {continue; };letmut entry = Map::new(); entry.insert("kind".to_string(), or_value(row, "record_kind")); entry.insert("id".to_string(), or_value(row, "record_id")); entry.insert("caption".to_string(), or_value(row, "caption")); out.entry(owner_id).or_default().push(Value::Object(entry)); }Ok(out)}/// The pictures one record shows, in its own order, each expanded to what a/// reader needs to draw it and an assistant needs to fetch it.////// `key` is what the phone hands `read.mediaPath` — a photo's own object key,/// a video's POSTER key, a document's storage path — and `bytes` names the/// tool that puts the thing itself in front of an assistant. A video has none:/// there is no `get_video_bytes` and a 2 MB tool-result cap would make one/// pointless, so it says so in `bytesNote` instead of answering an empty/// promise.////// A target that is not here LEFT-reads as `missing: true` with its reference/// intact — the record still remembers asking for it. An erased picture's/// rows went with it (the store's `OWNED_BY`), so it is not listed at all.pubfn attachments_of( ctx: &Ctx<'_>, owner: &AttachmentOwner, owner_id: &str,) -> Result<Vec<Value>, ToolFailure> {let held = rows( ctx, &Query::on(owner.table) .columns(&["id", "record_kind", "record_id", "position", "caption"]) .eq(owner.owner_column, owner_id.to_string())// Total whatever the file holds: `position` carries no UNIQUE,// because a reorder arrives as fragments and two rows swapping// places collide for an instant. .order_by("position", Order::Asc) .order_by("created_at", Order::Asc) .order_by("id", Order::Asc), )?;if held.is_empty() {returnOk(Vec::new()); }letmut targets: Vec<(&str, Map<String, Value>)> = Vec::new();for (kind, table, columns) in [ ("photo","cotton_photos", &["id", "caption", "content_type", "width", "height", "key"][..], ), ("video","cotton_videos", &["id", "caption", "content_type", "width", "height", "poster_key"][..], ), ("document","cotton_documents", &["id", "title", "mime", "storage_path"][..], ), ] {let ids: Vec<SqlValue> = held .iter() .filter(|row| text(row, "record_kind").as_deref() == Some(kind)) .filter_map(|row| text(row, "record_id").map(SqlValue::Text)) .collect();if ids.is_empty() {continue; }letmut query = Query::on(table) .columns(columns) .filter(Filter::In("id".to_string(), ids));// A picture or a document in the bin reads as missing: its place// stays, so a list sent back keeps it and a restore brings it back// where it was. query = query.filter(Filter::IsNull("trashed_at".to_string()));letmut found = Map::new();for row in rows(ctx, &query)? {ifletSome(id) = text(&row, "id") { found.insert(id, Value::Object(row)); } } targets.push((kind, found)); }// A document's format is said by the database's `documents` lines, so// the print of an HTML page says "Web page" without a word in Swift.let format_lines = cotton_core::rules::shell_lines::LineSet::of_rows("documents", &crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id), );letmut out: Vec<Value> = Vec::with_capacity(held.len());for (position, row) in held.iter().enumerate() {let kind = text(row, "record_kind").unwrap_or_default();let record_id = text(row, "record_id").unwrap_or_default();let override_caption = text(row, "caption");let target = targets .iter() .find(|(named, _)| *named == kind) .and_then(|(_, found)| found.get(&record_id)) .and_then(Value::as_object);letmut item = Map::new(); item.insert("kind".to_string(), Value::from(kind.clone())); item.insert("id".to_string(), Value::from(record_id.clone()));// The answer's own order, not the stored number: a reader draws the// list it was given, and two rows that transiently share a `position`// must still be two places. item.insert("position".to_string(), Value::from(position as i64));// TWO CAPTIONS, NEVER ONE COLLAPSED. `caption` is the OWNER's own// override and nothing else, so a caller reading a record and sending// the list back can say exactly what the record said; `recordCaption`// is what the picture or the document already calls itself. Collapsing// them made a re-send indistinguishable from a rename, and a phone// holding only the collapsed string could not leave a caption where it// was. item.insert("caption".to_string(), override_caption.map_or(Value::Null, Value::from), );letSome(target) = target else { item.insert("recordCaption".to_string(), Value::Null); item.insert("title".to_string(), Value::Null); item.insert("key".to_string(), Value::Null); item.insert("missing".to_string(), Value::Bool(true)); item.insert("bytes".to_string(), Value::Null); out.push(Value::Object(item));continue; };match kind.as_str() {"document" => {// A document's own words for itself ARE its title. item.insert("recordCaption".to_string(), or_value(target, "title")); item.insert("title".to_string(), or_value(target, "title")); item.insert("mime".to_string(), or_value(target, "mime")); item.insert("key".to_string(), or_value(target, "storage_path")); item.insert("missing".to_string(), Value::Bool(false)); item.insert("bytes".to_string(), bytes_call("get_document_bytes","documentId",Value::from(record_id.clone()), ), ); } media => { item.insert("recordCaption".to_string(), or_value(target, "caption")); item.insert("title".to_string(), Value::Null); item.insert("contentType".to_string(), or_value(target, "content_type")); item.insert("width".to_string(), or_value(target, "width")); item.insert("height".to_string(), or_value(target, "height")); item.insert("missing".to_string(), Value::Bool(false));if media == "video" { item.insert("key".to_string(), or_value(target, "poster_key")); item.insert("bytes".to_string(), Value::Null); item.insert("bytesNote".to_string(),Value::from("video bytes exceed the 2 MB tool limit; get_video describes it", ), ); } else { item.insert("key".to_string(), or_value(target, "key")); item.insert("bytes".to_string(), bytes_call("get_photo_bytes", "id", Value::from(record_id.clone())), ); } } }// What the file is, said by the `documents` lines from its type.let mime = item.get("mime").or_else(|| item.get("contentType")).and_then(Value::as_str);let format = cotton_core::rules::file_format::FileFormat::of(mime, None) .map_or(cotton_core::rules::file_format::FileFormat::UNKNOWN_LINE, |format| format.line()); item.insert("format".to_string(), format_lines.as_ref().and_then(|lines| lines.say(format, &[])).map_or(Value::Null, Value::from), ); out.push(Value::Object(item)); }Ok(out)}/// One column of a target row, or `null` where it has none.fn or_value(row: &Map<String, Value>, column: &str) -> Value { row.get(column).cloned().unwrap_or(Value::Null)}/// `{ tool, args }` — the call that puts this thing in front of an assistant.fn bytes_call(tool: &str, key: &str, id: Value) -> Value {letmut args = Map::new(); args.insert(key.to_string(), id);letmut call = Map::new(); call.insert("tool".to_string(), Value::from(tool)); call.insert("args".to_string(), Value::Object(args));Value::Object(call)}