rpc-io 0.2.0

JSON-RPC 2.0 engine with Content-Length and newline framings, a sans-IO core, and a blocking adapter: one transport for LSP, DAP, MCP, and service APIs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! The state an endpoint shares with its handles ([`Peer`](crate::Peer),
//! [`Call`](crate::Call), [`Responder`](crate::Responder)): the sink, our
//! outstanding requests, the peer's deferred requests, open batches, and the
//! gate.
//!
//! Everything sits behind one mutex. Handles on other threads send through it
//! directly, so a deferred reply or a notification from a worker goes out at
//! once, even while the endpoint's own thread is blocked reading. The lock is
//! held only to encode and hand a message to the sink, never while user code
//! (a handler or event hook) runs. One connection's traffic is serial on the
//! wire anyway, so a single lock costs nothing a lock-free design would save.

use std::{
    collections::{BTreeMap, BTreeSet},
    io, mem,
    panic::{self, AssertUnwindSafe},
    sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc},
    thread::{self, ThreadId},
    time::{Duration, Instant},
};

use crate::{
    config::{Cancellation, Config},
    error::{CallError, Error},
    error_object::ErrorObject,
    handles::CancelToken,
    id::Id,
    message::{write_call, write_numbered_call, write_response},
    pending::Pending,
    raw::{Json, Raw},
    sink::Sink,
    text,
};

/// How one of our requests ended.
pub(crate) type Outcome = Result<Raw<'static>, CallError>;

/// What the handles need from the shared state, with the sink type erased.
pub(crate) trait Link: Send + Sync {
    fn notify(&self, method: &str, params: Option<&Json<'_>>) -> Result<(), Error>;
    fn request(
        &self,
        method: &str,
        params: Option<&Json<'_>>,
        timeout: Option<Duration>,
    ) -> Result<Issued, Error>;
    fn cancel(&self, id: u64) -> bool;
    fn expire(&self);
    fn respond(
        &self,
        id: &Id<'static>,
        result: Result<&Json<'_>, &ErrorObject>,
    ) -> Result<(), Error>;
    fn on_endpoint_thread(&self) -> bool;
    fn is_closed(&self) -> bool;
}

/// A request just sent: its id, where its outcome arrives, its deadline.
pub(crate) struct Issued {
    pub(crate) id: u64,
    pub(crate) outcome: mpsc::Receiver<Outcome>,
    pub(crate) deadline: Option<Instant>,
}

pub(crate) struct Shared<K> {
    inner: Mutex<Inner<K>>,
}

impl<K: Sink> Shared<K> {
    pub(crate) fn new(sink: K, config: &Config) -> Arc<Self> {
        Arc::new(Self {
            inner: Mutex::new(Inner {
                sink,
                closed: false,
                broken: None,
                corked: false,
                scratch: String::new(),
                pending: Pending::new(config.max_pending),
                in_flight: BTreeMap::new(),
                batches: BTreeMap::new(),
                next_batch: 0,
                gate: if config.gate.is_some() {
                    GateState::Closed
                } else {
                    GateState::Open
                },
                held: Vec::new(),
                held_requests: BTreeSet::new(),
                settings: Settings::from(config),
                epoch: Instant::now(),
                endpoint_thread: None,
            }),
        })
    }

    /// The state. A panic while it was locked can only have come from a
    /// [`Sink`]; the state is still usable, so the poison is ignored.
    pub(crate) fn lock(&self) -> MutexGuard<'_, Inner<K>> {
        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

impl<K: Sink> Link for Shared<K> {
    fn notify(&self, method: &str, params: Option<&Json<'_>>) -> Result<(), Error> {
        self.lock().notify(method, params)
    }

    fn request(
        &self,
        method: &str,
        params: Option<&Json<'_>>,
        timeout: Option<Duration>,
    ) -> Result<Issued, Error> {
        self.lock().request(method, params, timeout)
    }

