Cotton code
56 lines · 2.1 KB · RustRaw
//! The phone's reader of published databases (`cotton_store::published`)://! the signed-in door's own address and credential, one POST per read//! (`apps/business/src/published.ts`). Installed once a process, at open; it//! asks the client for its door at each read, so a sign-in after open is heard//! and a sign-out answers `SignedOut`.use std::sync::{Arc, Weak};use cotton_client::transport::object::{bearer, ObjectRefusal};use cotton_store::published::{Answer, Ask, Reader, Unread};use serde_json::Value;use crate::shell::client::ClientController;#[derive(Debug)]pub struct PhoneReader {    client: Weak<ClientController>,}impl PhoneReader {    #[must_use]    pub fn new(client: &Arc<ClientController>) -> PhoneReader {        PhoneReader { client: Arc::downgrade(client) }    }}impl Reader for PhoneReader {    fn read(&self, publisher: &str, name: &str, table: &str, ask: &Ask) -> Result<Answer, Unread> {        let client = self.client.upgrade().ok_or(Unread::SignedOut)?;        let door = client.object_door().ok_or(Unread::SignedOut)?;        answer_of(door.address.send(door.exchange.as_ref(), "POST", &path(publisher, name, table), bearer(&door.credential), Some(&ask.body())))    }}/// The route one table is read at.#[must_use]pub fn path(publisher: &str, name: &str, table: &str) -> String {    format!("/v1/published/{publisher}/{name}/{table}/search")}/// The server's answer, or why there is none: nothing answered is offline, a/// credential it no longer takes is signed out, anything else its own refusal.pub fn answer_of(answered: Result<Value, ObjectRefusal>) -> Result<Answer, Unread> {    match answered {        Ok(body) => Ok(Answer {            version: body["version"].as_str().unwrap_or_default().to_string(),            rows: body["rows"].as_array().cloned().unwrap_or_default(),        }),        Err(refusal) if refusal.status == 0 => Err(Unread::Offline(refusal.message)),        Err(refusal) if refusal.status == 401 => Err(Unread::SignedOut),        Err(refusal) => Err(Unread::Refused { code: refusal.code, message: refusal.message }),    }}#[cfg(test)]#[path = "published_reader_tests.rs"]mod tests;