1use super::error::ProtocolResult;
25use super::links_operations::{
26 matches, notification_document, parse_changes_for, subscription_document, Change,
27 GenericLinksOperation, LinksOperation, Part,
28};
29use super::protocols::{read_any_document_with_query_limits, MessageFormat, ProtocolLimits};
30use super::sessions::{LinksSessions, SessionId};
31use super::triplets_operations::{
32 matches_triplet, pack_triplets, triplet_notification_document, TripletsOperation,
33};
34use crate::link::{GenericLink, Link};
35use crate::named_type_links::NamedTypeLinks;
36use crate::permissions::AccessPolicy;
37use crate::query_address::QueryAddress;
38use crate::query_options::QueryLimits;
39use crate::query_processor::{GenericQueryProcessor, QueryProcessor};
40use crate::query_reply_budget::QueryReplyBudget;
41use crate::triplets::{Triplet, TripletChange};
42use links_notation::binary::{format_document, LinoDocument};
43use links_notation::LiNo;
44use std::collections::{BTreeMap, VecDeque};
45use std::fmt;
46use std::io::{self, BufReader, BufWriter, Write};
47use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
48use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
49use std::sync::mpsc::{self, Receiver, Sender};
50use std::sync::{Arc, Condvar, Mutex, MutexGuard};
51use std::thread;
52
53#[path = "server_query.rs"]
54mod query;
55pub(super) use query::admit_document;
56pub(super) use query::{execute_observed_request, reference_name};
57pub use query::{execute_request, execute_request_for, parse_document_with_limits, query_document};
58
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub enum AcceptedProtocols {
62 #[default]
64 Any,
65 Text,
67 Binary,
69}
70
71impl AcceptedProtocols {
72 fn accepts(self, format: MessageFormat) -> bool {
73 matches!(
74 (self, format),
75 (AcceptedProtocols::Any, _)
76 | (AcceptedProtocols::Text, MessageFormat::Text)
77 | (AcceptedProtocols::Binary, MessageFormat::Binary(_))
78 )
79 }
80}
81
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct ServerOptions {
85 pub trace: bool,
87 pub auto_create_missing_references: bool,
89 pub accept: AcceptedProtocols,
91 pub limits: ProtocolLimits,
93 pub max_pending_notifications: usize,
96 pub triplets: bool,
100}
101
102pub const DEFAULT_MAX_PENDING_NOTIFICATIONS: usize = 1024;
104
105impl Default for ServerOptions {
106 fn default() -> Self {
107 Self {
108 trace: false,
109 auto_create_missing_references: false,
110 accept: AcceptedProtocols::default(),
111 limits: ProtocolLimits::default(),
112 max_pending_notifications: DEFAULT_MAX_PENDING_NOTIFICATIONS,
113 triplets: false,
114 }
115 }
116}
117
118pub type Readable = Box<dyn Fn(&Link) -> bool + Send>;
120
121enum Job {
122 Request {
125 connection: u64,
126 outbox: Arc<Outbox>,
127 document: LinoDocument,
128 format: MessageFormat,
129 done: Sender<()>,
130 },
131 Close(u64),
133 Shutdown,
134}
135
136#[derive(Clone, Debug)]
138pub struct ShutdownHandle {
139 jobs: Sender<Job>,
140 stopping: Arc<AtomicBool>,
141 address: SocketAddr,
142}
143
144impl ShutdownHandle {
145 pub fn shutdown(&self) {
147 self.stopping.store(true, Ordering::SeqCst);
148 let _ = self.jobs.send(Job::Shutdown);
149 let _ = TcpStream::connect(self.address);
151 }
152}
153
154pub struct LinksServer {
156 listener: TcpListener,
157 options: ServerOptions,
158 readable: Option<Readable>,
159 jobs: Sender<Job>,
160 queue: Receiver<Job>,
161 stopping: Arc<AtomicBool>,
162}
163
164impl fmt::Debug for LinksServer {
165 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
166 formatter
167 .debug_struct("LinksServer")
168 .field("listener", &self.listener)
169 .field("options", &self.options)
170 .field("readable", &self.readable.is_some())
171 .finish_non_exhaustive()
172 }
173}
174
175impl LinksServer {
176 pub fn bind(address: impl ToSocketAddrs, options: ServerOptions) -> ProtocolResult<Self> {
178 let listener = TcpListener::bind(address)?;
179 let (jobs, queue) = mpsc::channel();
180 Ok(Self {
181 listener,
182 options,
183 readable: None,
184 jobs,
185 queue,
186 stopping: Arc::new(AtomicBool::new(false)),
187 })
188 }
189
190 pub fn with_readable(mut self, readable: impl Fn(&Link) -> bool + Send + 'static) -> Self {
199 self.readable = Some(Box::new(readable));
200 self
201 }
202
203 pub fn local_addr(&self) -> ProtocolResult<SocketAddr> {
205 Ok(self.listener.local_addr()?)
206 }
207
208 pub fn shutdown_handle(&self) -> ProtocolResult<ShutdownHandle> {
210 Ok(ShutdownHandle {
211 jobs: self.jobs.clone(),
212 stopping: Arc::clone(&self.stopping),
213 address: self.local_addr()?,
214 })
215 }
216
217 pub fn serve<S: NamedTypeLinks>(self, storage: &mut S) -> ProtocolResult<()> {
220 let auto_create = self.options.auto_create_missing_references;
221 let mut sessions =
222 LinksSessions::new(storage).with_auto_create_missing_references(auto_create);
223 self.serve_sessions(&mut sessions)
224 }
225
226 pub fn serve_for<T: QueryAddress, S: NamedTypeLinks<T>>(
229 self,
230 storage: &mut S,
231 ) -> ProtocolResult<()> {
232 let LinksServer {
233 listener,
234 options,
235 readable: _,
236 jobs,
237 queue,
238 stopping,
239 } = self;
240 let query_limits = storage.query_limits();
241 let acceptor = {
242 let stopping = Arc::clone(&stopping);
243 thread::spawn(move || accept_loop(listener, jobs, stopping, options, query_limits))
244 };
245 let processor = GenericQueryProcessor::<T>::new(false)
246 .with_auto_create_missing_references(options.auto_create_missing_references);
247 while let Ok(job) = queue.recv() {
248 match job {
249 Job::Shutdown => break,
250 Job::Close(_) => {}
251 Job::Request {
252 document,
253 outbox,
254 format,
255 done,
256 ..
257 } => {
258 if options.trace
259 && storage
260 .query_limits()
261 .is_none_or(|limits| admit_document(&document, limits).is_ok())
262 {
263 crate::diagnostics::stderr!(
264 "[server] request: {}",
265 format_document(&document)
266 );
267 }
268 let response = execute_request_for(storage, &processor, &document);
269 if options.trace {
270 crate::diagnostics::stderr!(
271 "[server] reply: {}",
272 format_document(&response)
273 );
274 }
275 outbox.reply(response, format);
276 let _ = done.send(());
277 }
278 }
279 }
280 stopping.store(true, Ordering::SeqCst);
281 drop(queue);
282 let _ = acceptor.join();
283 Ok(())
284 }
285
286 pub fn serve_sessions<S: NamedTypeLinks, P: AccessPolicy>(
290 self,
291 sessions: &mut LinksSessions<S, P>,
292 ) -> ProtocolResult<()> {
293 let LinksServer {
294 listener,
295 options,
296 readable,
297 jobs,
298 queue,
299 stopping,
300 } = self;
301 if options.triplets {
302 sessions
303 .ensure_triplets()
304 .map_err(|error| io::Error::other(format!("{error:#}")))?;
305 }
306 let query_limits = sessions.store().query_limits();
307 let acceptor = {
308 let stopping = Arc::clone(&stopping);
309 thread::spawn(move || accept_loop(listener, jobs, stopping, options, query_limits))
310 };
311 let mut dispatcher = Dispatcher::new(options, readable);
312 while let Ok(job) = queue.recv() {
313 if !dispatcher.run(sessions, job) {
314 break;
315 }
316 }
317 dispatcher.close_all(sessions);
318 stopping.store(true, Ordering::SeqCst);
319 drop(queue);
320 let _ = acceptor.join();
321 Ok(())
322 }
323}
324
325struct Dispatcher {
328 options: ServerOptions,
329 readable: Option<Readable>,
330 connections: BTreeMap<u64, Connection>,
331}
332
333impl Dispatcher {
334 fn new(options: ServerOptions, readable: Option<Readable>) -> Self {
335 Self {
336 options,
337 readable,
338 connections: BTreeMap::new(),
339 }
340 }
341
342 fn run<S: NamedTypeLinks, P: AccessPolicy>(
344 &mut self,
345 sessions: &mut LinksSessions<S, P>,
346 job: Job,
347 ) -> bool {
348 match job {
349 Job::Shutdown => return false,
350 Job::Close(connection) => {
351 if let Some(closed) = self.connections.remove(&connection) {
352 sessions.close(closed.session);
353 }
354 }
355 Job::Request {
356 connection,
357 outbox,
358 document,
359 format,
360 done,
361 } => {
362 if self.options.trace
363 && sessions
364 .store()
365 .query_limits()
366 .is_none_or(|limits| admit_document(&document, limits).is_ok())
367 {
368 crate::diagnostics::stderr!("[server] request: {}", format_document(&document));
369 }
370 let current = self
371 .connections
372 .entry(connection)
373 .or_insert_with(|| Connection::new(outbox, sessions.open(None)));
374 let triplets = sessions.has_triplets();
375 let mut changes = Vec::new();
376 let mut triplet_changes = Vec::new();
377 let reply = current
378 .execute(&document, format, triplets)
379 .unwrap_or_else(|| {
380 if triplets {
381 sessions.execute_triplets_observed(
382 current.session,
383 &document,
384 &mut triplet_changes,
385 )
386 } else {
387 sessions.execute_observed(current.session, &document, &mut changes)
388 }
389 });
390 if self.options.trace {
391 crate::diagnostics::stderr!("[server] reply: {}", format_document(&reply));
392 }
393 let reply = if triplets {
394 pack_triplets(reply, format)
395 } else {
396 reply
397 };
398 current.outbox.reply(reply, format);
399 let readable = self.readable.as_ref();
400 let others = self.connections.iter().filter(|(id, _)| **id != connection);
401 if !changes.is_empty() || !triplet_changes.is_empty() {
402 for (_, other) in others {
403 let session = other.session;
404 let mut can_read = |link: &Link| {
405 readable.is_none_or(|readable| readable(link))
406 && sessions.can_read(session, link)
407 };
408 other.notify(&changes, &mut can_read);
409 other.notify_triplets(&triplet_changes, &mut can_read);
410 }
411 }
412 let _ = done.send(());
413 }
414 }
415 true
416 }
417
418 fn close_all<S: NamedTypeLinks, P: AccessPolicy>(
420 &mut self,
421 sessions: &mut LinksSessions<S, P>,
422 ) {
423 for (_, connection) in std::mem::take(&mut self.connections) {
424 sessions.close(connection.session);
425 }
426 }
427}
428
429struct Connection {
432 outbox: Arc<Outbox>,
433 session: SessionId,
434 subscriptions: BTreeMap<u32, (Vec<Part>, MessageFormat)>,
435 next_subscription: u32,
436}
437
438impl Connection {
439 fn new(outbox: Arc<Outbox>, session: SessionId) -> Self {
440 Self {
441 outbox,
442 session,
443 subscriptions: BTreeMap::new(),
444 next_subscription: 1,
445 }
446 }
447
448 fn execute(
451 &mut self,
452 document: &[LiNo<String>],
453 format: MessageFormat,
454 triplets: bool,
455 ) -> Option<LinoDocument> {
456 if triplets {
457 match TripletsOperation::from_document(document) {
458 Ok(Some(TripletsOperation::Subscribe(restriction))) => {
459 return Some(self.subscribe(restriction, format));
460 }
461 Ok(None) => {}
462 Ok(Some(_)) | Err(_) => return None,
463 }
464 }
465 match LinksOperation::from_document(document) {
466 Ok(Some(LinksOperation::Subscribe(restriction))) => {
467 Some(self.subscribe(restriction, format))
468 }
469 Ok(Some(LinksOperation::Unsubscribe(subscription))) => {
470 self.subscriptions.remove(&subscription);
472 Some(Vec::new())
473 }
474 _ => None,
475 }
476 }
477
478 fn subscribe(&mut self, restriction: Vec<Part>, format: MessageFormat) -> LinoDocument {
479 let subscription = self.next_subscription;
480 self.next_subscription = self.next_subscription.wrapping_add(1);
481 self.subscriptions
482 .insert(subscription, (restriction, format));
483 subscription_document(subscription)
484 }
485
486 fn notify(&self, changes: &[Change], readable: &mut dyn FnMut(&Link) -> bool) {
490 for (subscription, (restriction, format)) in &self.subscriptions {
491 let mut side = |link: &Link| {
492 if !link.is_null() && matches(link, restriction) && readable(link) {
493 *link
494 } else {
495 Link::null()
496 }
497 };
498 let seen: Vec<Change> = changes
499 .iter()
500 .map(|(before, after)| (side(before), side(after)))
501 .filter(|(before, after)| !before.is_null() || !after.is_null())
502 .collect();
503 if !seen.is_empty()
504 && !self
505 .outbox
506 .push(notification_document(*subscription, &seen), *format)
507 {
508 return;
509 }
510 }
511 }
512}
513
514impl Connection {
515 fn notify_triplets(&self, changes: &[TripletChange], readable: &mut dyn FnMut(&Link) -> bool) {
517 if changes.is_empty() {
518 return;
519 }
520 for (subscription, (restriction, format)) in &self.subscriptions {
521 let mut side = |triplet: Option<Triplet>| {
522 triplet.filter(|triplet| {
523 matches_triplet(triplet, restriction)
524 && readable(&Link::new(triplet.index, triplet.type_id, triplet.index))
525 })
526 };
527 let seen: Vec<TripletChange> = changes
528 .iter()
529 .map(|change| TripletChange {
530 before: side(change.before),
531 after: side(change.after),
532 })
533 .filter(|change| change.before.is_some() || change.after.is_some())
534 .collect();
535 if !seen.is_empty()
536 && !self.outbox.push(
537 pack_triplets(triplet_notification_document(*subscription, &seen), *format),
538 *format,
539 )
540 {
541 return;
542 }
543 }
544 }
545}
546
547struct Outbox {
551 state: Mutex<OutboxState>,
552 changed: Condvar,
553 max_pending_notifications: usize,
554 hang_up: Box<dyn Fn() + Send + Sync>,
556}
557
558#[derive(Default)]
559struct OutboxState {
560 queue: VecDeque<(LinoDocument, MessageFormat, bool)>,
561 pending_replies: usize,
562 pending_notifications: usize,
563 closed: bool,
564}
565
566impl Outbox {
567 fn new(max_pending_notifications: usize, hang_up: Box<dyn Fn() + Send + Sync>) -> Self {
568 Self {
569 state: Mutex::default(),
570 changed: Condvar::new(),
571 max_pending_notifications,
572 hang_up,
573 }
574 }
575
576 fn lock(&self) -> MutexGuard<'_, OutboxState> {
577 self.state
578 .lock()
579 .unwrap_or_else(|poisoned| poisoned.into_inner())
580 }
581
582 fn reply(&self, document: LinoDocument, format: MessageFormat) {
585 let mut state = self.lock();
586 if state.closed {
587 return;
588 }
589 state.queue.push_back((document, format, true));
590 state.pending_replies += 1;
591 self.changed.notify_all();
592 }
593
594 fn push(&self, document: LinoDocument, format: MessageFormat) -> bool {
598 {
599 let mut state = self.lock();
600 if state.closed {
601 return false;
602 }
603 if state.pending_notifications < self.max_pending_notifications {
604 state.queue.push_back((document, format, false));
605 state.pending_notifications += 1;
606 self.changed.notify_all();
607 return true;
608 }
609 }
610 self.close();
611 false
612 }
613
614 fn wait_for_replies(&self) {
617 let mut state = self.lock();
618 while state.pending_replies > 0 && !state.closed {
619 state = self
620 .changed
621 .wait(state)
622 .unwrap_or_else(|poisoned| poisoned.into_inner());
623 }
624 }
625
626 fn is_closed(&self) -> bool {
627 self.lock().closed
628 }
629
630 fn write_all(&self, writer: &mut impl Write, limits: ProtocolLimits) -> ProtocolResult<()> {
632 let result = self.try_write_all(writer, limits);
633 if result.is_err() {
634 self.close();
636 }
637 result
638 }
639
640 fn try_write_all(&self, writer: &mut impl Write, limits: ProtocolLimits) -> ProtocolResult<()> {
641 loop {
642 let (document, format) = {
643 let mut state = self.lock();
644 while state.queue.is_empty() && !state.closed {
645 state = self
646 .changed
647 .wait(state)
648 .unwrap_or_else(|poisoned| poisoned.into_inner());
649 }
650 if state.closed {
651 return Ok(());
652 }
653 let (document, format, _) = &state.queue[0];
654 (document.clone(), *format)
655 };
656 format.protocol(limits).write_document(writer, &document)?;
657 writer.flush()?;
658 let mut state = self.lock();
659 if let Some((_, _, reply)) = state.queue.pop_front() {
660 if reply {
661 state.pending_replies -= 1;
662 } else {
663 state.pending_notifications -= 1;
664 }
665 }
666 self.changed.notify_all();
667 }
668 }
669
670 fn close(&self) {
672 {
673 let mut state = self.lock();
674 if state.closed {
675 return;
676 }
677 state.closed = true;
678 state.queue.clear();
679 self.changed.notify_all();
680 }
681 (self.hang_up)();
682 }
683}
684
685fn accept_loop(
686 listener: TcpListener,
687 jobs: Sender<Job>,
688 stopping: Arc<AtomicBool>,
689 options: ServerOptions,
690 query_limits: Option<QueryLimits>,
691) {
692 for stream in listener.incoming() {
693 if stopping.load(Ordering::SeqCst) {
694 return;
695 }
696 let Ok(stream) = stream else { continue };
697 let jobs = jobs.clone();
698 thread::spawn(move || {
699 if let Err(error) = handle_connection(stream, jobs, options, query_limits) {
700 if options.trace {
701 crate::diagnostics::stderr!("[server] connection closed: {error}");
702 }
703 }
704 });
705 }
706}
707
708fn handle_connection(
709 stream: TcpStream,
710 jobs: Sender<Job>,
711 options: ServerOptions,
712 query_limits: Option<QueryLimits>,
713) -> ProtocolResult<()> {
714 static CONNECTIONS: AtomicU64 = AtomicU64::new(0);
715 let connection = CONNECTIONS.fetch_add(1, Ordering::Relaxed);
716 let _ = stream.set_nodelay(true);
717 let outbox = {
718 let stream = stream.try_clone()?;
719 Arc::new(Outbox::new(
720 options.max_pending_notifications,
721 Box::new(move || {
722 let _ = stream.shutdown(Shutdown::Both);
723 }),
724 ))
725 };
726 let writer = {
727 let outbox = Arc::clone(&outbox);
728 let mut stream = BufWriter::new(stream.try_clone()?);
729 thread::spawn(move || {
730 if let Err(error) = outbox.write_all(&mut stream, options.limits) {
731 if options.trace {
732 crate::diagnostics::stderr!("[server] connection closed: {error}");
733 }
734 }
735 })
736 };
737 let result = serve_connection(stream, connection, &outbox, &jobs, options, query_limits);
738 let _ = jobs.send(Job::Close(connection));
740 outbox.close();
741 let _ = writer.join();
742 result
743}
744
745fn serve_connection(
746 stream: TcpStream,
747 connection: u64,
748 outbox: &Arc<Outbox>,
749 jobs: &Sender<Job>,
750 options: ServerOptions,
751 query_limits: Option<QueryLimits>,
752) -> ProtocolResult<()> {
753 let mut reader = BufReader::new(stream);
754 loop {
755 let (document, format) =
756 match read_any_document_with_query_limits(&mut reader, &options.limits, query_limits) {
757 Ok(Some(message)) => message,
758 Ok(None) => {
759 if options.trace {
760 crate::diagnostics::stderr!("[server] client hung up");
761 }
762 return Ok(());
763 }
764 Err(_) if outbox.is_closed() => return Ok(()),
765 Err(error) => {
766 outbox.reply(error_document(&error.to_string()), MessageFormat::Text);
768 outbox.wait_for_replies();
769 return Err(error);
770 }
771 };
772 if options.accept.accepts(format) {
773 let (done, finished) = mpsc::channel();
774 let job = Job::Request {
775 connection,
776 outbox: Arc::clone(outbox),
777 document,
778 format,
779 done,
780 };
781 if jobs.send(job).is_err() || finished.recv().is_err() {
783 outbox.reply(error_document("server is shutting down"), format);
784 }
785 } else {
786 outbox.reply(
787 error_document("this server does not accept this protocol"),
788 format,
789 );
790 }
791 outbox.wait_for_replies();
792 if outbox.is_closed() {
793 if options.trace {
794 crate::diagnostics::stderr!("[server] connection closed");
795 }
796 return Ok(());
797 }
798 }
799}
800
801pub fn error_document(message: &str) -> LinoDocument {
803 vec![LiNo::Link {
804 id: Some("error".to_string()),
805 values: vec![LiNo::Ref(message.to_string())],
806 }]
807}
808
809pub fn error_message(document: &[LiNo<String>]) -> Option<&str> {
811 match document {
812 [LiNo::Link {
813 id: Some(id),
814 values,
815 }] if id == "error" => match values.as_slice() {
816 [LiNo::Ref(message)] => Some(message),
817 _ => None,
818 },
819 _ => None,
820 }
821}
822
823#[cfg(test)]
824mod tests;