Skip to main content

perspective_viewer/utils/
completion.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use std::future::Future;
14
15use futures::channel::oneshot;
16use perspective_js::utils::*;
17
18/// A completion handle for message-based public API methods (invariant I6 —
19/// see `SESSION_CONFIG_COHERENCE_PLAN.md`): its ONLY resolution API is
20/// [`Completion::resolve_after`], which takes a run future — so resolving a
21/// public method's promise at message-handling time (before the renders it
22/// caused have drawn) is unwritable, not merely discouraged. Dropping an
23/// unresolved `Completion` rejects the caller as cancelled.
24pub struct Completion(Option<oneshot::Sender<ApiResult<()>>>);
25
26impl Completion {
27    #[allow(clippy::new_ret_no_self)]
28    pub fn new() -> (Self, oneshot::Receiver<ApiResult<()>>) {
29        let (sender, receiver) = oneshot::channel();
30        (Self(Some(sender)), receiver)
31    }
32
33    /// Resolve this completion with `run`'s result when it settles. The
34    /// caller relinquishes the handle — one run, one resolution.
35    pub fn resolve_after(mut self, run: impl Future<Output = ApiResult<()>> + 'static) {
36        let sender = self.0.take().unwrap();
37        ApiFuture::spawn(async move {
38            let _ = sender.send(run.await);
39            Ok(())
40        });
41    }
42}
43
44impl std::fmt::Debug for Completion {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.debug_struct("Completion").finish()
47    }
48}
49
50impl Drop for Completion {
51    fn drop(&mut self) {
52        if let Some(sender) = self.0.take() {
53            let _ = sender.send(Err(ApiError::new("Cancelled")));
54        }
55    }
56}