    fn cancel(&self, id: u64) -> bool {
        self.lock().cancel_outgoing(id)
    }

    fn expire(&self) {
        self.lock().expire();
    }

    fn respond(
        &self,
        id: &Id<'static>,
        result: Result<&Json<'_>, &ErrorObject>,
    ) -> Result<(), Error> {
        self.lock().respond_deferred(id, result)
    }

    fn on_endpoint_thread(&self) -> bool {
        self.lock().endpoint_thread == Some(thread::current().id())
    }

    fn is_closed(&self) -> bool {
        self.lock().closed
    }
}

/// The settings the shared state applies.
pub(crate) struct Settings {
    pub(crate) cancellation: Option<Cancellation>,
    pub(crate) request_timeout: Option<Duration>,
    pub(crate) max_in_flight: usize,
}

impl From<&Config> for Settings {
    fn from(config: &Config) -> Self {
        Self {
            cancellation: config.cancellation.clone(),
            request_timeout: config.request_timeout,
            max_in_flight: config.max_in_flight,
        }
    }
}

/// Where the gate is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum GateState {
    /// No gate, or the opening request succeeded.
    Open,
    /// Waiting for the opening request.
    Closed,
    /// The opening request with this id is being answered.
    Opening(Id<'static>),
}

/// A peer request answered later through a [`Responder`](crate::Responder).
struct InFlight {
    token: CancelToken,
    batch: Option<u64>,
}

/// A batch being answered: responses so far, and how many are still owed.
struct Batch {
    remaining: usize,
    body: String,
}

/// A message held back until the gate opens.
struct Held {
    request: Option<u64>,
    body: String,
}

/// What a message is, for the gate.
#[derive(Clone, Copy)]
enum Sending {
    Response,
    Notification,
    Request(u64),
}

pub(crate) struct Inner<K> {
    sink: K,
    closed: bool,
    /// The first failure of the sink, for the endpoint's thread to report.
    broken: Option<io::Error>,
    /// While set (the endpoint is handling a message), the sink is flushed at
    /// the end of the turn instead of after each message.
    corked: bool,
    /// Reused buffer every message is encoded in.
    scratch: String,
    pending: Pending<mpsc::Sender<Outcome>>,
    in_flight: BTreeMap<Id<'static>, InFlight>,
    batches: BTreeMap<u64, Batch>,
    next_batch: u64,
    pub(crate) gate: GateState,
    held: Vec<Held>,
    /// Ids of our requests in `held` and not abandoned since: lookups stay
    /// `O(log n)` however much is held.
    held_requests: BTreeSet<u64>,
    pub(crate) settings: Settings,
    epoch: Instant,
    /// The thread inside the endpoint's `handle` or `run`, if any.
    pub(crate) endpoint_thread: Option<ThreadId>,
}

impl<K: Sink> Inner<K> {
    pub(crate) fn sink_mut(&mut self) -> &mut K {
        &mut self.sink
    }

    pub(crate) fn is_closed(&self) -> bool {
        self.closed
    }

    /// Replaces the settings and the capacity of the pending map (kept if
    /// requests are already outstanding).
    pub(crate) fn configure(&mut self, config: &Config) {
        self.settings = Settings::from(config);
        if self.pending.is_empty() {
            self.pending = Pending::new(config.max_pending);
        }
        if config.gate.is_none() {
            self.gate = GateState::Open;
        } else if self.gate == GateState::Open && self.held.is_empty() {
            self.gate = GateState::Closed;
        }
    }

    fn now(&self) -> Duration {
        self.epoch.elapsed()
    }

    /// When the earliest outstanding request is due.
    pub(crate) fn next_deadline(&self) -> Option<Instant> {
        self.pending
            .next_deadline()
            .and_then(|at| self.epoch.checked_add(at))
    }

    pub(crate) fn cork(&mut self) {
        self.corked = true;
    }

    /// Whether the calling thread is the one inside the endpoint's turn.
    fn on_endpoint_thread(&self) -> bool {
        self.endpoint_thread == Some(thread::current().id())
    }

