Skip to main content

menger_notes/
seam.rs

1//! **The seam** — the notes service as a client of the service it is
2//! mounted beside (V2-1; the media service's `seam.rs` is the pattern). The
3//! running service is built after this activation is, so the activation
4//! holds an empty [`Seam`] the builder fills ([`Seam::attach`]).
5//!
6//! Two questions go through it, never through another service's file:
7//! **may this caller do this to a note of `acme`** — the gate's word,
8//! the method's grant (`notes.save`) asked on the organization's scope
9//! (`acme:`), within the session's ceiling ([`Seam::holds`]); and **which
10//! organizations is it in** — `orgs.list`, asked of the tickets service as
11//! the caller ([`Seam::orgs`]).
12//!
13//! The media service is a client of this one the same way: [`may`] asks
14//! `notes.may` as the caller before it keeps an image for a note.
15//!
16//! NOTES-4: a third — **does this kept version hold this component** —
17//! asked of the ui service before a slot is filled ([`Seam::component`]),
18//! through what the builder attaches ([`Components`]): the ui service's own
19//! store, in the process. The ui service of plexus-ui 0.2.6 answers no wire
20//! method a version's components (`ui.components` resolves the live bundle's
21//! and an author's own); the notes service opens no ui file either way.
22
23use crate::{NotesClient, NotesEvent};
24use futures::TryStreamExt;
25use menger_tickets_api::members::Role;
26use menger_tickets_api::{OrgsClient, OrgsEvent};
27use plexus_rpc::auth_core::grants::Grant;
28use plexus_rpc::core::plexus::{AuthContext, DynamicHub, HubTransport};
29use std::sync::{Arc, OnceLock, Weak};
30
31/// Where the running service is, once the builder says. Weak: the service
32/// owns the activation that holds this.
33#[derive(Clone, Default)]
34pub struct Seam {
35    at: Arc<OnceLock<Weak<DynamicHub>>>,
36    components: Arc<OnceLock<Arc<dyn Components>>>,
37}
38
39/// NOTES-4: what the ui service says of a component of a version.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum Held {
42    /// The version is kept (its whole hash) and holds the component.
43    Holds(String),
44    /// The version is kept (its whole hash) and holds no such component.
45    NoComponent(String),
46    /// The ui service keeps no such version (none, or a prefix naming two).
47    NoVersion,
48}
49
50/// NOTES-4: the ui service's answer to "does `version` hold `component`" —
51/// the builder attaches the running ui service's ([`Seam::attach_components`]).
52pub trait Components: Send + Sync {
53    /// Whether the kept version `version` (a hash, or its first 6 or more
54    /// hex digits) holds `component`. `Err`: the ui store failed, in words.
55    fn holds(&self, version: &str, component: &str) -> Result<Held, String>;
56}
57
58impl std::fmt::Debug for Seam {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.debug_struct("Seam").field("attached", &self.at.get().is_some()).finish()
61    }
62}
63
64/// The grant a role's question about a note is asked as: a viewer
65/// reads (`notes.get`), an editor writes (`notes.save`), an admin deletes
66/// (`notes.delete`). Any other role holds nothing of a note.
67pub fn grant_of(role: Role) -> Option<&'static str> {
68    match role {
69        Role::Viewer => Some("notes.get"),
70        Role::Editor => Some("notes.save"),
71        Role::Admin => Some("notes.delete"),
72        _ => None,
73    }
74}
75
76impl Seam {
77    /// The service this one is registered in; the first attach holds.
78    pub fn attach(&self, service: &Arc<DynamicHub>) {
79        let _ = self.at.set(Arc::downgrade(service));
80    }
81
82    /// NOTES-4: the ui service's word on versions; the first attach holds.
83    pub fn attach_components(&self, components: Arc<dyn Components>) {
84        let _ = self.components.set(components);
85    }
86
87    /// NOTES-4: whether the kept version `version` holds `component`, as the
88    /// ui service says (off the runtime). `Err`: none attached, or it failed.
89    pub async fn component(&self, version: &str, component: &str) -> Result<Held, String> {
90        let ui = self.components.get().cloned().ok_or("the notes service is not attached to the ui service")?;
91        let (version, component) = (version.to_string(), component.to_string());
92        tokio::task::spawn_blocking(move || ui.holds(&version, &component)).await.map_err(|e| format!("the ui service's answer failed: {e}"))?
93    }
94
95    /// The running service, while it runs.
96    pub fn service(&self) -> Option<Arc<DynamicHub>> {
97        self.at.get().and_then(Weak::upgrade)
98    }
99
100    /// Whether `caller` holds `grant` (`notes.save`) on the organization
101    /// `org`, as the gate answers it now — through a role held on `org:`
102    /// or on `*`, within the session's ceiling. A service with no gate
103    /// holds everything open. `Err`: not attached.
104    pub fn holds(&self, caller: &AuthContext, grant: &str, org: &str) -> Result<bool, String> {
105        let service = self.service().ok_or("the notes service is not attached to a running service")?;
106        Ok(match service.gate() {
107            None => true,
108            Some(gate) => gate.check(Some(caller), &Grant::new(grant), Some(&format!("{org}:"))).is_ok(),
109        })
110    }
111
112    /// The organizations `caller` is in, in the order they were made —
113    /// `orgs.list` asked as the caller, the tickets service's word.
114    pub async fn orgs(&self, caller: &AuthContext) -> Result<Vec<String>, String> {
115        let service = self.service().ok_or("the notes service is not attached to a running service")?;
116        let orgs = OrgsClient::new(HubTransport::as_(service, caller.clone()));
117        match orgs.list().try_collect::<Vec<_>>().await {
118            Ok(events) => {
119                let mut out = Vec::new();
120                for e in events {
121                    match e {
122                        OrgsEvent::Org { org } => out.push(org.name.as_str().to_string()),
123                        OrgsEvent::Error { message } => return Err(format!("orgs.list: {message}")),
124                        _ => {}
125                    }
126                }
127                Ok(out)
128            }
129            Err(e) => Err(format!("orgs.list through the seam: {e}")),
130        }
131    }
132}
133
134/// What the notes service answered a `may`.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub enum Answer {
137    /// The caller reads the note and holds the role on it: its id.
138    Held(String),
139    /// The caller reads it and does not hold the role.
140    NotHeld,
141    /// No such note in the caller's reach (not there and not theirs, one answer).
142    NotFound,
143}
144
145/// `notes.may { id, role }` through `service` as `caller` — the media
146/// service's question before it keeps an image for a note, or answers
147/// one. `Err`: the call itself failed, in words.
148pub async fn may(service: Arc<DynamicHub>, caller: AuthContext, id: &str, role: Role) -> Result<Answer, String> {
149    let doc: crate::NoteId = id.parse()?;
150    let notes = NotesClient::new(HubTransport::as_(service, caller));
151    match notes.may(doc, role).try_collect::<Vec<_>>().await {
152        Ok(events) => match events.as_slice() {
153            [NotesEvent::May { id, held: true, .. }] => Ok(Answer::Held(id.clone())),
154            [NotesEvent::May { held: false, .. }] => Ok(Answer::NotHeld),
155            [NotesEvent::NotFound { .. }] => Ok(Answer::NotFound),
156            [NotesEvent::Error { message }] => Err(format!("notes.may: {message}")),
157            other => Err(format!("notes.may answered {other:?}")),
158        },
159        Err(e) => Err(format!("notes.may through the seam: {e}")),
160    }
161}