Skip to main content

subspace_shell/
account.rs

1//! One optional native account per product, from the identity provider the
2//! app registers, independent of settings drafts.
3
4use gpui_kit::{App, AppContext as _, Context, Entity, Global};
5use std::sync::Arc;
6use subspace_account::{Account, Cancel, Error, Provider, ProviderInfo, Started};
7
8mod bootstrap;
9mod lease;
10mod rules;
11pub(crate) use bootstrap::init;
12use lease::LeaseGate;
13pub use lease::{AccountSession, AccountTokenSource};
14pub(crate) use rules::Session;
15pub(crate) use rules::{account_label, sign_in_label, status_text};
16use rules::{after, asks, holds};
17
18/// How an app adds a native account: its identity provider and the trusted
19/// adapter it hands the token source to before Spaces start.
20pub struct AccountRegistration {
21    /// Builds the provider. Its argument is the product's bundle identifier,
22    /// a stable namespace for the provider's keychain entries.
23    pub provider: fn(&str) -> Option<Arc<dyn Provider>>,
24    /// Installs the app's trusted native token consumer, such as an API client.
25    pub configure: Option<fn(AccountTokenSource)>,
26    /// Whether the app cannot be used without the account. The shell then
27    /// asks for sign-in over the main window whenever there is no session,
28    /// at start-up and when a session ends, if the provider needs a person
29    /// to sign in. A saved session it cannot renew because the service is
30    /// out of reach still lets the person in.
31    pub required: bool,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub(crate) enum Status {
36    Unavailable,
37    Idle,
38    Starting,
39    Waiting,
40    Completing,
41    Refreshing,
42    SigningOut,
43    Failed(Error),
44}
45
46#[derive(Clone, Copy)]
47enum Retry {
48    SignIn,
49    Restore,
50    Reconnect,
51    SignOut,
52}
53
54pub(crate) struct NativeAccount {
55    /// Whether the app asks for sign-in over the main window without a
56    /// session ([`AccountRegistration::required`]).
57    pub required: bool,
58    manager: Option<Arc<dyn Provider>>,
59    gate: Arc<LeaseGate>,
60    pub provider: ProviderInfo,
61    pub account: Option<Account>,
62    pub status: Status,
63    before_sign_in: Status,
64    retry: Retry,
65    /// The person's session, apart from the last sign-in attempt's outcome.
66    pub session: Session,
67    cancel: Option<Cancel>,
68    url: Option<String>,
69    /// The user code to confirm in the browser, during device authorisation.
70    pub code: Option<String>,
71    run: u64,
72}
73
74struct Shared(Entity<NativeAccount>);
75impl Global for Shared {}
76
77pub(crate) fn shared(cx: &App) -> Option<Entity<NativeAccount>> {
78    cx.try_global::<Shared>().map(|v| v.0.clone())
79}
80
81/// A product-composition seam for a trusted native service adapter, such as
82/// a Space crate an app adds that calls its own API with the account.
83// qual:api — the product chooses the allowed native resource, never a webpage.
84pub fn account_session(cx: &App) -> Option<AccountSession> {
85    let state = shared(cx)?;
86    let state = state.read(cx);
87    let valid = matches!(state.status, Status::Idle | Status::Refreshing)
88        || (matches!(state.status, Status::Failed(_)) && matches!(state.retry, Retry::Reconnect));
89    if !valid {
90        return None;
91    }
92    let manager = state.manager.clone()?;
93    Some(AccountSession {
94        gate: state.gate.clone(),
95        generation: manager.generation(),
96        account: state.account.clone()?,
97        manager,
98    })
99}
100
101impl NativeAccount {
102    /// Whether the shell asks for sign-in over the main window now.
103    pub(crate) fn asks_for_sign_in(&self) -> bool {
104        self.required && self.provider.browser && asks(self.session, self.status)
105    }
106
107    /// Whether a notification or another route from outside the window
108    /// waits until sign-in: while the shell asks for it, or may yet.
109    pub(crate) fn holds_routes(&self) -> bool {
110        self.required && self.provider.browser && holds(self.session, self.status)
111    }
112
113    pub fn busy(&self) -> bool {
114        matches!(
115            self.status,
116            Status::Starting
117                | Status::Waiting
118                | Status::Completing
119                | Status::Refreshing
120                | Status::SigningOut
121        )
122    }
123
124    pub fn start(&mut self, cx: &mut Context<Self>) {
125        if self.busy() {
126            return;
127        }
128        let Some(manager) = self.manager.clone() else {
129            return;
130        };
131        self.close_leases(manager.as_ref());
132        let generation = manager.generation();
133        self.run += 1;
134        let run = self.run;
135        let cancel = Cancel::default();
136        self.retry = Retry::SignIn;
137        self.before_sign_in = self.status;
138        self.cancel = Some(cancel.clone());
139        self.status = Status::Starting;
140        cx.notify();
141        cx.spawn(async move |this, cx| {
142            let starter = manager.clone();
143            let started = cx.background_spawn(async move { starter.start() }).await;
144            let started = match started {
145                Ok(value) => value,
146                Err(error) => {
147                    let _ = this.update(cx, |this, cx| this.finish(run, Err(error), cx));
148                    return;
149                }
150            };
151            let current = this
152                .update(cx, |this, cx| this.show_sign_in_prompt(run, &started, cx))
153                .unwrap_or(false);
154            if !current {
155                cancel.cancel();
156                return;
157            }
158            let result = cx
159                .background_spawn(
160                    async move { manager.finish(started, &cancel, generation).map(Some) },
161                )
162                .await;
163            let _ = this.update(cx, |this, cx| this.finish(run, result, cx));
164        })
165        .detach();
166    }
167
168    fn show_sign_in_prompt(&mut self, run: u64, started: &Started, cx: &mut Context<Self>) -> bool {
169        if self.run != run {
170            return false;
171        }
172        self.url = started.url.clone();
173        self.code = started.code.clone();
174        // A provider without a browser leg completes headlessly.
175        self.status = if self.url.is_some() {
176            Status::Waiting
177        } else {
178            Status::Completing
179        };
180        self.reopen(cx);
181        cx.notify();
182        true
183    }
184
185    pub fn cancel(&mut self, cx: &mut Context<Self>) {
186        if let Some(cancel) = &self.cancel
187            && !cancel.cancel()
188        {
189            self.status = Status::Completing;
190            cx.notify();
191            return;
192        }
193        self.cancel = None;
194        if let Some(manager) = &self.manager {
195            manager.invalidate();
196        }
197        self.gate.open();
198        self.run += 1;
199        self.url = None;
200        self.code = None;
201        self.status = self.before_sign_in;
202        cx.notify();
203    }
204
205    pub fn reopen(&self, cx: &mut Context<Self>) {
206        if let Some(url) = &self.url {
207            cx.open_url(url);
208        }
209    }
210
211    pub fn retry(&mut self, cx: &mut Context<Self>) {
212        match self.retry {
213            Retry::SignIn => self.start(cx),
214            Retry::Restore => self.restore(cx),
215            Retry::Reconnect => self.reconnect(cx),
216            Retry::SignOut => self.sign_out(cx),
217        }
218    }
219
220    fn restore(&mut self, cx: &mut Context<Self>) {
221        self.renew(true, cx);
222    }
223    pub fn reconnect(&mut self, cx: &mut Context<Self>) {
224        self.renew(false, cx);
225    }
226
227    fn renew(&mut self, restore: bool, cx: &mut Context<Self>) {
228        if self.busy() {
229            return;
230        }
231        let Some(manager) = self.manager.clone() else {
232            return;
233        };
234        self.run += 1;
235        let run = self.run;
236        self.retry = if restore {
237            Retry::Restore
238        } else {
239            Retry::Reconnect
240        };
241        self.status = Status::Refreshing;
242        cx.notify();
243        cx.spawn(async move |this, cx| {
244            let result = cx
245                .background_spawn(async move {
246                    if restore {
247                        manager.restore()
248                    } else {
249                        manager.reconnect()
250                    }
251                })
252                .await;
253            let _ = this.update(cx, |this, cx| this.finish(run, result, cx));
254        })
255        .detach();
256    }
257
258    pub fn sign_out(&mut self, cx: &mut Context<Self>) {
259        if self.busy() {
260            return;
261        }
262        let Some(manager) = self.manager.clone() else {
263            return;
264        };
265        self.close_leases(manager.as_ref());
266        self.run += 1;
267        let run = self.run;
268        self.retry = Retry::SignOut;
269        self.status = Status::SigningOut;
270        cx.notify();
271        cx.spawn(async move |this, cx| {
272            let result = cx
273                .background_spawn(async move { manager.sign_out().map(|()| None) })
274                .await;
275            let _ = this.update(cx, |this, cx| this.finish(run, result, cx));
276        })
277        .detach();
278    }
279
280    fn finish(&mut self, run: u64, result: Result<Option<Account>, Error>, cx: &mut Context<Self>) {
281        if run != self.run {
282            return;
283        }
284        let browser = matches!(self.status, Status::Waiting | Status::Completing);
285        self.cancel = None;
286        self.url = None;
287        self.code = None;
288        self.reopen_leases(result.is_ok());
289        self.session = after(
290            self.session,
291            self.retry,
292            result.as_ref().map(Option::is_some).map_err(|error| *error),
293        );
294        match result {
295            Ok(account) => {
296                self.account = account;
297                self.status = Status::Idle;
298                if browser {
299                    cx.activate(true);
300                }
301            }
302            Err(Error::Cancelled) => self.status = self.before_sign_in,
303            Err(error) => self.status = Status::Failed(error),
304        }
305        cx.notify();
306    }
307
308    /// Before a sign-in or sign-out, refuse leases and supersede in-flight work.
309    fn close_leases(&self, manager: &dyn Provider) {
310        self.gate.close();
311        manager.invalidate();
312    }
313
314    /// After a sign-in or sign-out ends, mark a committed account change with
315    /// a new generation before any lease can see it, then allow leases again.
316    fn reopen_leases(&self, committed: bool) {
317        if self.gate.is_open() {
318            return;
319        }
320        if committed && let Some(manager) = &self.manager {
321            manager.invalidate();
322        }
323        self.gate.open();
324    }
325}
326
327#[cfg(any(test, all(debug_assertions, feature = "capture")))]
328mod fixtures;
329#[cfg(test)]
330mod tests;
331#[cfg(any(test, all(debug_assertions, feature = "capture")))]
332pub(crate) use fixtures::seed as fixture;