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