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