1use 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 crate::changes_simplifier::simplify_changes;
17use crate::link::Link;
18use crate::named_type_links::NamedTypeLinks;
19use crate::permissions::{AccessPolicy, PermissionPolicy, PermissionsDecorator};
20use crate::query_processor::QueryProcessor;
21use crate::undoable_links::UndoableLinksDecorator;
22
23pub type Authenticator = Box<dyn FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>>>;
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct SessionId(u64);
35
36#[derive(Debug, Default)]
38struct Session {
39 subject: u32,
40 created: HashSet<u32>,
42}
43
44enum Store<S: NamedTypeLinks, P: AccessPolicy> {
45 Plain(S),
46 Permitted(PermissionsDecorator<UndoableLinksDecorator<S>, P>),
47}
48
49pub struct LinksSessions<S: NamedTypeLinks, P: AccessPolicy = PermissionPolicy> {
66 store: Store<S, P>,
67 processor: QueryProcessor,
68 authenticate: Option<Authenticator>,
69 subject: u32,
70 sessions: HashMap<SessionId, Session>,
71 next: u64,
72}
73
74impl<S: NamedTypeLinks> LinksSessions<S> {
75 pub fn new(store: S) -> Self {
77 Self::of(Store::Plain(store))
78 }
79}
80
81impl<S: NamedTypeLinks, P: AccessPolicy> LinksSessions<S, P> {
82 pub fn with_permissions(store: S, policy: P) -> Self {
84 Self::of(Store::Permitted(PermissionsDecorator::new(
85 UndoableLinksDecorator::new(store),
86 policy,
87 0,
88 )))
89 }
90
91 fn of(store: Store<S, P>) -> Self {
92 Self {
93 store,
94 processor: QueryProcessor::new(false),
95 authenticate: None,
96 subject: 0,
97 sessions: HashMap::new(),
98 next: 0,
99 }
100 }
101
102 pub fn with_authenticator(
104 mut self,
105 authenticate: impl FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>> + 'static,
106 ) -> Self {
107 self.authenticate = Some(Box::new(authenticate));
108 self
109 }
110
111 pub fn with_subject(mut self, subject: u32) -> Self {
114 self.subject = subject;
115 self
116 }
117
118 pub fn with_auto_create_missing_references(mut self, enabled: bool) -> Self {
120 self.processor = QueryProcessor::new(false).with_auto_create_missing_references(enabled);
121 self
122 }
123
124 pub fn has_permissions(&self) -> bool {
126 matches!(self.store, Store::Permitted(_))
127 }
128
129 pub fn store(&self) -> &S {
131 match &self.store {
132 Store::Plain(store) => store,
133 Store::Permitted(view) => view.inner().inner(),
134 }
135 }
136
137 pub fn store_mut(&mut self) -> &mut S {
139 match &mut self.store {
140 Store::Plain(store) => store,
141 Store::Permitted(view) => view.inner_mut().inner_mut(),
142 }
143 }
144
145 pub fn policy(&self) -> Option<&P> {
147 match &self.store {
148 Store::Plain(_) => None,
149 Store::Permitted(view) => Some(view.policy()),
150 }
151 }
152
153 pub fn into_inner(self) -> S {
154 match self.store {
155 Store::Plain(store) => store,
156 Store::Permitted(view) => view.into_inner().into_inner(),
157 }
158 }
159
160 pub fn open(&mut self, subject: Option<u32>) -> SessionId {
163 let id = SessionId(self.next);
164 self.next += 1;
165 self.sessions.insert(
166 id,
167 Session {
168 subject: subject.unwrap_or(self.subject),
169 created: HashSet::new(),
170 },
171 );
172 id
173 }
174
175 pub fn close(&mut self, session: SessionId) {
177 self.sessions.remove(&session);
178 }
179
180 pub fn sessions(&self) -> Vec<SessionId> {
182 let mut sessions: Vec<SessionId> = self.sessions.keys().copied().collect();
183 sessions.sort();
184 sessions
185 }
186
187 pub fn subject(&self, session: SessionId) -> Option<u32> {
189 self.sessions.get(&session).map(|session| session.subject)
190 }
191
192 pub fn created(&self, session: SessionId) -> Option<&HashSet<u32>> {
194 self.sessions.get(&session).map(|session| &session.created)
195 }
196
197 pub fn request(&mut self, session: SessionId, text: &str) -> String {
199 let reply = match parse_document(text) {
200 Ok(document) => self.execute(session, &document),
201 Err(error) => error_document(&error.to_string()),
202 };
203 format_document(&reply)
204 }
205
206 pub fn execute(&mut self, session: SessionId, document: &[LiNo<String>]) -> LinoDocument {
209 self.execute_observed(session, document, &mut Vec::new())
210 }
211
212 pub fn execute_observed(
217 &mut self,
218 session: SessionId,
219 document: &[LiNo<String>],
220 changed: &mut Vec<Change>,
221 ) -> LinoDocument {
222 let mut state = self.sessions.remove(&session).unwrap_or(Session {
223 subject: self.subject,
224 created: HashSet::new(),
225 });
226 let reply = self.execute_as(&mut state, document, changed);
227 self.sessions.insert(session, state);
228 reply
229 }
230
231 pub fn can_read(&mut self, session: SessionId, link: &Link) -> bool {
234 let view = match &mut self.store {
235 Store::Plain(_) => return true,
236 Store::Permitted(view) => view,
237 };
238 let (subject, created) = match self.sessions.get_mut(&session) {
239 Some(state) => (state.subject, std::mem::take(&mut state.created)),
240 None => (self.subject, HashSet::new()),
241 };
242 view.set_subject(subject);
243 let created = view.replace_created(created);
244 let readable = view.can_read(link);
245 let created = view.replace_created(created);
246 if let Some(state) = self.sessions.get_mut(&session) {
247 state.created = created;
248 }
249 readable
250 }
251
252 fn execute_as(
253 &mut self,
254 session: &mut Session,
255 document: &[LiNo<String>],
256 changed: &mut Vec<Change>,
257 ) -> LinoDocument {
258 if let [LiNo::Link {
259 id: Some(id),
260 values,
261 }] = document
262 {
263 if id == "auth" {
264 return self.authenticate(session, values);
265 }
266 }
267 let view = match &mut self.store {
268 Store::Plain(store) => {
269 return execute_observed_request(store, &self.processor, document, changed)
270 }
271 Store::Permitted(view) => view,
272 };
273 view.set_subject(session.subject);
274 view.replace_created(std::mem::take(&mut session.created));
275 view.inner_mut().begin();
276 let processor = &self.processor;
277 let outcome = panic::catch_unwind(AssertUnwindSafe(|| request(view, processor, document)));
278 let reply = match outcome {
279 Ok(reply) if error_message(&reply).is_none() => {
280 let deleted: HashSet<u32> = view
281 .inner()
282 .log()
283 .changes()
284 .iter()
285 .filter_map(|change| match change {
286 (Some(before), None) => Some(before.index),
287 _ => None,
288 })
289 .collect();
290 let changes = view
291 .inner()
292 .log()
293 .changes()
294 .iter()
295 .map(|(before, after)| {
296 (
297 before.unwrap_or_else(Link::null),
298 after.unwrap_or_else(Link::null),
299 )
300 })
301 .collect();
302 changed.extend(
303 simplify_changes(changes)
304 .into_iter()
305 .filter(|(before, after)| before != after),
306 );
307 view.inner_mut().commit();
308 for other in self.sessions.values_mut() {
310 other.created.retain(|index| !deleted.contains(index));
311 }
312 reply
313 }
314 Ok(reply) => match undo(view) {
315 Ok(()) => reply,
316 Err(error) => error_document(&format!(
317 "{}; undoing it failed: {error:#}",
318 error_message(&reply).unwrap_or_default()
319 )),
320 },
321 Err(panicked) => {
322 let _ = undo(view);
323 session.created = view.replace_created(HashSet::new());
324 panic::resume_unwind(panicked);
325 }
326 };
327 session.created = view.replace_created(HashSet::new());
328 reply
329 }
330
331 fn authenticate(&mut self, session: &mut Session, values: &[LiNo<String>]) -> LinoDocument {
332 let found = match (values, self.authenticate.as_mut()) {
333 ([LiNo::Ref(token)], Some(authenticate)) => {
334 let store: &mut dyn NamedTypeLinks = match &mut self.store {
335 Store::Plain(store) => store,
336 Store::Permitted(view) => view.inner_mut().inner_mut(),
337 };
338 authenticate(store, token).ok().flatten()
339 }
340 _ => None,
341 };
342 match found {
343 Some(subject) => {
344 session.subject = subject;
345 vec![LiNo::Link {
346 id: Some("subject".to_string()),
347 values: vec![LiNo::Ref(subject.to_string())],
348 }]
349 }
350 None => error_document("Forbidden: authentication failed"),
351 }
352 }
353}
354
355fn undo<S: NamedTypeLinks, P: AccessPolicy>(
357 view: &mut PermissionsDecorator<UndoableLinksDecorator<S>, P>,
358) -> Result<()> {
359 for created in view.inner_mut().rollback()? {
360 view.forget(created);
361 }
362 Ok(())
363}
364
365fn request<L: NamedTypeLinks, P: AccessPolicy>(
368 view: &mut PermissionsDecorator<L, P>,
369 processor: &QueryProcessor,
370 document: &[LiNo<String>],
371) -> LinoDocument {
372 let operation = match LinksOperation::from_document(document) {
373 Ok(operation) => operation,
374 Err(error) => return error_document(&error.to_string()),
375 };
376 match operation {
377 Some(LinksOperation::GetName(link)) if !view.exists(link) => Vec::new(),
378 Some(LinksOperation::GetByName(name)) => match view.get_by_name(&name) {
379 Ok(Some(link)) if link != 0 && view.exists(link) => {
380 execute_request(view, processor, document)
381 }
382 Ok(_) => Vec::new(),
383 Err(error) => error_document(&format!("{error:#}")),
384 },
385 _ => execute_request(view, processor, document),
386 }
387}