Skip to main content

kovlet/
spaces.rs

1//! The app-scoped spaces API (PROTOCOL.md §2.8, ADR 0019): list, create,
2//! find-or-create, and grant requests for more spaces without signing in again.
3
4use std::collections::BTreeMap;
5use std::sync::Arc;
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9use serde_json::{json, Value};
10
11use crate::auth::SlotGrant;
12use crate::engine::Ctx;
13use crate::error::{Error, Result};
14
15/// A space this app can reach.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17pub struct SpaceInfo {
18    pub id: String,
19    #[serde(default)]
20    pub name: String,
21    #[serde(default)]
22    pub slug: String,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub icon: Option<String>,
25    /// `viewer`, `editor`, …; empty while an admin must still approve (`reason`).
26    #[serde(default)]
27    pub role: String,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub reason: Option<String>,
30    #[serde(default)]
31    pub workspace_id: String,
32    #[serde(default)]
33    pub head_seq: i64,
34}
35
36/// `GET /v1/spaces` for an app session.
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub struct SpaceList {
39    pub spaces: Vec<SpaceInfo>,
40    /// The user's other spaces the app could ask for.
41    #[serde(default)]
42    pub requestable: u32,
43    #[serde(default)]
44    pub can_create: bool,
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub create_blocked: Option<Value>,
47    /// True when the server couldn't be reached and this is the last list
48    /// this client saw (kept in its SyncStore), so an app can open its
49    /// spaces offline.
50    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
51    pub offline: bool,
52}
53
54const CACHE_KEY: &str = "spaces";
55
56/// True for failures in transit (no answer from the server).
57fn unreachable(e: &Error) -> bool {
58    e.code == "network" || e.code == "timeout"
59}
60
61fn cached(ctx: &Ctx) -> Option<SpaceList> {
62    let s = ctx.meta.meta_get(CACHE_KEY).ok().flatten()?;
63    let mut l: SpaceList = serde_json::from_str(&s).ok()?;
64    l.offline = true;
65    Some(l)
66}
67
68fn remember(ctx: &Ctx, l: &SpaceList) {
69    if let Ok(s) = serde_json::to_string(l) {
70        let _ = ctx.meta.meta_set(CACHE_KEY, &s);
71    }
72}
73
74/// Drops the last-known list (sign-out).
75pub(crate) fn forget(ctx: &Ctx) -> Result<()> {
76    ctx.meta.meta_set(CACHE_KEY, "")
77}
78
79/// One ask in a grant request.
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81pub struct Ask {
82    /// `viewer` or `editor`.
83    pub role: String,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub slot: Option<String>,
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub space_id: Option<String>,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub suggested_name: Option<String>,
90}
91
92impl Ask {
93    pub fn editor() -> Ask {
94        Ask { role: "editor".into(), slot: None, space_id: None, suggested_name: None }
95    }
96}
97
98/// A granted space from a grant request.
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
100pub struct Granted {
101    pub space_id: String,
102    #[serde(default)]
103    pub name: String,
104    #[serde(default)]
105    pub role: String,
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub slot: Option<String>,
108    #[serde(default)]
109    pub created: bool,
110}
111
112/// How a grant request ended.
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct GrantResult {
115    /// `approved`, `denied` or `expired`.
116    pub status: String,
117    #[serde(default)]
118    pub spaces: Vec<Granted>,
119}
120
121/// `client.spaces()`. Calls wait for a sign-in by default; see [`Spaces::no_wait`].
122#[derive(Clone)]
123pub struct Spaces {
124    pub(crate) ctx: Arc<Ctx>,
125    pub(crate) wait: bool,
126}
127
128impl Spaces {
129    /// These calls fail with `signed_out` straight away while there is no
130    /// session, instead of waiting for a sign-in (for UI calls that must
131    /// not hang).
132    pub fn no_wait(mut self) -> Spaces {
133        self.wait = false;
134        self
135    }
136
137    fn api(&self) -> crate::api::Api {
138        self.ctx.api.waiting(self.wait)
139    }
140
141    /// The spaces this app can reach, and whether it may create one.
142    ///
143    /// When the server can't be reached, this answers with the last list the
144    /// client saw (`offline: true`), so an app can open its spaces and work
145    /// offline; it fails only when there is none.
146    pub async fn list(&self) -> Result<SpaceList> {
147        let api = self.api();
148        let r = self
149            .ctx
150            .handle
151            .spawn(async move { api.json("GET", "/v1/spaces", None).await })
152            .await
153            .map_err(Error::network)?;
154        match r {
155            Ok(v) => {
156                let l: SpaceList = serde_json::from_value(v)?;
157                remember(&self.ctx, &l);
158                Ok(l)
159            }
160            Err(e) if unreachable(&e) => cached(&self.ctx).ok_or(e),
161            Err(e) => Err(e),
162        }
163    }
164
165    /// Creates a space owned by the signed-in user and grants it to this app.
166    /// Pass a `slug` so a retry after a network error can't create a duplicate.
167    pub async fn create(&self, name: &str, slug: Option<&str>) -> Result<SpaceInfo> {
168        let mut body = json!({ "name": name });
169        if let Some(s) = slug {
170            body["slug"] = json!(s);
171        }
172        let api = self.api();
173        let v = self
174            .ctx
175            .handle
176            .spawn(async move { api.json("POST", "/v1/spaces", Some(&body)).await })
177            .await
178            .map_err(Error::network)??;
179        let space: SpaceInfo = serde_json::from_value(v.get("space").cloned().unwrap_or(v))?;
180        if let Some(mut l) = cached(&self.ctx) {
181            l.offline = false;
182            l.spaces.retain(|s| s.id != space.id);
183            l.spaces.push(space.clone());
184            remember(&self.ctx, &l);
185        }
186        Ok(space)
187    }
188
189    /// The first granted space with this name, or a new one: the "pick or
190    /// create" step every quickstart needs. Offline, it finds the space in
191    /// the last-known list; it can't create one until the server is back.
192    pub async fn find_or_create(&self, name: &str) -> Result<SpaceInfo> {
193        let list = self.list().await?;
194        let offline = list.offline;
195        if let Some(s) = list.spaces.into_iter().find(|s| s.name == name && !s.role.is_empty()) {
196            return Ok(s);
197        }
198        if offline {
199            return Err(Error::new(
200                "network",
201                format!("the server can't be reached, and no space named {name:?} is known yet"),
202            )
203            .with_hint(
204                "Retry once the device is online: the first sign-in needs the network to find or create the space.",
205            ));
206        }
207        let slug = slugify(name);
208        match self.create(name, Some(&slug)).await {
209            Err(e) if e.code == "slug_taken" => {
210                // A retry of our own create made it already, or the user has
211                // another space with that slug that this app can't see.
212                let list = self.list().await?;
213                match list.spaces.into_iter().find(|s| s.name == name && !s.role.is_empty()) {
214                    Some(s) => Ok(s),
215                    None => self.create(name, None).await,
216                }
217            }
218            r => r,
219        }
220    }
221
222    /// Asks the user for more spaces on the same session and machine.
223    /// `on_approve_url` gets the URL to show (a browser sheet, a link, a QR code);
224    /// the call then polls until the user decides or the request expires.
225    pub async fn request_access(
226        &self,
227        asks: Vec<Ask>,
228        on_approve_url: impl Fn(&str) + Send + Sync + 'static,
229    ) -> Result<GrantResult> {
230        let ctx = self.ctx.clone();
231        let api = self.api();
232        self.ctx
233            .handle
234            .spawn(async move {
235                let created = api.json("POST", "/v1/grant-requests", Some(&json!({ "asks": asks }))).await?;
236                let id = created.get("request").and_then(Value::as_str).unwrap_or_default().to_string();
237                let url = created.get("approve_url").and_then(Value::as_str).unwrap_or_default().to_string();
238                on_approve_url(&url);
239                let interval = Duration::from_secs(created.get("interval").and_then(Value::as_u64).unwrap_or(2).max(1));
240                let deadline = tokio::time::Instant::now()
241                    + Duration::from_secs(created.get("expires_in").and_then(Value::as_u64).unwrap_or(600))
242                    + interval;
243                while tokio::time::Instant::now() < deadline {
244                    tokio::time::sleep(interval).await;
245                    let st = match api.json("GET", &format!("/v1/grant-requests/{}", crate::api::seg(&id)), None).await
246                    {
247                        Ok(v) => v,
248                        Err(e) if e.is_transient() => continue,
249                        Err(e) => return Err(e),
250                    };
251                    let r: GrantResult = serde_json::from_value(st)?;
252                    if r.status == "pending" {
253                        continue;
254                    }
255                    let slots: BTreeMap<String, SlotGrant> = r
256                        .spaces
257                        .iter()
258                        .filter_map(|g| {
259                            g.slot
260                                .clone()
261                                .map(|s| (s, SlotGrant { space_id: g.space_id.clone(), role: g.role.clone() }))
262                        })
263                        .collect();
264                    if !slots.is_empty() {
265                        ctx.auth.merge_slots(slots)?;
266                    }
267                    return Ok(r);
268                }
269                Ok(GrantResult { status: "expired".into(), spaces: vec![] })
270            })
271            .await
272            .map_err(Error::network)?
273    }
274}
275
276fn slugify(name: &str) -> String {
277    let mut s = String::new();
278    for c in name.chars().flat_map(char::to_lowercase) {
279        if c.is_ascii_alphanumeric() {
280            s.push(c);
281        } else if !s.ends_with('-') && !s.is_empty() {
282            s.push('-');
283        }
284    }
285    let s = s.trim_end_matches('-').to_string();
286    if s.is_empty() {
287        "space".into()
288    } else {
289        s.chars().take(48).collect()
290    }
291}