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, subscription_document, Change, LinksOperation,
27    Part,
28};
29use super::protocols::{read_any_document, MessageFormat, ProtocolLimits};
30use super::sessions::{LinksSessions, SessionId};
31use super::triplets_operations::{
32    matches_triplet, pack_triplets, triplet_notification_document, TripletsOperation,
33};
34use crate::link::Link;
35use crate::named_type_links::NamedTypeLinks;
36use crate::permissions::AccessPolicy;
37use crate::query_processor::QueryProcessor;
38use crate::triplets::{Triplet, TripletChange};
39use links_notation::binary::{format_document, LinoDocument};
40use links_notation::LiNo;
41use std::collections::{BTreeMap, VecDeque};
42use std::fmt;
43use std::io::{self, BufReader, BufWriter, Write};
44use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
45use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
46use std::sync::mpsc::{self, Receiver, Sender};
47use std::sync::{Arc, Condvar, Mutex, MutexGuard};
48use std::thread;
49
50/// Which protocols a server accepts.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
52pub enum AcceptedProtocols {
53    /// Detect the protocol of every message (the default).
54    #[default]
55    Any,
56    /// Only [`TextLinoProtocol`](super::TextLinoProtocol) messages.
57    Text,
58    /// Only [`BinaryLinoProtocol`](super::BinaryLinoProtocol) messages.
59    Binary,
60}
61
62impl AcceptedProtocols {
63    fn accepts(self, format: MessageFormat) -> bool {
64        matches!(
65            (self, format),
66            (AcceptedProtocols::Any, _)
67                | (AcceptedProtocols::Text, MessageFormat::Text)
68                | (AcceptedProtocols::Binary, MessageFormat::Binary(_))
69        )
70    }
71}
72
73/// Server configuration.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub struct ServerOptions {
76    /// Print every request and reply to stderr.
77    pub trace: bool,
78    /// Passed to [`QueryProcessor::with_auto_create_missing_references`].
79    pub auto_create_missing_references: bool,
80    /// Protocols the server answers.
81    pub accept: AcceptedProtocols,
82    /// Limits applied to incoming messages.
83    pub limits: ProtocolLimits,
84    /// Pushes a connection may have waiting before the server closes it as
85    /// too slow to read them.
86    pub max_pending_notifications: usize,
87    /// Read every request as triplets (issue #152): `(create: (type from to))`
88    /// and the rest of [`TripletsOperation`], over a store of doublets. A server
89    /// without it answers as it always did.
90    pub triplets: bool,
91}
92
93/// The default of [`ServerOptions::max_pending_notifications`].
94pub const DEFAULT_MAX_PENDING_NOTIFICATIONS: usize = 1024;
95
96impl Default for ServerOptions {
97    fn default() -> Self {
98        Self {
99            trace: false,
100            auto_create_missing_references: false,
101            accept: AcceptedProtocols::default(),
102            limits: ProtocolLimits::default(),
103            max_pending_notifications: DEFAULT_MAX_PENDING_NOTIFICATIONS,
104            triplets: false,
105        }
106    }
107}
108
109/// Which links a subscriber may see: see [`LinksServer::with_readable`].
110pub type Readable = Box<dyn Fn(&Link) -> bool + Send>;
111
112enum Job {
113    /// A request of `connection`; its reply goes to `outbox`, and `done` is
114    /// signalled once it is there.
115    Request {
116        connection: u64,
117        outbox: Arc<Outbox>,
118        document: LinoDocument,
119        format: MessageFormat,
120        done: Sender<()>,
121    },
122    /// `connection` hung up: its subscriptions go with it.
123    Close(u64),
124    Shutdown,
125}
126
127/// Stops a running [`LinksServer::serve`] from another thread.
128#[derive(Clone, Debug)]
129pub struct ShutdownHandle {
130    jobs: Sender<Job>,
131    stopping: Arc<AtomicBool>,
132    address: SocketAddr,
133}
134
135impl ShutdownHandle {
136    /// Asks the server to stop; `serve` returns after the current request.
137    pub fn shutdown(&self) {
138        self.stopping.store(true, Ordering::SeqCst);
139        let _ = self.jobs.send(Job::Shutdown);
140        // Wake the accept loop so it notices the flag.
141        let _ = TcpStream::connect(self.address);
142    }
143}
144
145/// A bound, not yet serving, LiNo server.
146pub struct LinksServer {
147    listener: TcpListener,
148    options: ServerOptions,
149    readable: Option<Readable>,
150    jobs: Sender<Job>,
151    queue: Receiver<Job>,
152    stopping: Arc<AtomicBool>,
153}
154
155impl fmt::Debug for LinksServer {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        formatter
158            .debug_struct("LinksServer")
159            .field("listener", &self.listener)
160            .field("options", &self.options)
161            .field("readable", &self.readable.is_some())
162            .finish_non_exhaustive()
163    }
164}
165
166impl LinksServer {
167    /// Binds to `address` (use port `0` for an ephemeral port).
168    pub fn bind(address: impl ToSocketAddrs, options: ServerOptions) -> ProtocolResult<Self> {
169        let listener = TcpListener::bind(address)?;
170        let (jobs, queue) = mpsc::channel();
171        Ok(Self {
172            listener,
173            options,
174            readable: None,
175            jobs,
176            queue,
177            stopping: Arc::new(AtomicBool::new(false)),
178        })
179    }
180
181    /// Lets subscribers see only the links `readable` accepts; without it,
182    /// every subscriber sees every link.
183    ///
184    /// A side of a change the subscriber may not read is left out of its push,
185    /// so a link that becomes unreadable arrives as a deletion and one that
186    /// becomes readable as a creation. This is where a permission layer plugs in.
187    /// On a server in triplet mode `readable` judges the outer doublet of a
188    /// triplet, as `(index: type index)`.
189    pub fn with_readable(mut self, readable: impl Fn(&Link) -> bool + Send + 'static) -> Self {
190        self.readable = Some(Box::new(readable));
191        self
192    }
193
194    /// The address the server listens on.
195    pub fn local_addr(&self) -> ProtocolResult<SocketAddr> {
196        Ok(self.listener.local_addr()?)
197    }
198
199    /// A handle that stops [`serve`](Self::serve).
200    pub fn shutdown_handle(&self) -> ProtocolResult<ShutdownHandle> {
201        Ok(ShutdownHandle {
202            jobs: self.jobs.clone(),
203            stopping: Arc::clone(&self.stopping),
204            address: self.local_addr()?,
205        })
206    }
207
208    /// Serves `storage` until a [`ShutdownHandle`] stops the server; every
209    /// connection sees and changes the whole store.
210    pub fn serve<S: NamedTypeLinks>(self, storage: &mut S) -> ProtocolResult<()> {
211        let auto_create = self.options.auto_create_missing_references;
212        let mut sessions =
213            LinksSessions::new(storage).with_auto_create_missing_references(auto_create);
214        self.serve_sessions(&mut sessions)
215    }
216
217    /// Serves `sessions` until a [`ShutdownHandle`] stops the server: every
218    /// connection is a session of its own, opened with the default subject
219    /// of `sessions` and closed when the connection closes (issue #149).
220    pub fn serve_sessions<S: NamedTypeLinks, P: AccessPolicy>(
221        self,
222        sessions: &mut LinksSessions<S, P>,
223    ) -> ProtocolResult<()> {
224        let LinksServer {
225            listener,
226            options,
227            readable,
228            jobs,
229            queue,
230            stopping,
231        } = self;
232        if options.triplets {
233            sessions
234                .ensure_triplets()
235                .map_err(|error| io::Error::other(format!("{error:#}")))?;
236        }
237        let acceptor = {
238            let stopping = Arc::clone(&stopping);
239            thread::spawn(move || accept_loop(listener, jobs, stopping, options))
240        };
241        let mut dispatcher = Dispatcher::new(options, readable);
242        while let Ok(job) = queue.recv() {
243            if !dispatcher.run(sessions, job) {
244                break;
245            }
246        }
247        dispatcher.close_all(sessions);
248        stopping.store(true, Ordering::SeqCst);
249        drop(queue);
250        let _ = acceptor.join();
251        Ok(())
252    }
253}
254
255/// Runs the jobs of [`LinksServer::serve`] and keeps the subscriptions of
256/// every connection.
257struct Dispatcher {
258    options: ServerOptions,
259    readable: Option<Readable>,
260    connections: BTreeMap<u64, Connection>,
261}
262
263impl Dispatcher {
264    fn new(options: ServerOptions, readable: Option<Readable>) -> Self {
265        Self {
266            options,
267            readable,
268            connections: BTreeMap::new(),
269        }
270    }
271
272    /// Runs `job`; false once the server should stop.
273    fn run<S: NamedTypeLinks, P: AccessPolicy>(
274        &mut self,
275        sessions: &mut LinksSessions<S, P>,
276        job: Job,
277    ) -> bool {
278        match job {
279            Job::Shutdown => return false,
280            Job::Close(connection) => {
281                if let Some(closed) = self.connections.remove(&connection) {
282                    sessions.close(closed.session);
283                }
284            }
285            Job::Request {
286                connection,
287                outbox,
288                document,
289                format,
290                done,
291            } => {
292                if self.options.trace {
293                    eprintln!("[server] request: {}", format_document(&document));
294                }
295                let current = self
296                    .connections
297                    .entry(connection)
298                    .or_insert_with(|| Connection::new(outbox, sessions.open(None)));
299                let triplets = sessions.has_triplets();
300                let mut changes = Vec::new();
301                let mut triplet_changes = Vec::new();
302                let reply = current
303                    .execute(&document, format, triplets)
304                    .unwrap_or_else(|| {
305                        if triplets {
306                            sessions.execute_triplets_observed(
307                                current.session,
308                                &document,
309                                &mut triplet_changes,
310                            )
311                        } else {
312                            sessions.execute_observed(current.session, &document, &mut changes)
313                        }
314                    });
315                if self.options.trace {
316                    eprintln!("[server] reply: {}", format_document(&reply));
317                }
318                let reply = if triplets {
319                    pack_triplets(reply, format)
320                } else {
321                    reply
322                };
323                current.outbox.reply(reply, format);
324                let readable = self.readable.as_ref();
325                let others = self.connections.iter().filter(|(id, _)| **id != connection);
326                if !changes.is_empty() || !triplet_changes.is_empty() {
327                    for (_, other) in others {
328                        let session = other.session;
329                        let mut can_read = |link: &Link| {
330                            readable.is_none_or(|readable| readable(link))
331                                && sessions.can_read(session, link)
332                        };
333                        other.notify(&changes, &mut can_read);
334                        other.notify_triplets(&triplet_changes, &mut can_read);
335                    }
336                }
337                let _ = done.send(());
338            }
339        }
340        true
341    }
342
343    /// Closes the session of every connection still open.
344    fn close_all<S: NamedTypeLinks, P: AccessPolicy>(
345        &mut self,
346        sessions: &mut LinksSessions<S, P>,
347    ) {
348        for (_, connection) in std::mem::take(&mut self.connections) {
349            sessions.close(connection.session);
350        }
351    }
352}
353
354/// The subscriptions of one connection, and the session its requests run
355/// as; only the serving thread touches them.
356struct Connection {
357    outbox: Arc<Outbox>,
358    session: SessionId,
359    subscriptions: BTreeMap<u32, (Vec<Part>, MessageFormat)>,
360    next_subscription: u32,
361}
362
363impl Connection {
364    fn new(outbox: Arc<Outbox>, session: SessionId) -> Self {
365        Self {
366            outbox,
367            session,
368            subscriptions: BTreeMap::new(),
369            next_subscription: 1,
370        }
371    }
372
373    /// The reply to a `subscribe` or an `unsubscribe`; `None` for any other
374    /// request. Subscription numbers start at 1 on every connection.
375    fn execute(
376        &mut self,
377        document: &[LiNo<String>],
378        format: MessageFormat,
379        triplets: bool,
380    ) -> Option<LinoDocument> {
381        if triplets {
382            match TripletsOperation::from_document(document) {
383                Ok(Some(TripletsOperation::Subscribe(restriction))) => {
384                    return Some(self.subscribe(restriction, format));
385                }
386                Ok(None) => {}
387                Ok(Some(_)) | Err(_) => return None,
388            }
389        }
390        match LinksOperation::from_document(document) {
391            Ok(Some(LinksOperation::Subscribe(restriction))) => {
392                Some(self.subscribe(restriction, format))
393            }
394            Ok(Some(LinksOperation::Unsubscribe(subscription))) => {
395                // An unknown number is ignored.
396                self.subscriptions.remove(&subscription);
397                Some(Vec::new())
398            }
399            _ => None,
400        }
401    }
402
403    fn subscribe(&mut self, restriction: Vec<Part>, format: MessageFormat) -> LinoDocument {
404        let subscription = self.next_subscription;
405        self.next_subscription = self.next_subscription.wrapping_add(1);
406        self.subscriptions
407            .insert(subscription, (restriction, format));
408        subscription_document(subscription)
409    }
410
411    /// Pushes `changes` to every subscription they fit, one `(notify: N)`
412    /// document each; a side that does not fit (or that `readable` refuses) is
413    /// left out, and a change left with no side is not pushed.
414    fn notify(&self, changes: &[Change], readable: &mut dyn FnMut(&Link) -> bool) {
415        for (subscription, (restriction, format)) in &self.subscriptions {
416            let mut side = |link: &Link| {
417                if !link.is_null() && matches(link, restriction) && readable(link) {
418                    *link
419                } else {
420                    Link::null()
421                }
422            };
423            let seen: Vec<Change> = changes
424                .iter()
425                .map(|(before, after)| (side(before), side(after)))
426                .filter(|(before, after)| !before.is_null() || !after.is_null())
427                .collect();
428            if !seen.is_empty()
429                && !self
430                    .outbox
431                    .push(notification_document(*subscription, &seen), *format)
432            {
433                return;
434            }
435        }
436    }
437}
438
439impl Connection {
440    /// [`notify`](Self::notify) for the changes of a server in triplet mode.
441    fn notify_triplets(&self, changes: &[TripletChange], readable: &mut dyn FnMut(&Link) -> bool) {
442        if changes.is_empty() {
443            return;
444        }
445        for (subscription, (restriction, format)) in &self.subscriptions {
446            let mut side = |triplet: Option<Triplet>| {
447                triplet.filter(|triplet| {
448                    matches_triplet(triplet, restriction)
449                        && readable(&Link::new(triplet.index, triplet.type_id, triplet.index))
450                })
451            };
452            let seen: Vec<TripletChange> = changes
453                .iter()
454                .map(|change| TripletChange {
455                    before: side(change.before),
456                    after: side(change.after),
457                })
458                .filter(|change| change.before.is_some() || change.after.is_some())
459                .collect();
460            if !seen.is_empty()
461                && !self.outbox.push(
462                    pack_triplets(triplet_notification_document(*subscription, &seen), *format),
463                    *format,
464                )
465            {
466                return;
467            }
468        }
469    }
470}
471
472/// The documents waiting to be written to one connection, replies and pushes
473/// in one queue, so a push never interleaves with a reply and a slow
474/// subscriber never holds up the store.
475struct Outbox {
476    state: Mutex<OutboxState>,
477    changed: Condvar,
478    max_pending_notifications: usize,
479    /// Stops both threads of the connection.
480    hang_up: Box<dyn Fn() + Send + Sync>,
481}
482
483#[derive(Default)]
484struct OutboxState {
485    queue: VecDeque<(LinoDocument, MessageFormat, bool)>,
486    pending_replies: usize,
487    pending_notifications: usize,
488    closed: bool,
489}
490
491impl Outbox {
492    fn new(max_pending_notifications: usize, hang_up: Box<dyn Fn() + Send + Sync>) -> Self {
493        Self {
494            state: Mutex::default(),
495            changed: Condvar::new(),
496            max_pending_notifications,
497            hang_up,
498        }
499    }
500
501    fn lock(&self) -> MutexGuard<'_, OutboxState> {
502        self.state
503            .lock()
504            .unwrap_or_else(|poisoned| poisoned.into_inner())
505    }
506
507    /// Queues a reply; [`wait_for_replies`](Self::wait_for_replies) waits
508    /// until it is written.
509    fn reply(&self, document: LinoDocument, format: MessageFormat) {
510        let mut state = self.lock();
511        if state.closed {
512            return;
513        }
514        state.queue.push_back((document, format, true));
515        state.pending_replies += 1;
516        self.changed.notify_all();
517    }
518
519    /// Queues a push; closes the connection instead when too many are already
520    /// waiting, since a subscriber that does not read its pushes would make
521    /// the server hold every change for it. False once the outbox is closed.
522    fn push(&self, document: LinoDocument, format: MessageFormat) -> bool {
523        {
524            let mut state = self.lock();
525            if state.closed {
526                return false;
527            }
528            if state.pending_notifications < self.max_pending_notifications {
529                state.queue.push_back((document, format, false));
530                state.pending_notifications += 1;
531                self.changed.notify_all();
532                return true;
533            }
534        }
535        self.close();
536        false
537    }
538
539    /// Waits until every queued reply is written, so a client that never reads
540    /// its replies stops being read from, as before the server had pushes.
541    fn wait_for_replies(&self) {
542        let mut state = self.lock();
543        while state.pending_replies > 0 && !state.closed {
544            state = self
545                .changed
546                .wait(state)
547                .unwrap_or_else(|poisoned| poisoned.into_inner());
548        }
549    }
550
551    fn is_closed(&self) -> bool {
552        self.lock().closed
553    }
554
555    /// Writes the queue to `writer`, in order, until the outbox closes.
556    fn write_all(&self, writer: &mut impl Write, limits: ProtocolLimits) -> ProtocolResult<()> {
557        let result = self.try_write_all(writer, limits);
558        if result.is_err() {
559            // The connection broke: its reader stops too.
560            self.close();
561        }
562        result
563    }
564
565    fn try_write_all(&self, writer: &mut impl Write, limits: ProtocolLimits) -> ProtocolResult<()> {
566        loop {
567            let (document, format) = {
568                let mut state = self.lock();
569                while state.queue.is_empty() && !state.closed {
570                    state = self
571                        .changed
572                        .wait(state)
573                        .unwrap_or_else(|poisoned| poisoned.into_inner());
574                }
575                if state.closed {
576                    return Ok(());
577                }
578                let (document, format, _) = &state.queue[0];
579                (document.clone(), *format)
580            };
581            format.protocol(limits).write_document(writer, &document)?;
582            writer.flush()?;
583            let mut state = self.lock();
584            if let Some((_, _, reply)) = state.queue.pop_front() {
585                if reply {
586                    state.pending_replies -= 1;
587                } else {
588                    state.pending_notifications -= 1;
589                }
590            }
591            self.changed.notify_all();
592        }
593    }
594
595    /// Stops the outbox and hangs up; called again, it does nothing.
596    fn close(&self) {
597        {
598            let mut state = self.lock();
599            if state.closed {
600                return;
601            }
602            state.closed = true;
603            state.queue.clear();
604            self.changed.notify_all();
605        }
606        (self.hang_up)();
607    }
608}
609
610fn accept_loop(
611    listener: TcpListener,
612    jobs: Sender<Job>,
613    stopping: Arc<AtomicBool>,
614    options: ServerOptions,
615) {
616    for stream in listener.incoming() {
617        if stopping.load(Ordering::SeqCst) {
618            return;
619        }
620        let Ok(stream) = stream else { continue };
621        let jobs = jobs.clone();
622        thread::spawn(move || {
623            if let Err(error) = handle_connection(stream, jobs, options) {
624                if options.trace {
625                    eprintln!("[server] connection closed: {error}");
626                }
627            }
628        });
629    }
630}
631
632fn handle_connection(
633    stream: TcpStream,
634    jobs: Sender<Job>,
635    options: ServerOptions,
636) -> ProtocolResult<()> {
637    static CONNECTIONS: AtomicU64 = AtomicU64::new(0);
638    let connection = CONNECTIONS.fetch_add(1, Ordering::Relaxed);
639    let _ = stream.set_nodelay(true);
640    let outbox = {
641        let stream = stream.try_clone()?;
642        Arc::new(Outbox::new(
643            options.max_pending_notifications,
644            Box::new(move || {
645                let _ = stream.shutdown(Shutdown::Both);
646            }),
647        ))
648    };
649    let writer = {
650        let outbox = Arc::clone(&outbox);
651        let mut stream = BufWriter::new(stream.try_clone()?);
652        thread::spawn(move || {
653            if let Err(error) = outbox.write_all(&mut stream, options.limits) {
654                if options.trace {
655                    eprintln!("[server] connection closed: {error}");
656                }
657            }
658        })
659    };
660    let result = serve_connection(stream, connection, &outbox, &jobs, options);
661    // Its subscriptions go with it.
662    let _ = jobs.send(Job::Close(connection));
663    outbox.close();
664    let _ = writer.join();
665    result
666}
667
668fn serve_connection(
669    stream: TcpStream,
670    connection: u64,
671    outbox: &Arc<Outbox>,
672    jobs: &Sender<Job>,
673    options: ServerOptions,
674) -> ProtocolResult<()> {
675    let mut reader = BufReader::new(stream);
676    loop {
677        let (document, format) = match read_any_document(&mut reader, &options.limits) {
678            Ok(Some(message)) => message,
679            Ok(None) => {
680                if options.trace {
681                    eprintln!("[server] client hung up");
682                }
683                return Ok(());
684            }
685            Err(_) if outbox.is_closed() => return Ok(()),
686            Err(error) => {
687                // The stream may be out of sync; answer in text and hang up.
688                outbox.reply(error_document(&error.to_string()), MessageFormat::Text);
689                outbox.wait_for_replies();
690                return Err(error);
691            }
692        };
693        if options.accept.accepts(format) {
694            let (done, finished) = mpsc::channel();
695            let job = Job::Request {
696                connection,
697                outbox: Arc::clone(outbox),
698                document,
699                format,
700                done,
701            };
702            // Once `serve` returns, no request may touch the store.
703            if jobs.send(job).is_err() || finished.recv().is_err() {
704                outbox.reply(error_document("server is shutting down"), format);
705            }
706        } else {
707            outbox.reply(
708                error_document("this server does not accept this protocol"),
709                format,
710            );
711        }
712        outbox.wait_for_replies();
713        if outbox.is_closed() {
714            if options.trace {
715                eprintln!("[server] connection closed");
716            }
717            return Ok(());
718        }
719    }
720}
721
722/// The reply document for a failed request: `(error: 'message')`.
723pub fn error_document(message: &str) -> LinoDocument {
724    vec![LiNo::Link {
725        id: Some("error".to_string()),
726        values: vec![LiNo::Ref(message.to_string())],
727    }]
728}
729
730/// Returns the message of an `(error: 'message')` reply.
731pub fn error_message(document: &[LiNo<String>]) -> Option<&str> {
732    match document {
733        [LiNo::Link {
734            id: Some(id),
735            values,
736        }] if id == "error" => match values.as_slice() {
737            [LiNo::Ref(message)] => Some(message),
738            _ => None,
739        },
740        _ => None,
741    }
742}
743
744/// Executes one request against `storage`.
745///
746/// A non-empty document is a substitution query; the reply holds one
747/// `(before) (after)` line per change, exactly like `clink --changes`. The
748/// empty document asks for every link, one `(index: source target)` per line.
749/// Failures produce an [`error_document`].
750pub fn execute_request<S: NamedTypeLinks>(
751    storage: &mut S,
752    processor: &QueryProcessor,
753    document: &[LiNo<String>],
754) -> LinoDocument {
755    execute_observed_request(storage, processor, document, &mut Vec::new())
756}
757
758/// Like [`execute_request`], adding the net change of every link the request
759/// changed to `changed`, with plain numbers.
760pub(super) fn execute_observed_request<S: NamedTypeLinks>(
761    storage: &mut S,
762    processor: &QueryProcessor,
763    document: &[LiNo<String>],
764    changed: &mut Vec<Change>,
765) -> LinoDocument {
766    match try_execute_request(storage, processor, document, changed) {
767        Ok(reply) => reply,
768        Err(error) => error_document(&format!("{error:#}")),
769    }
770}
771
772fn try_execute_request<S: NamedTypeLinks>(
773    storage: &mut S,
774    processor: &QueryProcessor,
775    document: &[LiNo<String>],
776    changed: &mut Vec<Change>,
777) -> anyhow::Result<LinoDocument> {
778    if let Some(operation) = LinksOperation::from_document(document)? {
779        let reply = operation.execute(storage)?;
780        if matches!(
781            operation,
782            LinksOperation::Create { .. }
783                | LinksOperation::Update { .. }
784                | LinksOperation::Delete(_)
785        ) {
786            changed.extend(parse_changes(&reply)?);
787        }
788        return Ok(reply);
789    }
790    if document.is_empty() {
791        let mut links = storage.all_links();
792        links.sort_by_key(|link| link.index);
793        return links.iter().map(|link| link_lino(storage, link)).collect();
794    }
795    let changes = processor.process_query(storage, &format_document(document))?;
796    changed.extend(changes.iter().map(|(before, after)| {
797        (
798            before.unwrap_or_else(Link::null),
799            after.unwrap_or_else(Link::null),
800        )
801    }));
802    if !changes.is_empty() {
803        storage.save()?;
804    }
805    changes
806        .iter()
807        .map(|(before, after)| {
808            Ok(LiNo::Link {
809                id: None,
810                values: vec![
811                    change_side(storage, before.as_ref())?,
812                    change_side(storage, after.as_ref())?,
813                ],
814            })
815        })
816        .collect()
817}
818
819/// `(index: source target)`, naming every reference that has a name.
820fn link_lino<S: NamedTypeLinks>(storage: &mut S, link: &Link) -> anyhow::Result<LiNo<String>> {
821    Ok(LiNo::Link {
822        id: Some(reference_name(storage, link.index)?),
823        values: vec![
824            LiNo::Ref(reference_name(storage, link.source)?),
825            LiNo::Ref(reference_name(storage, link.target)?),
826        ],
827    })
828}
829
830/// `()` for a missing side of a change, `((index: source target))` otherwise.
831fn change_side<S: NamedTypeLinks>(
832    storage: &mut S,
833    link: Option<&Link>,
834) -> anyhow::Result<LiNo<String>> {
835    let values = match link {
836        Some(link) => vec![link_lino(storage, link)?],
837        None => Vec::new(),
838    };
839    Ok(LiNo::Link { id: None, values })
840}
841
842pub(super) fn reference_name<S: NamedTypeLinks + ?Sized>(
843    storage: &mut S,
844    id: u32,
845) -> anyhow::Result<String> {
846    Ok(storage.get_name(id)?.unwrap_or_else(|| id.to_string()))
847}
848
849#[cfg(test)]
850mod tests {
851    use super::*;
852    use crate::link_storage::LinkStorage;
853    use links_notation::binary::parse_document;
854
855    fn outbox() -> Arc<Outbox> {
856        Arc::new(Outbox::new(
857            DEFAULT_MAX_PENDING_NOTIFICATIONS,
858            Box::new(|| {}),
859        ))
860    }
861
862    fn request(
863        dispatcher: &mut Dispatcher,
864        sessions: &mut LinksSessions<LinkStorage>,
865        connection: u64,
866        outbox: &Arc<Outbox>,
867        text: &str,
868    ) {
869        let (done, finished) = mpsc::channel();
870        let job = Job::Request {
871            connection,
872            outbox: Arc::clone(outbox),
873            document: parse_document(text).unwrap(),
874            format: MessageFormat::Text,
875            done,
876        };
877        assert!(dispatcher.run(sessions, job));
878        finished.recv().unwrap();
879    }
880
881    fn queued(outbox: &Outbox) -> Vec<String> {
882        outbox
883            .lock()
884            .queue
885            .drain(..)
886            .map(|(document, _, _)| format_document(&document))
887            .collect()
888    }
889
890    #[test]
891    fn closing_a_connection_drops_its_subscriptions() {
892        let database = tempfile::NamedTempFile::new().unwrap();
893        let storage = LinkStorage::new(database.path(), false).unwrap();
894        let mut sessions = LinksSessions::new(storage);
895        let mut dispatcher = Dispatcher::new(ServerOptions::default(), None);
896        let (subscriber, writer) = (outbox(), outbox());
897
898        request(
899            &mut dispatcher,
900            &mut sessions,
901            1,
902            &subscriber,
903            "(subscribe: ())",
904        );
905        request(
906            &mut dispatcher,
907            &mut sessions,
908            2,
909            &writer,
910            "(create: (0 0))",
911        );
912        assert_eq!(dispatcher.connections.len(), 2);
913        assert_eq!(sessions.sessions().len(), 2);
914        assert_eq!(
915            queued(&subscriber),
916            ["(subscription: 1)", "(notify: 1)\n() ((1: 0 0))"]
917        );
918        // A connection is never told about its own writes.
919        assert_eq!(queued(&writer), ["() ((1: 0 0))"]);
920
921        assert!(dispatcher.run(&mut sessions, Job::Close(1)));
922        assert_eq!(dispatcher.connections.keys().collect::<Vec<_>>(), [&2]);
923        // Its session is closed with it.
924        assert_eq!(sessions.sessions().len(), 1);
925        request(
926            &mut dispatcher,
927            &mut sessions,
928            2,
929            &writer,
930            "(create: (1 1))",
931        );
932        assert!(queued(&subscriber).is_empty());
933        assert!(!dispatcher.run(&mut sessions, Job::Shutdown));
934        dispatcher.close_all(&mut sessions);
935        assert!(sessions.sessions().is_empty());
936    }
937}