1use super::error::ProtocolResult;
22use super::links_operations::{
23 matches, notification_document, parse_changes, subscription_document, Change, LinksOperation,
24 Part,
25};
26use super::protocols::{read_any_document, MessageFormat, ProtocolLimits};
27use super::sessions::{LinksSessions, SessionId};
28use crate::link::Link;
29use crate::named_type_links::NamedTypeLinks;
30use crate::permissions::AccessPolicy;
31use crate::query_processor::QueryProcessor;
32use links_notation::binary::{format_document, LinoDocument};
33use links_notation::LiNo;
34use std::collections::{BTreeMap, VecDeque};
35use std::fmt;
36use std::io::{BufReader, BufWriter, Write};
37use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
38use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
39use std::sync::mpsc::{self, Receiver, Sender};
40use std::sync::{Arc, Condvar, Mutex, MutexGuard};
41use std::thread;
42
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
45pub enum AcceptedProtocols {
46 #[default]
48 Any,
49 Text,
51 Binary,
53}
54
55impl AcceptedProtocols {
56 fn accepts(self, format: MessageFormat) -> bool {
57 matches!(
58 (self, format),
59 (AcceptedProtocols::Any, _)
60 | (AcceptedProtocols::Text, MessageFormat::Text)
61 | (AcceptedProtocols::Binary, MessageFormat::Binary(_))
62 )
63 }
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub struct ServerOptions {
69 pub trace: bool,
71 pub auto_create_missing_references: bool,
73 pub accept: AcceptedProtocols,
75 pub limits: ProtocolLimits,
77 pub max_pending_notifications: usize,
80}
81
82pub const DEFAULT_MAX_PENDING_NOTIFICATIONS: usize = 1024;
84
85impl Default for ServerOptions {
86 fn default() -> Self {
87 Self {
88 trace: false,
89 auto_create_missing_references: false,
90 accept: AcceptedProtocols::default(),
91 limits: ProtocolLimits::default(),
92 max_pending_notifications: DEFAULT_MAX_PENDING_NOTIFICATIONS,
93 }
94 }
95}
96
97pub type Readable = Box<dyn Fn(&Link) -> bool + Send>;
99
100enum Job {
101 Request {
104 connection: u64,
105 outbox: Arc<Outbox>,
106 document: LinoDocument,
107 format: MessageFormat,
108 done: Sender<()>,
109 },
110 Close(u64),
112 Shutdown,
113}
114
115#[derive(Clone, Debug)]
117pub struct ShutdownHandle {
118 jobs: Sender<Job>,
119 stopping: Arc<AtomicBool>,
120 address: SocketAddr,
121}
122
123impl ShutdownHandle {
124 pub fn shutdown(&self) {
126 self.stopping.store(true, Ordering::SeqCst);
127 let _ = self.jobs.send(Job::Shutdown);
128 let _ = TcpStream::connect(self.address);
130 }
131}
132
133pub struct LinksServer {
135 listener: TcpListener,
136 options: ServerOptions,
137 readable: Option<Readable>,
138 jobs: Sender<Job>,
139 queue: Receiver<Job>,
140 stopping: Arc<AtomicBool>,
141}
142
143impl fmt::Debug for LinksServer {
144 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
145 formatter
146 .debug_struct("LinksServer")
147 .field("listener", &self.listener)
148 .field("options", &self.options)
149 .field("readable", &self.readable.is_some())
150 .finish_non_exhaustive()
151 }
152}
153
154impl LinksServer {
155 pub fn bind(address: impl ToSocketAddrs, options: ServerOptions) -> ProtocolResult<Self> {
157 let listener = TcpListener::bind(address)?;
158 let (jobs, queue) = mpsc::channel();
159 Ok(Self {
160 listener,
161 options,
162 readable: None,
163 jobs,
164 queue,
165 stopping: Arc::new(AtomicBool::new(false)),
166 })
167 }
168
169 pub fn with_readable(mut self, readable: impl Fn(&Link) -> bool + Send + 'static) -> Self {
176 self.readable = Some(Box::new(readable));
177 self
178 }
179
180 pub fn local_addr(&self) -> ProtocolResult<SocketAddr> {
182 Ok(self.listener.local_addr()?)
183 }
184
185 pub fn shutdown_handle(&self) -> ProtocolResult<ShutdownHandle> {
187 Ok(ShutdownHandle {
188 jobs: self.jobs.clone(),
189 stopping: Arc::clone(&self.stopping),
190 address: self.local_addr()?,
191 })
192 }
193
194 pub fn serve<S: NamedTypeLinks>(self, storage: &mut S) -> ProtocolResult<()> {
197 let auto_create = self.options.auto_create_missing_references;
198 let mut sessions =
199 LinksSessions::new(storage).with_auto_create_missing_references(auto_create);
200 self.serve_sessions(&mut sessions)
201 }
202
203 pub fn serve_sessions<S: NamedTypeLinks, P: AccessPolicy>(
207 self,
208 sessions: &mut LinksSessions<S, P>,
209 ) -> ProtocolResult<()> {
210 let LinksServer {
211 listener,
212 options,
213 readable,
214 jobs,
215 queue,
216 stopping,
217 } = self;
218 let acceptor = {
219 let stopping = Arc::clone(&stopping);
220 thread::spawn(move || accept_loop(listener, jobs, stopping, options))
221 };
222 let mut dispatcher = Dispatcher::new(options, readable);
223 while let Ok(job) = queue.recv() {
224 if !dispatcher.run(sessions, job) {
225 break;
226 }
227 }
228 dispatcher.close_all(sessions);
229 stopping.store(true, Ordering::SeqCst);
230 drop(queue);
231 let _ = acceptor.join();
232 Ok(())
233 }
234}
235
236struct Dispatcher {
239 options: ServerOptions,
240 readable: Option<Readable>,
241 connections: BTreeMap<u64, Connection>,
242}
243
244impl Dispatcher {
245 fn new(options: ServerOptions, readable: Option<Readable>) -> Self {
246 Self {
247 options,
248 readable,
249 connections: BTreeMap::new(),
250 }
251 }
252
253 fn run<S: NamedTypeLinks, P: AccessPolicy>(
255 &mut self,
256 sessions: &mut LinksSessions<S, P>,
257 job: Job,
258 ) -> bool {
259 match job {
260 Job::Shutdown => return false,
261 Job::Close(connection) => {
262 if let Some(closed) = self.connections.remove(&connection) {
263 sessions.close(closed.session);
264 }
265 }
266 Job::Request {
267 connection,
268 outbox,
269 document,
270 format,
271 done,
272 } => {
273 if self.options.trace {
274 eprintln!("[server] request: {}", format_document(&document));
275 }
276 let current = self
277 .connections
278 .entry(connection)
279 .or_insert_with(|| Connection::new(outbox, sessions.open(None)));
280 let mut changes = Vec::new();
281 let reply = current.execute(&document, format).unwrap_or_else(|| {
282 sessions.execute_observed(current.session, &document, &mut changes)
283 });
284 if self.options.trace {
285 eprintln!("[server] reply: {}", format_document(&reply));
286 }
287 current.outbox.reply(reply, format);
288 if !changes.is_empty() {
289 let readable = self.readable.as_ref();
290 for (_, other) in self.connections.iter().filter(|(id, _)| **id != connection) {
291 let session = other.session;
292 other.notify(&changes, &mut |link: &Link| {
293 readable.is_none_or(|readable| readable(link))
294 && sessions.can_read(session, link)
295 });
296 }
297 }
298 let _ = done.send(());
299 }
300 }
301 true
302 }
303
304 fn close_all<S: NamedTypeLinks, P: AccessPolicy>(
306 &mut self,
307 sessions: &mut LinksSessions<S, P>,
308 ) {
309 for (_, connection) in std::mem::take(&mut self.connections) {
310 sessions.close(connection.session);
311 }
312 }
313}
314
315struct Connection {
318 outbox: Arc<Outbox>,
319 session: SessionId,
320 subscriptions: BTreeMap<u32, (Vec<Part>, MessageFormat)>,
321 next_subscription: u32,
322}
323
324impl Connection {
325 fn new(outbox: Arc<Outbox>, session: SessionId) -> Self {
326 Self {
327 outbox,
328 session,
329 subscriptions: BTreeMap::new(),
330 next_subscription: 1,
331 }
332 }
333
334 fn execute(
337 &mut self,
338 document: &[LiNo<String>],
339 format: MessageFormat,
340 ) -> Option<LinoDocument> {
341 match LinksOperation::from_document(document) {
342 Ok(Some(LinksOperation::Subscribe(restriction))) => {
343 let subscription = self.next_subscription;
344 self.next_subscription = self.next_subscription.wrapping_add(1);
345 self.subscriptions
346 .insert(subscription, (restriction, format));
347 Some(subscription_document(subscription))
348 }
349 Ok(Some(LinksOperation::Unsubscribe(subscription))) => {
350 self.subscriptions.remove(&subscription);
352 Some(Vec::new())
353 }
354 _ => None,
355 }
356 }
357
358 fn notify(&self, changes: &[Change], readable: &mut dyn FnMut(&Link) -> bool) {
362 for (subscription, (restriction, format)) in &self.subscriptions {
363 let mut side = |link: &Link| {
364 if !link.is_null() && matches(link, restriction) && readable(link) {
365 *link
366 } else {
367 Link::null()
368 }
369 };
370 let seen: Vec<Change> = changes
371 .iter()
372 .map(|(before, after)| (side(before), side(after)))
373 .filter(|(before, after)| !before.is_null() || !after.is_null())
374 .collect();
375 if !seen.is_empty()
376 && !self
377 .outbox
378 .push(notification_document(*subscription, &seen), *format)
379 {
380 return;
381 }
382 }
383 }
384}
385
386struct Outbox {
390 state: Mutex<OutboxState>,
391 changed: Condvar,
392 max_pending_notifications: usize,
393 hang_up: Box<dyn Fn() + Send + Sync>,
395}
396
397#[derive(Default)]
398struct OutboxState {
399 queue: VecDeque<(LinoDocument, MessageFormat, bool)>,
400 pending_replies: usize,
401 pending_notifications: usize,
402 closed: bool,
403}
404
405impl Outbox {
406 fn new(max_pending_notifications: usize, hang_up: Box<dyn Fn() + Send + Sync>) -> Self {
407 Self {
408 state: Mutex::default(),
409 changed: Condvar::new(),
410 max_pending_notifications,
411 hang_up,
412 }
413 }
414
415 fn lock(&self) -> MutexGuard<'_, OutboxState> {
416 self.state
417 .lock()
418 .unwrap_or_else(|poisoned| poisoned.into_inner())
419 }
420
421 fn reply(&self, document: LinoDocument, format: MessageFormat) {
424 let mut state = self.lock();
425 if state.closed {
426 return;
427 }
428 state.queue.push_back((document, format, true));
429 state.pending_replies += 1;
430 self.changed.notify_all();
431 }
432
433 fn push(&self, document: LinoDocument, format: MessageFormat) -> bool {
437 {
438 let mut state = self.lock();
439 if state.closed {
440 return false;
441 }
442 if state.pending_notifications < self.max_pending_notifications {
443 state.queue.push_back((document, format, false));
444 state.pending_notifications += 1;
445 self.changed.notify_all();
446 return true;
447 }
448 }
449 self.close();
450 false
451 }
452
453 fn wait_for_replies(&self) {
456 let mut state = self.lock();
457 while state.pending_replies > 0 && !state.closed {
458 state = self
459 .changed
460 .wait(state)
461 .unwrap_or_else(|poisoned| poisoned.into_inner());
462 }
463 }
464
465 fn is_closed(&self) -> bool {
466 self.lock().closed
467 }
468
469 fn write_all(&self, writer: &mut impl Write, limits: ProtocolLimits) -> ProtocolResult<()> {
471 let result = self.try_write_all(writer, limits);
472 if result.is_err() {
473 self.close();
475 }
476 result
477 }
478
479 fn try_write_all(&self, writer: &mut impl Write, limits: ProtocolLimits) -> ProtocolResult<()> {
480 loop {
481 let (document, format) = {
482 let mut state = self.lock();
483 while state.queue.is_empty() && !state.closed {
484 state = self
485 .changed
486 .wait(state)
487 .unwrap_or_else(|poisoned| poisoned.into_inner());
488 }
489 if state.closed {
490 return Ok(());
491 }
492 let (document, format, _) = &state.queue[0];
493 (document.clone(), *format)
494 };
495 format.protocol(limits).write_document(writer, &document)?;
496 writer.flush()?;
497 let mut state = self.lock();
498 if let Some((_, _, reply)) = state.queue.pop_front() {
499 if reply {
500 state.pending_replies -= 1;
501 } else {
502 state.pending_notifications -= 1;
503 }
504 }
505 self.changed.notify_all();
506 }
507 }
508
509 fn close(&self) {
511 {
512 let mut state = self.lock();
513 if state.closed {
514 return;
515 }
516 state.closed = true;
517 state.queue.clear();
518 self.changed.notify_all();
519 }
520 (self.hang_up)();
521 }
522}
523
524fn accept_loop(
525 listener: TcpListener,
526 jobs: Sender<Job>,
527 stopping: Arc<AtomicBool>,
528 options: ServerOptions,
529) {
530 for stream in listener.incoming() {
531 if stopping.load(Ordering::SeqCst) {
532 return;
533 }
534 let Ok(stream) = stream else { continue };
535 let jobs = jobs.clone();
536 thread::spawn(move || {
537 if let Err(error) = handle_connection(stream, jobs, options) {
538 if options.trace {
539 eprintln!("[server] connection closed: {error}");
540 }
541 }
542 });
543 }
544}
545
546fn handle_connection(
547 stream: TcpStream,
548 jobs: Sender<Job>,
549 options: ServerOptions,
550) -> ProtocolResult<()> {
551 static CONNECTIONS: AtomicU64 = AtomicU64::new(0);
552 let connection = CONNECTIONS.fetch_add(1, Ordering::Relaxed);
553 let _ = stream.set_nodelay(true);
554 let outbox = {
555 let stream = stream.try_clone()?;
556 Arc::new(Outbox::new(
557 options.max_pending_notifications,
558 Box::new(move || {
559 let _ = stream.shutdown(Shutdown::Both);
560 }),
561 ))
562 };
563 let writer = {
564 let outbox = Arc::clone(&outbox);
565 let mut stream = BufWriter::new(stream.try_clone()?);
566 thread::spawn(move || {
567 if let Err(error) = outbox.write_all(&mut stream, options.limits) {
568 if options.trace {
569 eprintln!("[server] connection closed: {error}");
570 }
571 }
572 })
573 };
574 let result = serve_connection(stream, connection, &outbox, &jobs, options);
575 let _ = jobs.send(Job::Close(connection));
577 outbox.close();
578 let _ = writer.join();
579 result
580}
581
582fn serve_connection(
583 stream: TcpStream,
584 connection: u64,
585 outbox: &Arc<Outbox>,
586 jobs: &Sender<Job>,
587 options: ServerOptions,
588) -> ProtocolResult<()> {
589 let mut reader = BufReader::new(stream);
590 loop {
591 let (document, format) = match read_any_document(&mut reader, &options.limits) {
592 Ok(Some(message)) => message,
593 Ok(None) => {
594 if options.trace {
595 eprintln!("[server] client hung up");
596 }
597 return Ok(());
598 }
599 Err(_) if outbox.is_closed() => return Ok(()),
600 Err(error) => {
601 outbox.reply(error_document(&error.to_string()), MessageFormat::Text);
603 outbox.wait_for_replies();
604 return Err(error);
605 }
606 };
607 if options.accept.accepts(format) {
608 let (done, finished) = mpsc::channel();
609 let job = Job::Request {
610 connection,
611 outbox: Arc::clone(outbox),
612 document,
613 format,
614 done,
615 };
616 if jobs.send(job).is_err() || finished.recv().is_err() {
618 outbox.reply(error_document("server is shutting down"), format);
619 }
620 } else {
621 outbox.reply(
622 error_document("this server does not accept this protocol"),
623 format,
624 );
625 }
626 outbox.wait_for_replies();
627 if outbox.is_closed() {
628 if options.trace {
629 eprintln!("[server] connection closed");
630 }
631 return Ok(());
632 }
633 }
634}
635
636pub fn error_document(message: &str) -> LinoDocument {
638 vec![LiNo::Link {
639 id: Some("error".to_string()),
640 values: vec![LiNo::Ref(message.to_string())],
641 }]
642}
643
644pub fn error_message(document: &[LiNo<String>]) -> Option<&str> {
646 match document {
647 [LiNo::Link {
648 id: Some(id),
649 values,
650 }] if id == "error" => match values.as_slice() {
651 [LiNo::Ref(message)] => Some(message),
652 _ => None,
653 },
654 _ => None,
655 }
656}
657
658pub fn execute_request<S: NamedTypeLinks>(
665 storage: &mut S,
666 processor: &QueryProcessor,
667 document: &[LiNo<String>],
668) -> LinoDocument {
669 execute_observed_request(storage, processor, document, &mut Vec::new())
670}
671
672pub(super) fn execute_observed_request<S: NamedTypeLinks>(
675 storage: &mut S,
676 processor: &QueryProcessor,
677 document: &[LiNo<String>],
678 changed: &mut Vec<Change>,
679) -> LinoDocument {
680 match try_execute_request(storage, processor, document, changed) {
681 Ok(reply) => reply,
682 Err(error) => error_document(&format!("{error:#}")),
683 }
684}
685
686fn try_execute_request<S: NamedTypeLinks>(
687 storage: &mut S,
688 processor: &QueryProcessor,
689 document: &[LiNo<String>],
690 changed: &mut Vec<Change>,
691) -> anyhow::Result<LinoDocument> {
692 if let Some(operation) = LinksOperation::from_document(document)? {
693 let reply = operation.execute(storage)?;
694 if matches!(
695 operation,
696 LinksOperation::Create { .. }
697 | LinksOperation::Update { .. }
698 | LinksOperation::Delete(_)
699 ) {
700 changed.extend(parse_changes(&reply)?);
701 }
702 return Ok(reply);
703 }
704 if document.is_empty() {
705 let mut links = storage.all_links();
706 links.sort_by_key(|link| link.index);
707 return links.iter().map(|link| link_lino(storage, link)).collect();
708 }
709 let changes = processor.process_query(storage, &format_document(document))?;
710 changed.extend(changes.iter().map(|(before, after)| {
711 (
712 before.unwrap_or_else(Link::null),
713 after.unwrap_or_else(Link::null),
714 )
715 }));
716 if !changes.is_empty() {
717 storage.save()?;
718 }
719 changes
720 .iter()
721 .map(|(before, after)| {
722 Ok(LiNo::Link {
723 id: None,
724 values: vec![
725 change_side(storage, before.as_ref())?,
726 change_side(storage, after.as_ref())?,
727 ],
728 })
729 })
730 .collect()
731}
732
733fn link_lino<S: NamedTypeLinks>(storage: &mut S, link: &Link) -> anyhow::Result<LiNo<String>> {
735 Ok(LiNo::Link {
736 id: Some(reference_name(storage, link.index)?),
737 values: vec![
738 LiNo::Ref(reference_name(storage, link.source)?),
739 LiNo::Ref(reference_name(storage, link.target)?),
740 ],
741 })
742}
743
744fn change_side<S: NamedTypeLinks>(
746 storage: &mut S,
747 link: Option<&Link>,
748) -> anyhow::Result<LiNo<String>> {
749 let values = match link {
750 Some(link) => vec![link_lino(storage, link)?],
751 None => Vec::new(),
752 };
753 Ok(LiNo::Link { id: None, values })
754}
755
756fn reference_name<S: NamedTypeLinks>(storage: &mut S, id: u32) -> anyhow::Result<String> {
757 Ok(storage.get_name(id)?.unwrap_or_else(|| id.to_string()))
758}
759
760#[cfg(test)]
761mod tests {
762 use super::*;
763 use crate::link_storage::LinkStorage;
764 use links_notation::binary::parse_document;
765
766 fn outbox() -> Arc<Outbox> {
767 Arc::new(Outbox::new(
768 DEFAULT_MAX_PENDING_NOTIFICATIONS,
769 Box::new(|| {}),
770 ))
771 }
772
773 fn request(
774 dispatcher: &mut Dispatcher,
775 sessions: &mut LinksSessions<LinkStorage>,
776 connection: u64,
777 outbox: &Arc<Outbox>,
778 text: &str,
779 ) {
780 let (done, finished) = mpsc::channel();
781 let job = Job::Request {
782 connection,
783 outbox: Arc::clone(outbox),
784 document: parse_document(text).unwrap(),
785 format: MessageFormat::Text,
786 done,
787 };
788 assert!(dispatcher.run(sessions, job));
789 finished.recv().unwrap();
790 }
791
792 fn queued(outbox: &Outbox) -> Vec<String> {
793 outbox
794 .lock()
795 .queue
796 .drain(..)
797 .map(|(document, _, _)| format_document(&document))
798 .collect()
799 }
800
801 #[test]
802 fn closing_a_connection_drops_its_subscriptions() {
803 let database = tempfile::NamedTempFile::new().unwrap();
804 let storage = LinkStorage::new(database.path(), false).unwrap();
805 let mut sessions = LinksSessions::new(storage);
806 let mut dispatcher = Dispatcher::new(ServerOptions::default(), None);
807 let (subscriber, writer) = (outbox(), outbox());
808
809 request(
810 &mut dispatcher,
811 &mut sessions,
812 1,
813 &subscriber,
814 "(subscribe: ())",
815 );
816 request(
817 &mut dispatcher,
818 &mut sessions,
819 2,
820 &writer,
821 "(create: (0 0))",
822 );
823 assert_eq!(dispatcher.connections.len(), 2);
824 assert_eq!(sessions.sessions().len(), 2);
825 assert_eq!(
826 queued(&subscriber),
827 ["(subscription: 1)", "(notify: 1)\n() ((1: 0 0))"]
828 );
829 assert_eq!(queued(&writer), ["() ((1: 0 0))"]);
831
832 assert!(dispatcher.run(&mut sessions, Job::Close(1)));
833 assert_eq!(dispatcher.connections.keys().collect::<Vec<_>>(), [&2]);
834 assert_eq!(sessions.sessions().len(), 1);
836 request(
837 &mut dispatcher,
838 &mut sessions,
839 2,
840 &writer,
841 "(create: (1 1))",
842 );
843 assert!(queued(&subscriber).is_empty());
844 assert!(!dispatcher.run(&mut sessions, Job::Shutdown));
845 dispatcher.close_all(&mut sessions);
846 assert!(sessions.sessions().is_empty());
847 }
848}