kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! The app-scoped spaces API (PROTOCOL.md §2.8, ADR 0019): list, create,
//! find-or-create, and grant requests for more spaces without signing in again.

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::auth::SlotGrant;
use crate::engine::Ctx;
use crate::error::{Error, Result};

/// A space this app can reach.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpaceInfo {
    pub id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub slug: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    /// `viewer`, `editor`, …; empty while an admin must still approve (`reason`).
    #[serde(default)]
    pub role: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default)]
    pub workspace_id: String,
    #[serde(default)]
    pub head_seq: i64,
}

/// `GET /v1/spaces` for an app session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpaceList {
    pub spaces: Vec<SpaceInfo>,
    /// The user's other spaces the app could ask for.
    #[serde(default)]
    pub requestable: u32,
    #[serde(default)]
    pub can_create: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub create_blocked: Option<Value>,
    /// True when the server couldn't be reached and this is the last list
    /// this client saw (kept in its SyncStore), so an app can open its
    /// spaces offline.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub offline: bool,
}

const CACHE_KEY: &str = "spaces";

/// True for failures in transit (no answer from the server).
fn unreachable(e: &Error) -> bool {
    e.code == "network" || e.code == "timeout"
}

fn cached(ctx: &Ctx) -> Option<SpaceList> {
    let s = ctx.meta.meta_get(CACHE_KEY).ok().flatten()?;
    let mut l: SpaceList = serde_json::from_str(&s).ok()?;
    l.offline = true;
    Some(l)
}

fn remember(ctx: &Ctx, l: &SpaceList) {
    if let Ok(s) = serde_json::to_string(l) {
        let _ = ctx.meta.meta_set(CACHE_KEY, &s);
    }
}

/// Drops the last-known list (sign-out).
pub(crate) fn forget(ctx: &Ctx) -> Result<()> {
    ctx.meta.meta_set(CACHE_KEY, "")
}

/// One ask in a grant request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ask {
    /// `viewer` or `editor`.
    pub role: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slot: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suggested_name: Option<String>,
}

impl Ask {
    pub fn editor() -> Ask {
        Ask { role: "editor".into(), slot: None, space_id: None, suggested_name: None }
    }
}

/// A granted space from a grant request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Granted {
    pub space_id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub role: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slot: Option<String>,
    #[serde(default)]
    pub created: bool,
}

/// How a grant request ended.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GrantResult {
    /// `approved`, `denied` or `expired`.
    pub status: String,
    #[serde(default)]
    pub spaces: Vec<Granted>,
}

/// `client.spaces()`. Calls wait for a sign-in by default; see [`Spaces::no_wait`].
#[derive(Clone)]
pub struct Spaces {
    pub(crate) ctx: Arc<Ctx>,
    pub(crate) wait: bool,
}

impl Spaces {
    /// These calls fail with `signed_out` straight away while there is no
    /// session, instead of waiting for a sign-in (for UI calls that must
    /// not hang).
    pub fn no_wait(mut self) -> Spaces {
        self.wait = false;
        self
    }

    fn api(&self) -> crate::api::Api {
        self.ctx.api.waiting(self.wait)
    }

    /// The spaces this app can reach, and whether it may create one.
    ///
    /// When the server can't be reached, this answers with the last list the
    /// client saw (`offline: true`), so an app can open its spaces and work
    /// offline; it fails only when there is none.
    pub async fn list(&self) -> Result<SpaceList> {
        let api = self.api();
        let r = self
            .ctx
            .handle
            .spawn(async move { api.json("GET", "/v1/spaces", None).await })
            .await
            .map_err(Error::network)?;
        match r {
            Ok(v) => {
                let l: SpaceList = serde_json::from_value(v)?;
                remember(&self.ctx, &l);
                Ok(l)
            }
            Err(e) if unreachable(&e) => cached(&self.ctx).ok_or(e),
            Err(e) => Err(e),
        }
    }

