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 and formats
4//! messages; 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
9use super::error::ProtocolResult;
10use super::links_operations::LinksOperation;
11use super::protocols::{read_any_document, MessageFormat, ProtocolLimits};
12use crate::link::Link;
13use crate::named_type_links::NamedTypeLinks;
14use crate::query_processor::QueryProcessor;
15use links_notation::binary::{format_document, LinoDocument};
16use links_notation::LiNo;
17use std::io::{BufReader, BufWriter, Write};
18use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::mpsc::{self, Receiver, Sender};
21use std::sync::Arc;
22use std::thread;
23
24/// Which protocols a server accepts.
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26pub enum AcceptedProtocols {
27    /// Detect the protocol of every message (the default).
28    #[default]
29    Any,
30    /// Only [`TextLinoProtocol`](super::TextLinoProtocol) messages.
31    Text,
32    /// Only [`BinaryLinoProtocol`](super::BinaryLinoProtocol) messages.
33    Binary,
34}
35
36impl AcceptedProtocols {
37    fn accepts(self, format: MessageFormat) -> bool {
38        matches!(
39            (self, format),
40            (AcceptedProtocols::Any, _)
41                | (AcceptedProtocols::Text, MessageFormat::Text)
42                | (AcceptedProtocols::Binary, MessageFormat::Binary(_))
43        )
44    }
45}
46
47/// Server configuration.
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
49pub struct ServerOptions {
50    /// Print every request and reply to stderr.
51    pub trace: bool,
52    /// Passed to [`QueryProcessor::with_auto_create_missing_references`].
53    pub auto_create_missing_references: bool,
54    /// Protocols the server answers.
55    pub accept: AcceptedProtocols,
56    /// Limits applied to incoming messages.
57    pub limits: ProtocolLimits,
58}
59
60enum Job {
61    Request {
62        document: LinoDocument,
63        reply: Sender<LinoDocument>,
64    },
65    Shutdown,
66}
67
68/// Stops a running [`LinksServer::serve`] from another thread.
69#[derive(Clone, Debug)]
70pub struct ShutdownHandle {
71    jobs: Sender<Job>,
72    stopping: Arc<AtomicBool>,
73    address: SocketAddr,
74}
75
76impl ShutdownHandle {
77    /// Asks the server to stop; `serve` returns after the current request.
78    pub fn shutdown(&self) {
79        self.stopping.store(true, Ordering::SeqCst);
80        let _ = self.jobs.send(Job::Shutdown);
81        // Wake the accept loop so it notices the flag.
82        let _ = TcpStream::connect(self.address);
83    }
84}
85
86/// A bound, not yet serving, LiNo server.
87#[derive(Debug)]
88pub struct LinksServer {
89    listener: TcpListener,
90    options: ServerOptions,
91    jobs: Sender<Job>,
92    queue: Receiver<Job>,
93    stopping: Arc<AtomicBool>,
94}
95
96impl LinksServer {
97    /// Binds to `address` (use port `0` for an ephemeral port).
98    pub fn bind(address: impl ToSocketAddrs, options: ServerOptions) -> ProtocolResult<Self> {
99        let listener = TcpListener::bind(address)?;
100        let (jobs, queue) = mpsc::channel();
101        Ok(Self {
102            listener,
103            options,
104            jobs,
105            queue,
106            stopping: Arc::new(AtomicBool::new(false)),
107        })
108    }
109
110    /// The address the server listens on.
111    pub fn local_addr(&self) -> ProtocolResult<SocketAddr> {
112        Ok(self.listener.local_addr()?)
113    }
114
115    /// A handle that stops [`serve`](Self::serve).
116    pub fn shutdown_handle(&self) -> ProtocolResult<ShutdownHandle> {
117        Ok(ShutdownHandle {
118            jobs: self.jobs.clone(),
119            stopping: Arc::clone(&self.stopping),
120            address: self.local_addr()?,
121        })
122    }
123
124    /// Serves `storage` until a [`ShutdownHandle`] stops the server.
125    pub fn serve<S: NamedTypeLinks>(self, storage: &mut S) -> ProtocolResult<()> {
126        let LinksServer {
127            listener,
128            options,
129            jobs,
130            queue,
131            stopping,
132        } = self;
133        let acceptor = {
134            let stopping = Arc::clone(&stopping);
135            thread::spawn(move || accept_loop(listener, jobs, stopping, options))
136        };
137        let processor = QueryProcessor::new(false)
138            .with_auto_create_missing_references(options.auto_create_missing_references);
139        while let Ok(job) = queue.recv() {
140            match job {
141                Job::Shutdown => break,
142                Job::Request { document, reply } => {
143                    if options.trace {
144                        eprintln!("[server] request: {}", format_document(&document));
145                    }
146                    let response = execute_request(storage, &processor, &document);
147                    if options.trace {
148                        eprintln!("[server] reply: {}", format_document(&response));
149                    }
150                    let _ = reply.send(response);
151                }
152            }
153        }
154        stopping.store(true, Ordering::SeqCst);
155        drop(queue);
156        let _ = acceptor.join();
157        Ok(())
158    }
159}
160
161fn accept_loop(
162    listener: TcpListener,
163    jobs: Sender<Job>,
164    stopping: Arc<AtomicBool>,
165    options: ServerOptions,
166) {
167    for stream in listener.incoming() {
168        if stopping.load(Ordering::SeqCst) {
169            return;
170        }
171        let Ok(stream) = stream else { continue };
172        let jobs = jobs.clone();
173        thread::spawn(move || {
174            if let Err(error) = handle_connection(stream, jobs, options) {
175                if options.trace {
176                    eprintln!("[server] connection closed: {error}");
177                }
178            }
179        });
180    }
181}
182
183fn handle_connection(
184    stream: TcpStream,
185    jobs: Sender<Job>,
186    options: ServerOptions,
187) -> ProtocolResult<()> {
188    let _ = stream.set_nodelay(true);
189    let mut writer = BufWriter::new(stream.try_clone()?);
190    let mut reader = BufReader::new(stream);
191    loop {
192        let (document, format) = match read_any_document(&mut reader, &options.limits) {
193            Ok(Some(message)) => message,
194            Ok(None) => {
195                if options.trace {
196                    eprintln!("[server] client hung up");
197                }
198                return Ok(());
199            }
200            Err(error) => {
201                // The stream may be out of sync; answer in text and hang up.
202                let reply = error_document(&error.to_string());
203                let _ = MessageFormat::Text
204                    .protocol(options.limits)
205                    .write_document(&mut writer, &reply);
206                return Err(error);
207            }
208        };
209        let response = if options.accept.accepts(format) {
210            let (reply, response) = mpsc::channel();
211            // Once `serve` returns, no request may touch the store.
212            jobs.send(Job::Request { document, reply })
213                .ok()
214                .and_then(|()| response.recv().ok())
215                .unwrap_or_else(|| error_document("server is shutting down"))
216        } else {
217            error_document("this server does not accept this protocol")
218        };
219        format
220            .protocol(options.limits)
221            .write_document(&mut writer, &response)?;
222        writer.flush()?;
223    }
224}
225
226/// The reply document for a failed request: `(error: 'message')`.
227pub fn error_document(message: &str) -> LinoDocument {
228    vec![LiNo::Link {
229        id: Some("error".to_string()),
230        values: vec![LiNo::Ref(message.to_string())],
231    }]
232}
233
234/// Returns the message of an `(error: 'message')` reply.
235pub fn error_message(document: &[LiNo<String>]) -> Option<&str> {
236    match document {
237        [LiNo::Link {
238            id: Some(id),
239            values,
240        }] if id == "error" => match values.as_slice() {
241            [LiNo::Ref(message)] => Some(message),
242            _ => None,
243        },
244        _ => None,
245    }
246}
247
248/// Executes one request against `storage`.
249///
250/// A non-empty document is a substitution query; the reply holds one
251/// `(before) (after)` line per change, exactly like `clink --changes`. The
252/// empty document asks for every link, one `(index: source target)` per line.
253/// Failures produce an [`error_document`].
254pub fn execute_request<S: NamedTypeLinks>(
255    storage: &mut S,
256    processor: &QueryProcessor,
257    document: &[LiNo<String>],
258) -> LinoDocument {
259    match try_execute_request(storage, processor, document) {
260        Ok(reply) => reply,
261        Err(error) => error_document(&format!("{error:#}")),
262    }
263}
264
265fn try_execute_request<S: NamedTypeLinks>(
266    storage: &mut S,
267    processor: &QueryProcessor,
268    document: &[LiNo<String>],
269) -> anyhow::Result<LinoDocument> {
270    if let Some(operation) = LinksOperation::from_document(document)? {
271        return operation.execute(storage);
272    }
273    if document.is_empty() {
274        let mut links = storage.all_links();
275        links.sort_by_key(|link| link.index);
276        return links.iter().map(|link| link_lino(storage, link)).collect();
277    }
278    let changes = processor.process_query(storage, &format_document(document))?;
279    if !changes.is_empty() {
280        storage.save()?;
281    }
282    changes
283        .iter()
284        .map(|(before, after)| {
285            Ok(LiNo::Link {
286                id: None,
287                values: vec![
288                    change_side(storage, before.as_ref())?,
289                    change_side(storage, after.as_ref())?,
290                ],
291            })
292        })
293        .collect()
294}
295
296/// `(index: source target)`, naming every reference that has a name.
297fn link_lino<S: NamedTypeLinks>(storage: &mut S, link: &Link) -> anyhow::Result<LiNo<String>> {
298    Ok(LiNo::Link {
299        id: Some(reference_name(storage, link.index)?),
300        values: vec![
301            LiNo::Ref(reference_name(storage, link.source)?),
302            LiNo::Ref(reference_name(storage, link.target)?),
303        ],
304    })
305}
306
307/// `()` for a missing side of a change, `((index: source target))` otherwise.
308fn change_side<S: NamedTypeLinks>(
309    storage: &mut S,
310    link: Option<&Link>,
311) -> anyhow::Result<LiNo<String>> {
312    let values = match link {
313        Some(link) => vec![link_lino(storage, link)?],
314        None => Vec::new(),
315    };
316    Ok(LiNo::Link { id: None, values })
317}
318
319fn reference_name<S: NamedTypeLinks>(storage: &mut S, id: u32) -> anyhow::Result<String> {
320    Ok(storage.get_name(id)?.unwrap_or_else(|| id.to_string()))
321}