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