    /// Creates a space owned by the signed-in user and grants it to this app.
    /// Pass a `slug` so a retry after a network error can't create a duplicate.
    pub async fn create(&self, name: &str, slug: Option<&str>) -> Result<SpaceInfo> {
        let mut body = json!({ "name": name });
        if let Some(s) = slug {
            body["slug"] = json!(s);
        }
        let api = self.api();
        let v = self
            .ctx
            .handle
            .spawn(async move { api.json("POST", "/v1/spaces", Some(&body)).await })
            .await
            .map_err(Error::network)??;
        let space: SpaceInfo = serde_json::from_value(v.get("space").cloned().unwrap_or(v))?;
        if let Some(mut l) = cached(&self.ctx) {
            l.offline = false;
            l.spaces.retain(|s| s.id != space.id);
            l.spaces.push(space.clone());
            remember(&self.ctx, &l);
        }
        Ok(space)
    }

    /// The first granted space with this name, or a new one: the "pick or
    /// create" step every quickstart needs. Offline, it finds the space in
    /// the last-known list; it can't create one until the server is back.
    pub async fn find_or_create(&self, name: &str) -> Result<SpaceInfo> {
        let list = self.list().await?;
        let offline = list.offline;
        if let Some(s) = list.spaces.into_iter().find(|s| s.name == name && !s.role.is_empty()) {
            return Ok(s);
        }
        if offline {
            return Err(Error::new(
                "network",
                format!("the server can't be reached, and no space named {name:?} is known yet"),
            )
            .with_hint(
                "Retry once the device is online: the first sign-in needs the network to find or create the space.",
            ));
        }
        let slug = slugify(name);
        match self.create(name, Some(&slug)).await {
            Err(e) if e.code == "slug_taken" => {
                // A retry of our own create made it already, or the user has
                // another space with that slug that this app can't see.
                let list = self.list().await?;
                match list.spaces.into_iter().find(|s| s.name == name && !s.role.is_empty()) {
                    Some(s) => Ok(s),
                    None => self.create(name, None).await,
                }
            }
            r => r,
        }
    }

    /// Asks the user for more spaces on the same session and machine.
    /// `on_approve_url` gets the URL to show (a browser sheet, a link, a QR code);
    /// the call then polls until the user decides or the request expires.
    pub async fn request_access(
        &self,
        asks: Vec<Ask>,
        on_approve_url: impl Fn(&str) + Send + Sync + 'static,
    ) -> Result<GrantResult> {
        let ctx = self.ctx.clone();
        let api = self.api();
        self.ctx
            .handle
            .spawn(async move {
                let created = api.json("POST", "/v1/grant-requests", Some(&json!({ "asks": asks }))).await?;
                let id = created.get("request").and_then(Value::as_str).unwrap_or_default().to_string();
                let url = created.get("approve_url").and_then(Value::as_str).unwrap_or_default().to_string();
                on_approve_url(&url);
                let interval = Duration::from_secs(created.get("interval").and_then(Value::as_u64).unwrap_or(2).max(1));
                let deadline = tokio::time::Instant::now()
                    + Duration::from_secs(created.get("expires_in").and_then(Value::as_u64).unwrap_or(600))
                    + interval;
                while tokio::time::Instant::now() < deadline {
                    tokio::time::sleep(interval).await;
                    let st = match api.json("GET", &format!("/v1/grant-requests/{}", crate::api::seg(&id)), None).await
                    {
                        Ok(v) => v,
                        Err(e) if e.is_transient() => continue,
                        Err(e) => return Err(e),
                    };
                    let r: GrantResult = serde_json::from_value(st)?;
                    if r.status == "pending" {
                        continue;
                    }
                    let slots: BTreeMap<String, SlotGrant> = r
                        .spaces
                        .iter()
                        .filter_map(|g| {
                            g.slot
                                .clone()
                                .map(|s| (s, SlotGrant { space_id: g.space_id.clone(), role: g.role.clone() }))
                        })
                        .collect();
                    if !slots.is_empty() {
                        ctx.auth.merge_slots(slots)?;
                    }
                    return Ok(r);
                }
                Ok(GrantResult { status: "expired".into(), spaces: vec![] })
            })
            .await
            .map_err(Error::network)?
    }
}

fn slugify(name: &str) -> String {
    let mut s = String::new();
    for c in name.chars().flat_map(char::to_lowercase) {
        if c.is_ascii_alphanumeric() {
            s.push(c);
        } else if !s.ends_with('-') && !s.is_empty() {
            s.push('-');
        }
    }
    let s = s.trim_end_matches('-').to_string();
    if s.is_empty() {
        "space".into()
    } else {
        s.chars().take(48).collect()
    }
}