use std::collections::{HashMap, HashSet};
use std::panic::{self, AssertUnwindSafe};
use anyhow::Result;
use links_notation::binary::{format_document, parse_document, LinoDocument};
use links_notation::LiNo;
use super::links_operations::{Change, LinksOperation};
use super::server::{error_document, error_message, execute_observed_request, execute_request};
use super::triplets_operations::{execute_observed_triplets_request, TripletsOperation};
use crate::changes_simplifier::simplify_changes;
use crate::link::Link;
use crate::named_type_links::NamedTypeLinks;
use crate::permissions::{AccessPolicy, PermissionPolicy, PermissionsDecorator};
use crate::query_processor::QueryProcessor;
use crate::triplets::{TripletChange, TripletMarkers, TripletsOverDoublets};
use crate::undoable_links::UndoableLinksDecorator;
pub type Authenticator = Box<dyn FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>>>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SessionId(u64);
#[derive(Debug, Default)]
struct Session {
subject: u32,
created: HashSet<u32>,
}
enum Store<S: NamedTypeLinks, P: AccessPolicy> {
Plain(S),
Permitted(PermissionsDecorator<UndoableLinksDecorator<S>, P>),
}
pub struct LinksSessions<S: NamedTypeLinks, P: AccessPolicy = PermissionPolicy> {
store: Store<S, P>,
processor: QueryProcessor,
triplets: Option<TripletMarkers>,
authenticate: Option<Authenticator>,
subject: u32,
sessions: HashMap<SessionId, Session>,
next: u64,
}
impl<S: NamedTypeLinks> LinksSessions<S> {
pub fn new(store: S) -> Self {
Self::of(Store::Plain(store))
}
}
impl<S: NamedTypeLinks, P: AccessPolicy> LinksSessions<S, P> {
pub fn with_permissions(store: S, policy: P) -> Self {
Self::of(Store::Permitted(PermissionsDecorator::new(
UndoableLinksDecorator::new(store),
policy,
0,
)))
}
fn of(store: Store<S, P>) -> Self {
Self {
store,
processor: QueryProcessor::new(false),
triplets: None,
authenticate: None,
subject: 0,
sessions: HashMap::new(),
next: 0,
}
}
pub fn with_authenticator(
mut self,
authenticate: impl FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>> + 'static,
) -> Self {
self.authenticate = Some(Box::new(authenticate));
self
}
pub fn with_subject(mut self, subject: u32) -> Self {
self.subject = subject;
self
}
pub fn with_auto_create_missing_references(mut self, enabled: bool) -> Self {
self.processor = QueryProcessor::new(false).with_auto_create_missing_references(enabled);
self
}
pub fn with_triplets(mut self) -> Result<Self> {
self.ensure_triplets()?;
Ok(self)
}
pub fn ensure_triplets(&mut self) -> Result<TripletMarkers> {
if let Some(markers) = self.triplets {
return Ok(markers);
}
let markers = TripletMarkers::ensure(self.store_mut())?;
self.triplets = Some(markers);
Ok(markers)
}
pub fn has_triplets(&self) -> bool {
self.triplets.is_some()
}
pub fn has_permissions(&self) -> bool {
matches!(self.store, Store::Permitted(_))
}
pub fn store(&self) -> &S {
match &self.store {
Store::Plain(store) => store,
Store::Permitted(view) => view.inner().inner(),
}
}
pub fn store_mut(&mut self) -> &mut S {
match &mut self.store {
Store::Plain(store) => store,
Store::Permitted(view) => view.inner_mut().inner_mut(),
}
}
pub fn policy(&self) -> Option<&P> {
match &self.store {
Store::Plain(_) => None,
Store::Permitted(view) => Some(view.policy()),
}
}
pub fn into_inner(self) -> S {
match self.store {
Store::Plain(store) => store,
Store::Permitted(view) => view.into_inner().into_inner(),
}
}
pub fn open(&mut self, subject: Option<u32>) -> SessionId {
let id = SessionId(self.next);
self.next += 1;
self.sessions.insert(
id,
Session {
subject: subject.unwrap_or(self.subject),
created: HashSet::new(),
},
);
id
}
pub fn close(&mut self, session: SessionId) {
self.sessions.remove(&session);
}
pub fn sessions(&self) -> Vec<SessionId> {
let mut sessions: Vec<SessionId> = self.sessions.keys().copied().collect();
sessions.sort();
sessions
}
pub fn subject(&self, session: SessionId) -> Option<u32> {
self.sessions.get(&session).map(|session| session.subject)
}
pub fn created(&self, session: SessionId) -> Option<&HashSet<u32>> {
self.sessions.get(&session).map(|session| &session.created)
}
pub fn request(&mut self, session: SessionId, text: &str) -> String {
let reply = match parse_document(text) {
Ok(document) => self.execute(session, &document),
Err(error) => error_document(&error.to_string()),
};
format_document(&reply)
}
pub fn execute(&mut self, session: SessionId, document: &[LiNo<String>]) -> LinoDocument {
self.execute_observed(session, document, &mut Vec::new())
}
pub fn execute_observed(
&mut self,
session: SessionId,
document: &[LiNo<String>],
changed: &mut Vec<Change>,
) -> LinoDocument {
self.run(session, document, changed, &mut Vec::new())
}
pub fn execute_triplets_observed(
&mut self,
session: SessionId,
document: &[LiNo<String>],
changed: &mut Vec<TripletChange>,
) -> LinoDocument {
self.run(session, document, &mut Vec::new(), changed)
}
fn run(
&mut self,
session: SessionId,
document: &[LiNo<String>],
changed: &mut Vec<Change>,
triplets_changed: &mut Vec<TripletChange>,
) -> LinoDocument {
let mut state = self.sessions.remove(&session).unwrap_or(Session {
subject: self.subject,
created: HashSet::new(),
});
let reply = self.execute_as(&mut state, document, changed, triplets_changed);
self.sessions.insert(session, state);
reply
}
pub fn can_read(&mut self, session: SessionId, link: &Link) -> bool {
let view = match &mut self.store {
Store::Plain(_) => return true,
Store::Permitted(view) => view,
};
let (subject, created) = match self.sessions.get_mut(&session) {
Some(state) => (state.subject, std::mem::take(&mut state.created)),
None => (self.subject, HashSet::new()),
};
view.set_subject(subject);
let created = view.replace_created(created);
let readable = if self.triplets.is_some() {
view.can_read_triplet(link)
} else {
view.can_read(link)
};
let created = view.replace_created(created);
if let Some(state) = self.sessions.get_mut(&session) {
state.created = created;
}
readable
}
fn execute_as(
&mut self,
session: &mut Session,
document: &[LiNo<String>],
changed: &mut Vec<Change>,
triplets_changed: &mut Vec<TripletChange>,
) -> LinoDocument {
if let [LiNo::Link {
id: Some(id),
values,
}] = document
{
if id == "auth" {
return self.authenticate(session, values);
}
}
let markers = self.triplets;
let view = match &mut self.store {
Store::Plain(store) => {
return match markers {
Some(markers) => execute_observed_triplets_request(
&mut TripletsOverDoublets::with_markers(store, markers),
document,
triplets_changed,
),
None => execute_observed_request(store, &self.processor, document, changed),
};
}
Store::Permitted(view) => view,
};
view.set_subject(session.subject);
view.replace_created(std::mem::take(&mut session.created));
view.inner_mut().begin();
let processor = &self.processor;
let observed = triplets_changed.len();
let outcome = panic::catch_unwind(AssertUnwindSafe(|| match markers {
Some(markers) => triplets_request(view, markers, document, triplets_changed),
None => request(view, document, |view, document| {
execute_request(view, processor, document)
}),
}));
let reply = match outcome {
Ok(reply) if error_message(&reply).is_none() => {
let deleted: HashSet<u32> = view
.inner()
.log()
.changes()
.iter()
.filter_map(|change| match change {
(Some(before), None) => Some(before.index),
_ => None,
})
.collect();
let changes = view
.inner()
.log()
.changes()
.iter()
.map(|(before, after)| {
(
before.unwrap_or_else(Link::null),
after.unwrap_or_else(Link::null),
)
})
.collect();
changed.extend(
simplify_changes(changes)
.into_iter()
.filter(|(before, after)| before != after),
);
view.inner_mut().commit();
for other in self.sessions.values_mut() {
other.created.retain(|index| !deleted.contains(index));
}
reply
}
Ok(reply) => {
triplets_changed.truncate(observed);
match undo(view) {
Ok(()) => reply,
Err(error) => error_document(&format!(
"{}; undoing it failed: {error:#}",
error_message(&reply).unwrap_or_default()
)),
}
}
Err(panicked) => {
let _ = undo(view);
session.created = view.replace_created(HashSet::new());
panic::resume_unwind(panicked);
}
};
session.created = view.replace_created(HashSet::new());
reply
}
fn authenticate(&mut self, session: &mut Session, values: &[LiNo<String>]) -> LinoDocument {
let found = match (values, self.authenticate.as_mut()) {
([LiNo::Ref(token)], Some(authenticate)) => {
let store: &mut dyn NamedTypeLinks = match &mut self.store {
Store::Plain(store) => store,
Store::Permitted(view) => view.inner_mut().inner_mut(),
};
authenticate(store, token).ok().flatten()
}
_ => None,
};
match found {
Some(subject) => {
session.subject = subject;
vec![LiNo::Link {
id: Some("subject".to_string()),
values: vec![LiNo::Ref(subject.to_string())],
}]
}
None => error_document("Forbidden: authentication failed"),
}
}
}
fn undo<S: NamedTypeLinks, P: AccessPolicy>(
view: &mut PermissionsDecorator<UndoableLinksDecorator<S>, P>,
) -> Result<()> {
for created in view.inner_mut().rollback()? {
view.forget(created);
}
Ok(())
}
fn request<L: NamedTypeLinks, P: AccessPolicy>(
view: &mut PermissionsDecorator<L, P>,
document: &[LiNo<String>],
run: impl FnOnce(&mut PermissionsDecorator<L, P>, &[LiNo<String>]) -> LinoDocument,
) -> LinoDocument {
let operation = match LinksOperation::from_document(document) {
Ok(operation) => operation,
Err(error) => return error_document(&error.to_string()),
};
match operation {
Some(LinksOperation::GetName(link)) if !view.exists(link) => Vec::new(),
Some(LinksOperation::GetByName(name)) => match view.get_by_name(&name) {
Ok(Some(link)) if link != 0 && view.exists(link) => run(view, document),
Ok(_) => Vec::new(),
Err(error) => error_document(&format!("{error:#}")),
},
_ => run(view, document),
}
}
fn triplets_request<S: NamedTypeLinks, P: AccessPolicy>(
view: &mut PermissionsDecorator<UndoableLinksDecorator<S>, P>,
markers: TripletMarkers,
document: &[LiNo<String>],
changed: &mut Vec<TripletChange>,
) -> LinoDocument {
let subject = view.subject();
let created = view.replace_created(HashSet::new());
let (links, policy) = view.parts_mut();
let mut layer = PermissionsDecorator::new(
TripletsOverDoublets::with_markers(links, markers),
policy,
subject,
)
.with_created(created);
let reply = if matches!(TripletsOperation::from_document(document), Ok(None)) {
request(&mut layer, document, |layer, document| {
execute_observed_triplets_request(layer, document, changed)
})
} else {
execute_observed_triplets_request(&mut layer, document, changed)
};
let created = layer.replace_created(HashSet::new());
view.replace_created(created);
reply
}