Skip to main content

link_cli/protocol/
sessions.rs

1//! Sessions of a links server, each with its subject (issue #149).
2//!
3//! [`LinksSessions`] is what a [`LinksServer`](super::LinksServer) gives
4//! every connection, without the network. The C# counterparts are
5//! `LinksSessions` and `LinksSession`.
6
7use std::collections::{HashMap, HashSet};
8use std::panic::{self, AssertUnwindSafe};
9
10use anyhow::Result;
11use links_notation::binary::{format_document, parse_document, LinoDocument};
12use links_notation::LiNo;
13
14use super::links_operations::{Change, LinksOperation};
15use super::server::{error_document, error_message, execute_observed_request, execute_request};
16use super::triplets_operations::{execute_observed_triplets_request, TripletsOperation};
17use crate::changes_simplifier::simplify_changes;
18use crate::link::Link;
19use crate::named_type_links::NamedTypeLinks;
20use crate::permissions::{AccessPolicy, PermissionPolicy, PermissionsDecorator};
21use crate::query_processor::QueryProcessor;
22use crate::triplets::{TripletChange, TripletMarkers, TripletsOverDoublets};
23use crate::undoable_links::UndoableLinksDecorator;
24
25/// The subject of a token, or `None` when the token is not valid: answers
26/// `(auth: token)`.
27///
28/// It is given the store the sessions serve, below any permissions, so a
29/// [`LinksTokenTable`](crate::LinksTokenTable) kept in the data can read it:
30/// `Box::new(|store, token| LinksTokenTable::new(store).authenticate(token))`.
31/// An error fails the authentication.
32pub type Authenticator = Box<dyn FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>>>;
33
34/// A session of a [`LinksSessions`], as [`LinksSessions::open`] returns it.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
36pub struct SessionId(u64);
37
38/// What a session keeps between its requests.
39#[derive(Debug, Default)]
40struct Session {
41    subject: u32,
42    /// The links the subject created, while they are its own.
43    created: HashSet<u32>,
44}
45
46enum Store<S: NamedTypeLinks, P: AccessPolicy> {
47    Plain(S),
48    Permitted(PermissionsDecorator<UndoableLinksDecorator<S>, P>),
49}
50
51/// A store served to many sessions, each with its subject (issue #149).
52///
53/// Without permissions every session sees and changes the whole store,
54/// exactly as before permissions existed. With them
55/// ([`with_permissions`](Self::with_permissions)), a session sees the store
56/// through a [`PermissionsDecorator`] of its subject, and every request is
57/// atomic: one that fails is undone whole, the writes the store made on its
58/// own (cascades, merges) and the names it took included, even where they
59/// touched links the subject cannot see.
60///
61/// `(auth: token)` sets the subject of the session to the one the
62/// [`Authenticator`] gives the token, and answers `(subject: i)`; an unknown
63/// token, or sessions without an authenticator, answer
64/// `(error: 'Forbidden: authentication failed')`.
65///
66/// With [`with_triplets`](Self::with_triplets) the sessions read every request
67/// as triplets (issue #152; see [`TripletsOperation`]), and permissions judge
68/// each triplet as a whole, not the wrappers and pairs that store it.
69///
70/// Requests run one at a time, as `&mut self` already demands.
71pub struct LinksSessions<S: NamedTypeLinks, P: AccessPolicy = PermissionPolicy> {
72    store: Store<S, P>,
73    processor: QueryProcessor,
74    triplets: Option<TripletMarkers>,
75    authenticate: Option<Authenticator>,
76    subject: u32,
77    sessions: HashMap<SessionId, Session>,
78    next: u64,
79}
80
81impl<S: NamedTypeLinks> LinksSessions<S> {
82    /// Sessions that see and change the whole store.
83    pub fn new(store: S) -> Self {
84        Self::of(Store::Plain(store))
85    }
86}
87
88impl<S: NamedTypeLinks, P: AccessPolicy> LinksSessions<S, P> {
89    /// Sessions that see the store as `policy` lets their subjects.
90    pub fn with_permissions(store: S, policy: P) -> Self {
91        Self::of(Store::Permitted(PermissionsDecorator::new(
92            UndoableLinksDecorator::new(store),
93            policy,
94            0,
95        )))
96    }
97
98    fn of(store: Store<S, P>) -> Self {
99        Self {
100            store,
101            processor: QueryProcessor::new(false),
102            triplets: None,
103            authenticate: None,
104            subject: 0,
105            sessions: HashMap::new(),
106            next: 0,
107        }
108    }
109
110    /// Answers `(auth: token)` with `authenticate`.
111    pub fn with_authenticator(
112        mut self,
113        authenticate: impl FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>> + 'static,
114    ) -> Self {
115        self.authenticate = Some(Box::new(authenticate));
116        self
117    }
118
119    /// The subject of a session before any `(auth: token)`; the null link
120    /// (0, the default) is a guest.
121    pub fn with_subject(mut self, subject: u32) -> Self {
122        self.subject = subject;
123        self
124    }
125
126    /// Passed to [`QueryProcessor::with_auto_create_missing_references`].
127    pub fn with_auto_create_missing_references(mut self, enabled: bool) -> Self {
128        self.processor = QueryProcessor::new(false).with_auto_create_missing_references(enabled);
129        self
130    }
131
132    /// Reads every request as triplets; the markers of the encoding are
133    /// created in the store when they are missing, whatever the subject of a
134    /// session may do.
135    pub fn with_triplets(mut self) -> Result<Self> {
136        self.ensure_triplets()?;
137        Ok(self)
138    }
139
140    /// Like [`with_triplets`](Self::with_triplets), on sessions already built.
141    pub fn ensure_triplets(&mut self) -> Result<TripletMarkers> {
142        if let Some(markers) = self.triplets {
143            return Ok(markers);
144        }
145        let markers = TripletMarkers::ensure(self.store_mut())?;
146        self.triplets = Some(markers);
147        Ok(markers)
148    }
149
150    /// Whether the sessions read every request as triplets.
151    pub fn has_triplets(&self) -> bool {
152        self.triplets.is_some()
153    }
154
155    /// Whether the sessions see the store through permissions.
156    pub fn has_permissions(&self) -> bool {
157        matches!(self.store, Store::Permitted(_))
158    }
159
160    /// The store.
161    pub fn store(&self) -> &S {
162        match &self.store {
163            Store::Plain(store) => store,
164            Store::Permitted(view) => view.inner().inner(),
165        }
166    }
167
168    /// The store, to read or write it as no session.
169    pub fn store_mut(&mut self) -> &mut S {
170        match &mut self.store {
171            Store::Plain(store) => store,
172            Store::Permitted(view) => view.inner_mut().inner_mut(),
173        }
174    }
175
176    /// The policy, when there are permissions.
177    pub fn policy(&self) -> Option<&P> {
178        match &self.store {
179            Store::Plain(_) => None,
180            Store::Permitted(view) => Some(view.policy()),
181        }
182    }
183
184    pub fn into_inner(self) -> S {
185        match self.store {
186            Store::Plain(store) => store,
187            Store::Permitted(view) => view.into_inner().into_inner(),
188        }
189    }
190
191    /// Opens a session of `subject`, by default the one of
192    /// [`with_subject`](Self::with_subject).
193    pub fn open(&mut self, subject: Option<u32>) -> SessionId {
194        let id = SessionId(self.next);
195        self.next += 1;
196        self.sessions.insert(
197            id,
198            Session {
199                subject: subject.unwrap_or(self.subject),
200                created: HashSet::new(),
201            },
202        );
203        id
204    }
205
206    /// Closes a session.
207    pub fn close(&mut self, session: SessionId) {
208        self.sessions.remove(&session);
209    }
210
211    /// The sessions that are open.
212    pub fn sessions(&self) -> Vec<SessionId> {
213        let mut sessions: Vec<SessionId> = self.sessions.keys().copied().collect();
214        sessions.sort();
215        sessions
216    }
217
218    /// The subject the requests of `session` run as, while it is open.
219    pub fn subject(&self, session: SessionId) -> Option<u32> {
220        self.sessions.get(&session).map(|session| session.subject)
221    }
222
223    /// The links `session` created, while they are its own.
224    pub fn created(&self, session: SessionId) -> Option<&HashSet<u32>> {
225        self.sessions.get(&session).map(|session| &session.created)
226    }
227
228    /// Answers a request written as LiNo text, as the text protocol does.
229    pub fn request(&mut self, session: SessionId, text: &str) -> String {
230        let reply = match parse_document(text) {
231            Ok(document) => self.execute(session, &document),
232            Err(error) => error_document(&error.to_string()),
233        };
234        format_document(&reply)
235    }
236
237    /// Answers one request document of `session`; a session that is not
238    /// open is opened.
239    pub fn execute(&mut self, session: SessionId, document: &[LiNo<String>]) -> LinoDocument {
240        self.execute_observed(session, document, &mut Vec::new())
241    }
242
243    /// Like [`execute`](Self::execute), adding the net change of every link
244    /// the request changed in the store to `changed`, with plain numbers:
245    /// the cascades and merges a write led to as well, even where the
246    /// subject cannot see them. A request undone for failing changed nothing.
247    pub fn execute_observed(
248        &mut self,
249        session: SessionId,
250        document: &[LiNo<String>],
251        changed: &mut Vec<Change>,
252    ) -> LinoDocument {
253        self.run(session, document, changed, &mut Vec::new())
254    }
255
256    /// Like [`execute`](Self::execute) on sessions that read requests as
257    /// triplets, adding every triplet the request changed to `changed`, with
258    /// plain numbers: those it took along too, even where the subject cannot
259    /// see them. A request undone for failing changed nothing.
260    pub fn execute_triplets_observed(
261        &mut self,
262        session: SessionId,
263        document: &[LiNo<String>],
264        changed: &mut Vec<TripletChange>,
265    ) -> LinoDocument {
266        self.run(session, document, &mut Vec::new(), changed)
267    }
268
269    fn run(
270        &mut self,
271        session: SessionId,
272        document: &[LiNo<String>],
273        changed: &mut Vec<Change>,
274        triplets_changed: &mut Vec<TripletChange>,
275    ) -> LinoDocument {
276        let mut state = self.sessions.remove(&session).unwrap_or(Session {
277            subject: self.subject,
278            created: HashSet::new(),
279        });
280        let reply = self.execute_as(&mut state, document, changed, triplets_changed);
281        self.sessions.insert(session, state);
282        reply
283    }
284
285    /// Whether the subject of `session` may read `link`: always, without
286    /// permissions; a session that is not open is a guest.
287    pub fn can_read(&mut self, session: SessionId, link: &Link) -> bool {
288        let view = match &mut self.store {
289            Store::Plain(_) => return true,
290            Store::Permitted(view) => view,
291        };
292        let (subject, created) = match self.sessions.get_mut(&session) {
293            Some(state) => (state.subject, std::mem::take(&mut state.created)),
294            None => (self.subject, HashSet::new()),
295        };
296        view.set_subject(subject);
297        let created = view.replace_created(created);
298        let readable = if self.triplets.is_some() {
299            view.can_read_triplet(link)
300        } else {
301            view.can_read(link)
302        };
303        let created = view.replace_created(created);
304        if let Some(state) = self.sessions.get_mut(&session) {
305            state.created = created;
306        }
307        readable
308    }
309
310    fn execute_as(
311        &mut self,
312        session: &mut Session,
313        document: &[LiNo<String>],
314        changed: &mut Vec<Change>,
315        triplets_changed: &mut Vec<TripletChange>,
316    ) -> LinoDocument {
317        if let [LiNo::Link {
318            id: Some(id),
319            values,
320        }] = document
321        {
322            if id == "auth" {
323                return self.authenticate(session, values);
324            }
325        }
326        let markers = self.triplets;
327        let view = match &mut self.store {
328            Store::Plain(store) => {
329                return match markers {
330                    Some(markers) => execute_observed_triplets_request(
331                        &mut TripletsOverDoublets::with_markers(store, markers),
332                        document,
333                        triplets_changed,
334                    ),
335                    None => execute_observed_request(store, &self.processor, document, changed),
336                };
337            }
338            Store::Permitted(view) => view,
339        };
340        view.set_subject(session.subject);
341        view.replace_created(std::mem::take(&mut session.created));
342        view.inner_mut().begin();
343        let processor = &self.processor;
344        let observed = triplets_changed.len();
345        let outcome = panic::catch_unwind(AssertUnwindSafe(|| match markers {
346            Some(markers) => triplets_request(view, markers, document, triplets_changed),
347            None => request(view, document, |view, document| {
348                execute_request(view, processor, document)
349            }),
350        }));
351        let reply = match outcome {
352            Ok(reply) if error_message(&reply).is_none() => {
353                let deleted: HashSet<u32> = view
354                    .inner()
355                    .log()
356                    .changes()
357                    .iter()
358                    .filter_map(|change| match change {
359                        (Some(before), None) => Some(before.index),
360                        _ => None,
361                    })
362                    .collect();
363                let changes = view
364                    .inner()
365                    .log()
366                    .changes()
367                    .iter()
368                    .map(|(before, after)| {
369                        (
370                            before.unwrap_or_else(Link::null),
371                            after.unwrap_or_else(Link::null),
372                        )
373                    })
374                    .collect();
375                changed.extend(
376                    simplify_changes(changes)
377                        .into_iter()
378                        .filter(|(before, after)| before != after),
379                );
380                view.inner_mut().commit();
381                // The links are gone: no other session owns them any more.
382                for other in self.sessions.values_mut() {
383                    other.created.retain(|index| !deleted.contains(index));
384                }
385                reply
386            }
387            Ok(reply) => {
388                triplets_changed.truncate(observed);
389                match undo(view) {
390                    Ok(()) => reply,
391                    Err(error) => error_document(&format!(
392                        "{}; undoing it failed: {error:#}",
393                        error_message(&reply).unwrap_or_default()
394                    )),
395                }
396            }
397            Err(panicked) => {
398                let _ = undo(view);
399                session.created = view.replace_created(HashSet::new());
400                panic::resume_unwind(panicked);
401            }
402        };
403        session.created = view.replace_created(HashSet::new());
404        reply
405    }
406
407    fn authenticate(&mut self, session: &mut Session, values: &[LiNo<String>]) -> LinoDocument {
408        let found = match (values, self.authenticate.as_mut()) {
409            ([LiNo::Ref(token)], Some(authenticate)) => {
410                let store: &mut dyn NamedTypeLinks = match &mut self.store {
411                    Store::Plain(store) => store,
412                    Store::Permitted(view) => view.inner_mut().inner_mut(),
413                };
414                authenticate(store, token).ok().flatten()
415            }
416            _ => None,
417        };
418        match found {
419            Some(subject) => {
420                session.subject = subject;
421                vec![LiNo::Link {
422                    id: Some("subject".to_string()),
423                    values: vec![LiNo::Ref(subject.to_string())],
424                }]
425            }
426            None => error_document("Forbidden: authentication failed"),
427        }
428    }
429}
430
431/// Undoes the request, and forgets the links it created.
432fn undo<S: NamedTypeLinks, P: AccessPolicy>(
433    view: &mut PermissionsDecorator<UndoableLinksDecorator<S>, P>,
434) -> Result<()> {
435    for created in view.inner_mut().rollback()? {
436        view.forget(created);
437    }
438    Ok(())
439}
440
441/// A request as the subject sees the store: names of links it cannot read
442/// are not found, and `run` answers everything else.
443fn request<L: NamedTypeLinks, P: AccessPolicy>(
444    view: &mut PermissionsDecorator<L, P>,
445    document: &[LiNo<String>],
446    run: impl FnOnce(&mut PermissionsDecorator<L, P>, &[LiNo<String>]) -> LinoDocument,
447) -> LinoDocument {
448    let operation = match LinksOperation::from_document(document) {
449        Ok(operation) => operation,
450        Err(error) => return error_document(&error.to_string()),
451    };
452    match operation {
453        Some(LinksOperation::GetName(link)) if !view.exists(link) => Vec::new(),
454        Some(LinksOperation::GetByName(name)) => match view.get_by_name(&name) {
455            Ok(Some(link)) if link != 0 && view.exists(link) => run(view, document),
456            Ok(_) => Vec::new(),
457            Err(error) => error_document(&format!("{error:#}")),
458        },
459        _ => run(view, document),
460    }
461}
462
463/// A request over triplets as the subject sees the store: the permissions move
464/// above the triplets, which write their wrappers and pairs straight to the
465/// store below, still inside the transaction of the request.
466fn triplets_request<S: NamedTypeLinks, P: AccessPolicy>(
467    view: &mut PermissionsDecorator<UndoableLinksDecorator<S>, P>,
468    markers: TripletMarkers,
469    document: &[LiNo<String>],
470    changed: &mut Vec<TripletChange>,
471) -> LinoDocument {
472    let subject = view.subject();
473    let created = view.replace_created(HashSet::new());
474    let (links, policy) = view.parts_mut();
475    let mut layer = PermissionsDecorator::new(
476        TripletsOverDoublets::with_markers(links, markers),
477        policy,
478        subject,
479    )
480    .with_created(created);
481    // A triplet operation holds four parts where one over doublets holds three:
482    // only what is left, the names, is for `request` to look at.
483    let reply = if matches!(TripletsOperation::from_document(document), Ok(None)) {
484        request(&mut layer, document, |layer, document| {
485            execute_observed_triplets_request(layer, document, changed)
486        })
487    } else {
488        execute_observed_triplets_request(&mut layer, document, changed)
489    };
490    let created = layer.replace_created(HashSet::new());
491    view.replace_created(created);
492    reply
493}