//! The personal object, over HTTPS: the contract the Mac speaks.//!//! Every call carries `Authorization: Bearer <device token>`, except the two//! sign-in steps that mint it. The object answers a refusal as//! `{ code, message }` with its status; a 401 means the token is revoked or//! expired, and the app signs out rather than dialling again with it.use std::time::Duration;use cotton_client::media::sealed::{PersonFiles, SEALED_FILE_TYPE, SEALED_KINDS};use reqwest::blocking::{Client, RequestBuilder, Response};use reqwest::StatusCode;use serde::{Deserialize, Serialize};use serde_json::{json, Value};/// What one part of a file sent in parts weighs, and the most a file sent in/// one PUT may: under the host's request limit (100 MB, `MEDIA_MAX_BYTES` in/// apps/business/src/media.ts, refused at the edge before the Worker sees/// it) and over R2's 5 MB floor for every part but the last.pubconst PART_BYTES: u64 = 64 * 1024 * 1024;/// The most keys one `POST /v1/media/missing` asks about (apps/business/src/business.ts).pubconst MISSING_KEYS: usize = 500;/// How many message changes one landing plans (the engine's batch, as the/// Worker's `CHANGES_PER_CALL` was).pubconst CHANGES_PER_CALL: usize = 1000;/// The most rows one `import_rows` act lands (`IMPORT_ROWS` in/// apps/business/src/business.ts).pubconst IMPORT_ROWS: usize = 500;#[derive(Debug, thiserror::Error, PartialEq)]pubenumObjectError {/// The token is revoked or expired: sign in again. #[error("Cotton signed this Mac out: sign in again")]SignedOut, #[error("the object refused ({status} {code}): {message}")]Refused { status: u16, code: String, message: String }, #[error("the object could not be reached: {0}")]Transport(String), #[error("the object's answer did not parse: {0}")]Decode(String),/// This Mac could not read the file it was sending: no try at the object mends that. #[error("{0}")]File(String),}implObjectError {pubfn code(&self) -> Option<&str> {matchself {ObjectError::Refused { code, .. } => Some(code), _ => None, } }/// Whether this says the object is away for now rather than anything of/// the request: a 5xx, a timeout, too many requests, an unreachable server/// or an answer cut short. The same request may well succeed later.pubfn is_passing(&self) -> bool {matchself {ObjectError::Refused { status, .. } => *status >= 500 || *status == 408 || *status == 429,ObjectError::Transport(_) | ObjectError::Decode(_) => true,ObjectError::SignedOut | ObjectError::File(_) => false, } }}pubtypeResult<T> = std::result::Result<T, ObjectError>;/// What `POST /v1/code` answers at the open host: the challenge the code/// proves, and the database the directory found for the number, which the/// sign-in names.#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]pubstructCodeAsked {pub challenge_id: String,pub database_id: String,}/// What `POST /v1/sign-in` answers. The credential is the owner's device/// token; the app keeps it in its keychain and nowhere else.#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]pubstructSignedIn {pub credential: String,pub person: Value,pub database_id: String, #[serde(default)]pub expires_in: Option<i64>,}/// An `act` the plain-row writer sends.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumAct {Create,Update,Delete,}implAct {pubconstfn as_str(self) -> &'static str {matchself {Act::Create => "create",Act::Update => "update",Act::Delete => "delete", } }}/// What a pass says this device is: the shape of a phone's first sync page,/// from which the object files the credential's device row.#[derive(Debug, Clone, PartialEq)]pubstructDeviceFacts {pub name: String,pub platform: String,pub app_version: String,}implDeviceFacts {fn query(&self) -> String { url::form_urlencoded::Serializer::new(String::new()) .append_pair("device_name", &self.name) .append_pair("platform", &self.platform) .append_pair("app_version", &self.app_version) .finish() }}#[derive(Debug, Clone)]pubstructObjectClient { base: String, token: Option<String>, http: Client,/// Plain writes to a table the object seals go sealed through the/// importer's copy (`crate::copy::SealDoor`), when a pass gave one. sealed: Option<std::sync::Arc<crate::copy::SealDoor>>,/// The person's files and the data key that seals them (e2e rulings R6):/// a photo, video, book, song or film leaves this Mac as an f1 file. files: Option<std::sync::Arc<PersonFiles>>,}implObjectClient {/// `base` is the open host, `https://cottondb.com`: the sign-in finds the/// person's database, and every later call's credential names it.pubfn new(base: implInto<String>, token: Option<String>) -> Result<ObjectClient> {let http = Client::builder() .user_agent(concat!("Cotton-Mac/", env!("CARGO_PKG_VERSION"))) .connect_timeout(Duration::from_secs(20)) .timeout(Duration::from_secs(300)) .build() .map_err(|e| ObjectError::Transport(e.to_string()))?;Ok(ObjectClient { base: base.into().trim_end_matches('/').to_string(), token, http, sealed: None, files: None, }) }pubfn base(&self) -> &str { &self.base }pubfn host(&self) -> &str {self.base .split_once("://") .map(|(_, rest)| rest) .unwrap_or(&self.base) }pubfn signed_in(&self) -> bool {self.token.is_some() }pubfn with_token(&self, token: Option<String>) -> ObjectClient {ObjectClient { base: self.base.clone(), token, http: self.http.clone(), sealed: self.sealed.clone(), files: self.files.clone(), } }/// This client, its plain writes to sealed tables sealed through `door`.pubfn sealing_with(&self, door: std::sync::Arc<crate::copy::SealDoor>) -> ObjectClient {ObjectClient { sealed: Some(door), ..self.clone() } }/// This client, the person's files sealed with the key `files` holds.pubfn sealing_files(&self, files: std::sync::Arc<PersonFiles>) -> ObjectClient {ObjectClient { files: Some(files), ..self.clone() } }/// The person's files this client seals and opens, when a pass gave them.pubfn person_files(&self) -> Option<&std::sync::Arc<PersonFiles>> {self.files.as_ref() }fn url(&self, path: &str) -> String { format!("{}{}", self.base, path) }/// Name this device to the object, as a phone's first sync page does, so/// it files the credential's device row: `GET /v1/me` with `facts` in the/// query, the cheapest signed-in call the object files a caller on. A pass/// makes it once, whether or not its sources have anything to send.pubfn name_device(&self, facts: &DeviceFacts) -> Result<()> {self.send(self.http.get(format!("{}?{}", self.url("/v1/me"), facts.query())))?;Ok(()) }fn authed(&self, builder: RequestBuilder) -> RequestBuilder {match &self.token {Some(token) => builder.bearer_auth(token),None => builder, } }fn send(&self, builder: RequestBuilder) -> Result<Response> {let response = self .authed(builder) .send() .map_err(|e| ObjectError::Transport(e.to_string()))?;let status = response.status();if status.is_success() {returnOk(response); }if status == StatusCode::UNAUTHORIZED {returnErr(ObjectError::SignedOut); }// A refusal the object never saw (the host's own, as HTML) carries// no `{ code, message }`: it says its status's reason instead.let body: Value = response.json().unwrap_or(Value::Null);Err(ObjectError::Refused { status: status.as_u16(), code: body .get("code") .and_then(Value::as_str) .unwrap_or("refused") .to_string(), message: body .get("message") .and_then(Value::as_str) .or(status.canonical_reason()) .unwrap_or("") .to_string(), }) }fn post_json<T: Serialize + ?Sized>(&self, path: &str, body: &T) -> Result<Value> {let response = self.send(self.http.post(self.url(path)).json(body))?; response.json().map_err(|e| ObjectError::Decode(e.to_string())) }// ── sign-in ──────────────────────────────────────────────────────────/// Step one: the owner's number. The code is never said by the object.pubfn ask_code(&self, phone: &str, device_id: &str) -> Result<CodeAsked> {let answer = self.post_json("/v1/code", &json!({ "phone": phone, "device_id": device_id }))?; serde_json::from_value(answer).map_err(|e| ObjectError::Decode(e.to_string())) }/// Step two: the code, at the database step one found, for the device token.pubfn sign_in(&self, database_id: &str, challenge_id: &str, code: &str, device_id: &str) -> Result<SignedIn> {let answer = self.post_json("/v1/sign-in", &json!({ "database_id": database_id, "challenge_id": challenge_id, "code": code, "device_id": device_id }), )?; serde_json::from_value(answer).map_err(|e| ObjectError::Decode(e.to_string())) }/// The database's id, which every media key starts with.pubfn database_id(&self) -> Result<String> {let response = self.send(self.http.get(self.url("/v1/definitions")))?;let body: Value = response.json().map_err(|e| ObjectError::Decode(e.to_string()))?; body.pointer("/business/database_id") .and_then(Value::as_str) .filter(|id| !id.is_empty()) .map(str::to_string) .ok_or_else(|| ObjectError::Decode("the definitions name no database_id".to_string())) }// ── media ────────────────────────────────────────────────────────────fn media_path(key: &str) -> String {let encoded: Vec<String> = key.split('/').map(encode_segment).collect(); format!("/v1/media/{}", encoded.join("/")) }/// Whether the object holds bytes under `key` already.pubfn media_held(&self, key: &str) -> Result<bool> {matchself.send(self.http.head(self.url(&Self::media_path(key)))) {Ok(_) => Ok(true),Err(ObjectError::Refused { status: 404, .. }) => Ok(false),Err(error) => Err(error), } }/// The file under `key` deleted from the person's storage; one already gone is no refusal.pubfn delete_media(&self, key: &str) -> Result<()> {matchself.send(self.http.delete(self.url(&Self::media_path(key)))) {Ok(_) | Err(ObjectError::Refused { status: 404, .. }) => Ok(()),Err(error) => Err(error), } }pubfn put_media(&self, key: &str, bytes: Vec<u8>, content_type: &str) -> Result<()> {self.send(self.http .put(self.url(&Self::media_path(key))) .header(reqwest::header::CONTENT_TYPE, content_type) .body(bytes), )?;Ok(()) }/// The type the object stores `key` as, or `None` when it holds nothing/// there: a sealed file says [`SEALED_FILE_TYPE`].pubfn media_type(&self, key: &str) -> Result<Option<String>> {matchself.send(self.http.head(self.url(&Self::media_path(key)))) {Ok(response) => Ok(Some( response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_string(), )),Err(ObjectError::Refused { status: 404, .. }) => Ok(None),Err(error) => Err(error), } }/// Of `keys`, the ones the object already stores sealed, asked/// [`MISSING_KEYS`] at a time in one call each instead of one call per/// file. `None` from an object that does not yet answer this question.pubfn media_held_sealed(&self, keys: &[String]) -> Result<Option<std::collections::BTreeSet<String>>> {letmut held = std::collections::BTreeSet::new();for batch in keys.chunks(MISSING_KEYS) {let answer = self.post_json("/v1/media/missing", &json!({ "keys": batch, "sealed": true }))?;if answer.get("sealed") != Some(&Value::Bool(true)) {returnOk(None); }let missing: std::collections::BTreeSet<&str> = answer.get("missing").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); held.extend(batch.iter().filter(|key| !missing.contains(key.as_str())).cloned()); }Ok(Some(held)) }/// What the object stores under `key`: its type and size, or `None`.pubfn media_stored(&self, key: &str) -> Result<Option<Stored>> {matchself.send(self.http.head(self.url(&Self::media_path(key)))) {Ok(response) => {let header = |name| response.headers().get(name).and_then(|v: &reqwest::header::HeaderValue| v.to_str().ok()).unwrap_or("").to_string();let size = header(reqwest::header::CONTENT_LENGTH).parse().map_err(|_| ObjectError::Decode(format!("{key}: the object named no size")))?;Ok(Some(Stored { content_type: header(reqwest::header::CONTENT_TYPE), size })) }Err(ObjectError::Refused { status: 404, .. }) => Ok(None),Err(error) => Err(error), } }/// The `size` bytes stored under `key`, written to `out` as they are/// stored (a sealed file unopened), read a range of [`PART_BYTES`] at a/// time so no one request outlives the client's ceiling.pubfn get_media_to(&self, key: &str, size: u64, out: &mutdyn std::io::Write) -> Result<()> {let at = self.url(&Self::media_path(key));letmut got = 0u64;while got < size {let end = (got + PART_BYTES).min(size) - 1;let response = self.send(self.http.get(&at).header(reqwest::header::RANGE, format!("bytes={got}-{end}")))?;let bytes = response.bytes().map_err(|e| ObjectError::Transport(e.to_string()))?;if bytes.len() as u64 != end + 1 - got {returnErr(ObjectError::Decode(format!("{key}: a read of {} bytes came back as {}", end + 1 - got, bytes.len()))); } out.write_all(&bytes).map_err(|e| ObjectError::Transport(format!("{key}: {e}")))?; got = end + 1; }Ok(()) }/// The key that seals and opens the person's file `key`. Refused by name/// (`seal_key_missing`) while this Mac holds no data key: a person's file/// waits here and never goes up open (e2e rulings R2, R6).pubfn person_file_key(&self, key: &str) -> Result<cotton_core::seal::file::FileKey> {let missing = |message: String| ObjectError::Refused { status: 0, code: cotton_client::seal::SEAL_KEY_MISSING.to_string(), message };let files = self.files.as_ref().ok_or_else(|| missing("this Mac holds no data key yet, so the file waits here".to_string()))?; files.file_key(key).map_err(|refusal| missing(refusal.message)) }/// The file at `path` (`size` bytes) under `key`, as a device sends it/// (e2e rulings R6): a person's photo, video, book, song or film is sealed/// as it is read (the f1 format under the file's own key, the same bytes a/// phone would send), any other key goes as it is. A person's file the/// object already holds sealed is left; one it holds in the clear is put/// again sealed. Answers the bytes sent.pubfn put_person_file(&self, key: &str, path: &std::path::Path, size: u64, content_type: &str) -> Result<u64> {self.put_person_file_as(key, path, size, content_type, false) }/// [`ObjectClient::put_person_file`], and with `replace` the file goes/// sealed even where the key holds a sealed file already, in one write/// over it: a film's master named afresh when its ladder is added/// (`pnpm film:ladder`), the old one played until that write lands.pubfn put_person_file_as(&self, key: &str, path: &std::path::Path, size: u64, content_type: &str, replace: bool) -> Result<u64> {let open = || std::fs::File::open(path).map_err(|e| ObjectError::File(format!("{}: {e}", path.display())));if !is_person_key(key) {ifself.media_held(key)? {returnOk(0); }self.put_from(key, &mut open()?, size, content_type, path)?;returnOk(size); }let fk = self.person_file_key(key)?;if !replace && self.media_type(key)?.is_some_and(|held| is_sealed_type(&held)) {returnOk(0); }letmut sealing = cotton_core::seal::file::SealingReader::new(&fk, key, std::io::BufReader::new(open()?), size);let sealed_size = sealing.sealed_len();self.put_from(key, &mut sealing, sealed_size, SEALED_FILE_TYPE, path)?;Ok(sealed_size) }/// [`ObjectClient::put_person_file`] for bytes in hand (a cover).pubfn put_person_bytes(&self, key: &str, bytes: Vec<u8>, content_type: &str) -> Result<u64> {if !is_person_key(key) {let size = bytes.len() as u64;self.put_media(key, bytes, content_type)?;returnOk(size); }let fk = self.person_file_key(key)?;ifself.media_type(key)?.is_some_and(|held| is_sealed_type(&held)) {returnOk(0); }let size = bytes.len() as u64;letmut sealing = cotton_core::seal::file::SealingReader::new(&fk, key, std::io::Cursor::new(bytes), size);let sealed_size = sealing.sealed_len();self.put_from(key, &mut sealing, sealed_size, SEALED_FILE_TYPE, std::path::Path::new(key))?;Ok(sealed_size) }/// `size` bytes of `body` under `key`: one request, or parts over [`PART_BYTES`].fn put_from(&self, key: &str, body: &mutdyn std::io::Read, size: u64, content_type: &str, what: &std::path::Path) -> Result<()> {if size > PART_BYTES {returnself.put_parts_from(key, body, size, content_type, what); }letmut bytes = Vec::with_capacity(size as usize); body.read_to_end(&mut bytes).map_err(|e| ObjectError::File(format!("{}: {e}", what.display())))?;if bytes.len() as u64 != size {returnErr(ObjectError::File(format!("{} changed while it was sent", what.display()))); }self.put_media(key, bytes, content_type) }/// The file at `path`, `size` bytes, put under `key` in parts of/// [`PART_BYTES`] (`POST ?uploads`, a `PUT ?upload=&part=` each, `POST/// ?upload=` to finish), read a part at a time. A part the object refused/// fails the whole; the next pass starts it again.pubfn put_media_in_parts(&self, key: &str, path: &std::path::Path, size: u64, content_type: &str) -> Result<()> {letmut file = std::fs::File::open(path).map_err(|e| ObjectError::File(format!("{}: {e}", path.display())))?;self.put_parts_from(key, &mut file, size, content_type, path) }fn put_parts_from(&self, key: &str, body: &mutdyn std::io::Read, size: u64, content_type: &str, path: &std::path::Path) -> Result<()> {use std::io::Readas _;let at = Self::media_path(key);let started = self.post_json(&format!("{at}?uploads"), &json!({ "size": size, "content_type": content_type }))?;if started.get("stored") == Some(&Value::Bool(false)) {returnOk(()); }let upload = started .get("upload") .and_then(Value::as_str) .ok_or_else(|| ObjectError::Decode("the object started no upload".to_string()))? .to_string();let query = url::form_urlencoded::Serializer::new(String::new()).append_pair("upload", &upload).finish();letmut parts = Vec::new();letmut sent = 0u64;letmut number = 1u32;while sent < size {let want = PART_BYTES.min(size - sent);letmut bytes = Vec::with_capacity(want as usize); (&mut *body) .take(want) .read_to_end(&mut bytes) .map_err(|e| ObjectError::File(format!("{}: {e}", path.display())))?;if bytes.len() as u64 != want {returnErr(ObjectError::File(format!("{} changed while it was sent", path.display()))); }let response = self.send(self.http .put(self.url(&format!("{at}?{query}&part={number}"))) .header(reqwest::header::CONTENT_TYPE, "application/octet-stream") .body(bytes), )?;let answer: Value = response.json().map_err(|e| ObjectError::Decode(e.to_string()))?;let etag = answer .get("etag") .and_then(Value::as_str) .ok_or_else(|| ObjectError::Decode("a part came back with no etag".to_string()))?; parts.push(json!({ "part": number, "etag": etag })); sent += want; number += 1; }self.post_json(&format!("{at}?{query}"), &json!({ "parts": parts }))?;Ok(()) }// ── the importer's own copy ──────────────────────────────────────────/// The object's definitions as served (`GET /v1/definitions`): every/// table with its columns and its `seal` block.pubfn definitions(&self) -> Result<Value> {let response = self.send(self.http.get(self.url("/v1/definitions")))?; response.json().map_err(|e| ObjectError::Decode(e.to_string())) }/// One page of `GET /v1/sync` of `tables` since `since`, or the page/// `cursor` names: `{ version, rows, next? }`, rows as the object holds/// them (a sealed row's blob unopened).pubfn sync_page(&self, since: i64, tables: &[&str], cursor: Option<&str>) -> Result<Value> {let query: Vec<(&str, String)> = match cursor {Some(cursor) => vec![("cursor", cursor.to_string())],None => vec![("since", since.to_string()), ("tables", tables.join(",")), ("limit", "5000".to_string())], };let response = self.send(self.http.get(self.url("/v1/sync")).query(&query))?; response.json().map_err(|e| ObjectError::Decode(e.to_string())) }/// The rows the importer's engines planned over its own copy, landed in/// one transaction (`import_rows`, at most [`IMPORT_ROWS`]): each/// `{ table, id, data?, blind?, created_at?, updated_at?, retract? }`.pubfn import_rows(&self, rows: &[Value]) -> Result<Value> {self.post_json("/v1/act", &json!({ "act": "import_rows", "args": { "rows": rows } })) }// ── plain rows ───────────────────────────────────────────────────────pubfn act(&self, act: Act, table: &str, id: &str, data: &Value) -> Result<Value> {self.act_as(act, table, id, data, false) }/// `act`, said as an import's (`import: true`) when `import`: the object/// logs only that it happened, never what it wrote, so it is not undone/// (the change log, apps/business/src/changes.ts). A sealed table's rows/// land through `import_rows`, which keeps no log at all.pubfn act_as(&self, act: Act, table: &str, id: &str, data: &Value, import: bool) -> Result<Value> {ifletSome(door) = &self.sealed {ifletSome(answer) = door.act(self, act, table, id, data)? {returnOk(answer); } }letmut args = json!({ "table": table, "id": id, "data": data });if import { args["import"] = Value::Bool(true); }self.post_json("/v1/act", &json!({ "act": act.as_str(), "args": args })) }/// A plain row by its own id: `create`, and when the id is taken/// (`409 duplicate_id`, a re-read) the same row as `update`.pubfn upsert(&self, table: &str, id: &str, data: &Value) -> Result<Value> {self.upsert_as(table, id, data, false) }/// `upsert`, said as an import's when `import` (`act_as`).pubfn upsert_as(&self, table: &str, id: &str, data: &Value, import: bool) -> Result<Value> {matchself.act_as(Act::Create, table, id, data, import) {Err(ObjectError::Refused { status: 409, code, .. }) if code == "duplicate_id" => {self.act_as(Act::Update, table, id, data, import) } other => other, } }/// Every live row of `table`, opened when sealed, read as a device reads/// (`/v1/sync`); `None` when this client holds no seal door (a token's/// client, which reads over `/mcp`).pubfn device_rows(&self, table: &str) -> Option<Result<Vec<Value>>> {self.sealed.as_ref().map(|door| door.rows(self, table)) }/// One live row of `table` by its id, opened when sealed, read over/// `/v1/sync` from `since` without bringing the whole copy up/// ([`crate::copy::SealDoor::row`]); `None` when this client holds no seal door.pubfn device_row(&self, table: &str, id: &str, since: i64) -> Option<Result<Option<Value>>> {self.sealed.as_ref().map(|door| door.row(self, table, id, since)) }/// One row of `table` as the object holds it now, opened when sealed (the seal door's copy read up first,/// [`crate::copy::SealDoor::row_now`]); `None` when this client holds no seal door.pubfn row_now(&self, table: &str, id: &str) -> Option<Result<Option<serde_json::Map<String, Value>>>> {self.sealed.as_ref().map(|door| door.row_now(self, table, id)) }// ── any route ────────────────────────────────────────────────────────/// `GET <path>?<query>`, its JSON answer (the seal migration's reads:/// `/v1/definitions`, `/v1/sync`, `/v1/seal/twins`).pubfn get_json(&self, path: &str, query: &[(&str, String)]) -> Result<Value> {let response = self.send(self.http.get(self.url(path)).query(query))?; response.json().map_err(|e| ObjectError::Decode(e.to_string())) }/// `POST <path>` with a JSON body, its JSON answer (the way back in by a recovery code).pubfn post_route(&self, path: &str, body: &Value) -> Result<Value> {self.post_json(path, body) }/// `POST /v1/act { act, args }`, the act's answer.pubfn post_act(&self, act: &str, args: &Value) -> Result<Value> {self.post_json("/v1/act", &json!({ "act": act, "args": args })) }// ── Cotton MCP ───────────────────────────────────────────────────────/// One Cotton MCP tool (`POST /mcp`, `tools/call`), its answer parsed/// from the text it says; a refusal is the tool's own sentence.pubfn tool(&self, name: &str, arguments: &Value) -> Result<Value> {let answer = self.post_json("/mcp", &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": name, "arguments": arguments } }), )?;letSome(result) = answer.get("result") else {let message = answer.pointer("/error/message").and_then(Value::as_str).unwrap_or("no answer").to_string();returnErr(ObjectError::Refused { status: 400, code: "mcp_error".to_string(), message: format!("{name}: {message}") }); };let text = result.pointer("/content/0/text").and_then(Value::as_str).unwrap_or_default();if result.get("isError") == Some(&Value::Bool(true)) {let code = result.pointer("/structuredContent/code").and_then(Value::as_str).unwrap_or("tool_refused").to_string();returnErr(ObjectError::Refused { status: 400, code, message: format!("{name}: {text}") }); } serde_json::from_str(text).map_err(|e| ObjectError::Decode(format!("{name}: {e}"))) }// ── sends from the phone ─────────────────────────────────────────────/// The outbox rows in `status` (`queued`, for the Mac to send).pubfn outbox(&self, status: &str) -> Result<Vec<Value>> {let response = self.send(self.http .get(self.url("/v1/outbox")) .query(&[("status", status)]), )?;let body: Value = response.json().map_err(|e| ObjectError::Decode(e.to_string()))?;let rows = body .get("rows") .or_else(|| body.get("outbox")) .cloned() .unwrap_or(body);let rows = match rows {Value::Array(rows) => rows, _ => returnErr(ObjectError::Decode("the outbox is not a list".to_string())), };match &self.sealed {// A sealed outbox's words open here, on this Mac, to be sent.Some(door) => door.open_listed(self, "outbox", rows),None => Ok(rows), } }}/// What the object stores under a key (`HEAD /v1/media/<key>`).#[derive(Debug, Clone, PartialEq, Eq)]pubstructStored {pub content_type: String,pub size: u64,}implStored {/// Whether the stored file is a sealed one (f1, or sealed at arrival).pubfn sealed(&self) -> bool { is_sealed_type(&self.content_type) }}/// Whether `key` names a person's photo, video, book, song or film file/// (`<database id>/<kind>/…`), which only ever leaves this Mac sealed.pubfn is_person_key(key: &str) -> bool {letmut parts = key.splitn(3, '/'); matches!((parts.next(), parts.next(), parts.next()), (Some(db), Some(kind), Some(rest)) if !db.is_empty() && !rest.is_empty() && SEALED_KINDS.contains(&kind))}/// Whether a stored type is a sealed file's (the Worker's `isSealedType`).pubfn is_sealed_type(content_type: &str) -> bool { content_type.split(';').next().unwrap_or("").trim().eq_ignore_ascii_case(SEALED_FILE_TYPE)}/// Percent-encode one path segment; a key's own `/` stays a separator.fn encode_segment(segment: &str) -> String {letmut out = String::with_capacity(segment.len());for byte in segment.bytes() {match byte { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(byte as char), _ => out.push_str(&format!("%{byte:02X}")), } } out}#[cfg(test)]mod tests {usesuper::*; #[test]fn media_paths_keep_the_key_shape() { assert_eq!(ObjectClient::media_path("db/photos/ab.heic"),"/v1/media/db/photos/ab.heic" ); assert_eq!(ObjectClient::media_path("db/a b/c"), "/v1/media/db/a%20b/c"); } #[test]fn host_is_the_origin_without_scheme() {let client = ObjectClient::new("https://cottondb.com/", None).unwrap(); assert_eq!(client.host(), "cottondb.com"); assert_eq!(client.base(), "https://cottondb.com"); }}