    /// Ends a turn: everything sent during it goes out.
    pub(crate) fn uncork(&mut self) {
        self.corked = false;
        if !self.closed {
            if let Err(error) = guard(|| self.sink.flush()) {
                let _closed = self.fail(error);
            }
        }
    }

    /// The sink's first failure, once.
    pub(crate) fn take_broken(&mut self) -> Option<io::Error> {
        self.broken.take()
    }

    /// Closes the connection: flushes, then tells every waiter it is over.
    pub(crate) fn close(&mut self) {
        if self.closed {
            return;
        }
        if let Err(error) = guard(|| self.sink.flush()) {
            let _closed = self.fail(error);
        }
        self.shut();
    }

    /// Marks the connection closed and releases everything waiting on it.
    fn shut(&mut self) {
        self.closed = true;
        for (_, waiter) in self.pending.drain() {
            // A waiter that dropped its `Call` has nothing to be told.
            let _gone = waiter.send(Err(CallError::Closed));
        }
        for (_, request) in mem::take(&mut self.in_flight) {
            // Workers still answering see the cancellation and can stop.
            request.token.cancel();
        }
        self.batches.clear();
        self.held.clear();
        self.held_requests.clear();
    }

    /// Records a sink failure and closes; returns the error for the sender.
    fn fail(&mut self, error: io::Error) -> Error {
        let copy = io::Error::new(error.kind(), error.to_string());
        if self.broken.is_none() {
            self.broken = Some(error);
        }
        self.shut();
        Error::Io(copy)
    }

    /// Sends the message in `scratch`, or holds it while the gate is shut.
    fn deliver(&mut self, sending: Sending) -> Result<(), Error> {
        if self.closed {
            return Err(Error::Closed);
        }
        if self.gate != GateState::Open && !matches!(sending, Sending::Response) {
            let request = match sending {
                Sending::Request(id) => Some(id),
                _ => None,
            };
            if let Some(id) = request {
                let _fresh = self.held_requests.insert(id);
            }
            self.held.push(Held {
                request,
                body: self.scratch.clone(),
            });
            return Ok(());
        }
        let mut sent = guard(|| self.sink.send(&self.scratch));
        // Inside a turn the endpoint flushes once at its end; a message from
        // any other thread (a worker answering, a progress report) must not
        // wait for a handler that may run for seconds.
        if sent.is_ok() && (!self.corked || !self.on_endpoint_thread()) {
            sent = guard(|| self.sink.flush());
        }
        sent.map_err(|error| self.fail(error))
    }

    pub(crate) fn notify(&mut self, method: &str, params: Option<&Json<'_>>) -> Result<(), Error> {
        if self.closed {
            return Err(Error::Closed);
        }
        self.scratch.clear();
        write_call(&mut self.scratch, None, method, params);
        self.deliver(Sending::Notification)
    }

    pub(crate) fn request(
        &mut self,
        method: &str,
        params: Option<&Json<'_>>,
        timeout: Option<Duration>,
    ) -> Result<Issued, Error> {
        if self.closed {
            return Err(Error::Closed);
        }
        self.expire();
        let (waiter, outcome) = mpsc::channel();
        let deadline = timeout
            .or(self.settings.request_timeout)
            .and_then(|t| self.now().checked_add(t));
        let (id, evicted) = self.pending.issue(waiter, deadline);
        if let Some((oldest, waiter)) = evicted {
            self.abandon(oldest, waiter, CallError::Evicted);
        }
        self.scratch.clear();
        write_numbered_call(&mut self.scratch, id, method, params);
        if let Err(error) = self.deliver(Sending::Request(id)) {
            let _unsent = self.pending.settle(id);
            return Err(error);
        }
        Ok(Issued {
            id,
            outcome,
            deadline: deadline.and_then(|at| self.epoch.checked_add(at)),
        })
    }

