Skip to main content

link_cli/protocol/
server.rs

1//! A TCP server exposing a links store through the LiNo protocols.
2//!
3//! Each connection gets its own thread that only parses messages and another
4//! that writes them; every request is executed by the thread that called
5//! [`LinksServer::serve`], one at a time, so the store needs neither `Send`
6//! nor locking. The protocol is detected per message and the reply uses the
7//! same protocol, so text and binary clients can share one server.
8//!
9//! A connection may `(subscribe: (index source target))` to the links matching
10//! a pattern: every later write of another connection that changes such a link
11//! is pushed to it as `(notify: N)` and the changes, in the protocol of the
12//! subscription request, until it sends `(unsubscribe: N)` or hangs up. The
13//! serving thread queues a reply together with the pushes of the same write,
14//! so every connection reads its replies and pushes in the order the store
15//! changed.
16//!
17//! Every connection is a session of a [`LinksSessions`], with a subject of
18//! its own (issue #149); a subscriber is pushed only what its subject may
19//! read.
20//!
21//! With [`ServerOptions::triplets`] the same requests and pushes are about
22//! triplets; see [`TripletsOperation`].
23
24use 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/// Which protocols a server accepts.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub enum AcceptedProtocols {
62    /// Detect the protocol of every message (the default).
63    #[default]
64    Any,
65    /// Only [`TextLinoProtocol`](super::TextLinoProtocol) messages.
66    Text,
67    /// Only [`BinaryLinoProtocol`](super::BinaryLinoProtocol) messages.
68    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/// Server configuration.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct ServerOptions {
85    /// Print every request and reply to stderr.
86    pub trace: bool,
87    /// Passed to [`QueryProcessor::with_auto_create_missing_references`].
88    pub auto_create_missing_references: bool,
89    /// Protocols the server answers.
90    pub accept: AcceptedProtocols,
91    /// Limits applied to incoming messages.
92    pub limits: ProtocolLimits,
93    /// Pushes a connection may have waiting before the server closes it as
94    /// too slow to read them.
95    pub max_pending_notifications: usize,
96    /// Read every request as triplets (issue #152): `(create: (type from to))`
97    /// and the rest of [`TripletsOperation`], over a store of doublets. A server
98    /// without it answers as it always did.
99    pub triplets: bool,
100}
101
102/// The default of [`ServerOptions::max_pending_notifications`].
103pub 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
118/// Which links a subscriber may see: see [`LinksServer::with_readable`].
119pub type Readable = Box<dyn Fn(&Link) -> bool + Send>;
120
121enum Job {
122    /// A request of `connection`; its reply goes to `outbox`, and `done` is
123    /// signalled once it is there.
124    Request {
125        connection: u64,
126        outbox: Arc<Outbox>,
127        document: LinoDocument,
128        format: MessageFormat,
129        done: Sender<()>,
130    },
131    /// `connection` hung up: its subscriptions go with it.
132    Close(u64),
133    Shutdown,
134}
135
136/// Stops a running [`LinksServer::serve`] from another thread.
137#[derive(Clone, Debug)]
138pub struct ShutdownHandle {
139    jobs: Sender<Job>,
140    stopping: Arc<AtomicBool>,
141    address: SocketAddr,
142}
143
144impl ShutdownHandle {
145    /// Asks the server to stop; `serve` returns after the current request.
146    pub fn shutdown(&self) {
147        self.stopping.store(true, Ordering::SeqCst);
148        let _ = self.jobs.send(Job::Shutdown);
149        // Wake the accept loop so it notices the flag.
150        let _ = TcpStream::connect(self.address);
151    }
152}
153
154/// A bound, not yet serving, LiNo server.
155pub 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    /// Binds to `address` (use port `0` for an ephemeral port).
177    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    /// Lets subscribers see only the links `readable` accepts; without it,
191    /// every subscriber sees every link.
192    ///
193    /// A side of a change the subscriber may not read is left out of its push,
194    /// so a link that becomes unreadable arrives as a deletion and one that
195    /// becomes readable as a creation. This is where a permission layer plugs in.
196    /// On a server in triplet mode `readable` judges the outer doublet of a
197    /// triplet, as `(index: type index)`.
198    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    /// The address the server listens on.
204    pub fn local_addr(&self) -> ProtocolResult<SocketAddr> {
205        Ok(self.listener.local_addr()?)
206    }
207
208    /// A handle that stops [`serve`](Self::serve).
209    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    /// Serves `storage` until a [`ShutdownHandle`] stops the server; every
218    /// connection sees and changes the whole store.
219    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    /// Serves the selected address type through the same request path.
227    /// Checked adapters may use a wider marker to retain their full stored range.
228    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    /// Serves `sessions` until a [`ShutdownHandle`] stops the server: every
287    /// connection is a session of its own, opened with the default subject
288    /// of `sessions` and closed when the connection closes (issue #149).
289    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
325/// Runs the jobs of [`LinksServer::serve`] and keeps the subscriptions of
326/// every connection.
327struct 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    /// Runs `job`; false once the server should stop.
343    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    /// Closes the session of every connection still open.
419    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
429/// The subscriptions of one connection, and the session its requests run
430/// as; only the serving thread touches them.
431struct 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    /// The reply to a `subscribe` or an `unsubscribe`; `None` for any other
449    /// request. Subscription numbers start at 1 on every connection.
450    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                // An unknown number is ignored.
471                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    /// Pushes `changes` to every subscription they fit, one `(notify: N)`
487    /// document each; a side that does not fit (or that `readable` refuses) is
488    /// left out, and a change left with no side is not pushed.
489    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    /// [`notify`](Self::notify) for the changes of a server in triplet mode.
516    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
547/// The documents waiting to be written to one connection, replies and pushes
548/// in one queue, so a push never interleaves with a reply and a slow
549/// subscriber never holds up the store.
550struct Outbox {
551    state: Mutex<OutboxState>,
552    changed: Condvar,
553    max_pending_notifications: usize,
554    /// Stops both threads of the connection.
555    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    /// Queues a reply; [`wait_for_replies`](Self::wait_for_replies) waits
583    /// until it is written.
584    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    /// Queues a push; closes the connection instead when too many are already
595    /// waiting, since a subscriber that does not read its pushes would make
596    /// the server hold every change for it. False once the outbox is closed.
597    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    /// Waits until every queued reply is written, so a client that never reads
615    /// its replies stops being read from, as before the server had pushes.
616    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    /// Writes the queue to `writer`, in order, until the outbox closes.
631    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            // The connection broke: its reader stops too.
635            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    /// Stops the outbox and hangs up; called again, it does nothing.
671    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    // Its subscriptions go with it.
739    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                    // The stream may be out of sync; answer in text and hang up.
767                    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            // Once `serve` returns, no request may touch the store.
782            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
801/// The reply document for a failed request: `(error: 'message')`.
802pub 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
809/// Returns the message of an `(error: 'message')` reply.
810pub 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;