    /// Ends every request whose deadline has passed with `TimedOut`.
    pub(crate) fn expire(&mut self) {
        let now = self.now();
        while let Some((id, waiter)) = self.pending.pop_expired(now) {
            self.abandon(id, waiter, CallError::TimedOut);
        }
    }

    pub(crate) fn cancel_outgoing(&mut self, id: u64) -> bool {
        match self.pending.settle(id) {
            Some(waiter) => {
                self.abandon(id, waiter, CallError::Cancelled);
                true
            }
            None => false,
        }
    }

    /// Delivers the answer to request `id`; `false` if it is not outstanding,
    /// or is still held behind the gate (the peer has never seen it, so the
    /// "answer" is forged or confused).
    pub(crate) fn settle(&mut self, id: u64, outcome: Outcome) -> bool {
        if self.held_requests.contains(&id) {
            return false;
        }
        match self.pending.settle(id) {
            Some(waiter) => {
                // A waiter that dropped its `Call` did not want the answer.
                let _gone = waiter.send(outcome);
                true
            }
            None => false,
        }
    }

    /// Ends a request removed from `pending` without an answer: tells the peer
    /// to stop (unless it was never sent), and tells the waiter why.
    fn abandon(&mut self, id: u64, waiter: mpsc::Sender<Outcome>, reason: CallError) {
        // Never sent: its held body is skipped when the gate opens, and the
        // peer has nothing to cancel.
        if !self.held_requests.remove(&id) && !self.closed {
            self.send_cancel(id);
        }
        let _gone = waiter.send(Err(reason));
    }

    /// Sends the cancel notification for our request `id`. Best effort: if
    /// the transport has failed, the request is moot anyway.
    fn send_cancel(&mut self, id: u64) {
        let Some(cancellation) = &self.settings.cancellation else {
            return;
        };
        self.scratch.clear();
        self.scratch.push_str("{\"jsonrpc\":\"2.0\",\"method\":");
        jsonx_lib::write_string(&mut self.scratch, &cancellation.method);
        self.scratch.push_str(",\"params\":{");
        jsonx_lib::write_string(&mut self.scratch, &cancellation.id_member);
        self.scratch.push(':');
        text::push_u64(&mut self.scratch, id);
        self.scratch.push_str("}}");
        let _best_effort = self.deliver(Sending::Notification);
    }

    /// Answers a peer request (or a malformed message) now.
    pub(crate) fn respond(
        &mut self,
        id: Option<&Id<'_>>,
        batch: Option<u64>,
        result: Result<&Json<'_>, &ErrorObject>,
    ) -> Result<(), Error> {
        if self.closed {
            return Err(Error::Closed);
        }
        self.scratch.clear();
        write_response(&mut self.scratch, id, result);
        let opening = match (&self.gate, id) {
            (GateState::Opening(opening), Some(id)) => opening == id,
            _ => false,
        };
        let sent = match batch {
            Some(batch) => self.add_to_batch(batch, true),
            None => self.deliver(Sending::Response),
        };
        if opening {
            self.settle_gate(result.is_ok());
        }
        sent
    }

    /// Adds the response in `scratch` (or, for a silently cancelled request,
    /// nothing) to `batch`; sends the batch once nothing more is owed.
    fn add_to_batch(&mut self, batch: u64, with_response: bool) -> Result<(), Error> {
        let Some(open) = self.batches.get_mut(&batch) else {
            return Ok(());
        };
        if with_response {
            if open.body.len() > 1 {
                open.body.push(',');
            }
            open.body.push_str(&self.scratch);
        }
        open.remaining = open.remaining.saturating_sub(1);
        if open.remaining > 0 {
            return Ok(());
        }
        let Some(mut done) = self.batches.remove(&batch) else {
            return Ok(());
        };
        if done.body.len() == 1 {
            // Every request in it was cancelled without a reply.
            return Ok(());
        }
        done.body.push(']');
        mem::swap(&mut self.scratch, &mut done.body);
        self.deliver(Sending::Response)
    }

    /// Opens the gate after a successful opening response, sending what was
    /// held; or shuts it again after a failed one, discarding what was held.
    fn settle_gate(&mut self, succeeded: bool) {
        let held = mem::take(&mut self.held);
        let live = mem::take(&mut self.held_requests);
        if succeeded {
            self.gate = GateState::Open;
            for message in held {
                if message.request.is_some_and(|id| !live.contains(&id)) {
                    continue;
                }
                self.scratch = message.body;
                if self.deliver(Sending::Notification).is_err() {
                    break;
                }
            }
        } else {
            self.gate = GateState::Closed;
            for message in held {
                if let Some(id) = message.request.filter(|id| live.contains(id)) {
                    if let Some(waiter) = self.pending.settle(id) {
                        let _gone = waiter.send(Err(CallError::Cancelled));
                    }
                }
            }
        }
    }

    /// Opens a batch that owes `answers` responses.
    pub(crate) fn open_batch(&mut self, answers: usize) -> u64 {
        let id = self.next_batch;
        self.next_batch = self.next_batch.wrapping_add(1);
        let _fresh = self.batches.insert(
            id,
            Batch {
                remaining: answers,
                body: String::from("["),
            },
        );
        id
    }

    /// Whether a deferred request with this id is being answered.
    pub(crate) fn in_flight(&self, id: &Id<'_>) -> bool {
        // Most sessions defer nothing: no copy of the id is made then.
        !self.in_flight.is_empty() && self.in_flight.contains_key(&id.clone().into_owned())
    }

    /// Records a deferred request; `None` when too many are in flight.
    pub(crate) fn begin_deferred(
        &mut self,
        id: Id<'static>,
        batch: Option<u64>,
    ) -> Option<CancelToken> {
        if self.in_flight.len() >= self.settings.max_in_flight {
            return None;
        }
        let token = CancelToken::new();
        let _fresh = self.in_flight.insert(
            id,
            InFlight {
                token: token.clone(),
                batch,
            },
        );
        Some(token)
    }

    /// Answers a deferred request, if it is still in flight.
    pub(crate) fn respond_deferred(
        &mut self,
        id: &Id<'static>,
        result: Result<&Json<'_>, &ErrorObject>,
    ) -> Result<(), Error> {
        match self.in_flight.remove(id) {
            Some(request) => self.respond(Some(id), request.batch, result),
            None if self.closed => Err(Error::Closed),
            None => Err(Error::AlreadyAnswered),
        }
    }

    /// The peer cancelled its request `id`: sets its token and answers it as
    /// the cancellation settings say. `false` if it is not in flight.
    pub(crate) fn cancel_incoming(&mut self, id: &Id<'_>) -> bool {
        let Some(request) = self.in_flight.remove(&id.clone().into_owned()) else {
            return false;
        };
        request.token.cancel();
        let reply = self.settings.cancellation.as_ref().and_then(|c| c.reply);
        let _sent = match reply {
            Some(code) => {
                let error = ErrorObject::new(code, "the request was cancelled");
                self.respond(Some(id), request.batch, Err(&error))
            }
            None => {
                // No response will come to settle the gate: a cancelled
                // opening request has failed, so the gate shuts again.
                if matches!(&self.gate, GateState::Opening(opening) if opening == id) {
                    self.settle_gate(false);
                }
                match request.batch {
                    Some(batch) => self.add_to_batch(batch, false),
                    None => Ok(()),
                }
            }
        };
        true
    }
}

/// Runs a [`Sink`] call, turning a panic in it into an I/O error: the sink is
/// user code, and its panic must close the connection, not unwind through the
/// endpoint (or through a worker that happened to be sending).
fn guard(send: impl FnOnce() -> io::Result<()>) -> io::Result<()> {
    panic::catch_unwind(AssertUnwindSafe(send))
        .unwrap_or_else(|_| Err(io::Error::other("the sink panicked")))
}