rpc-io 0.4.0

JSON-RPC 2.0 engine for LSP, MCP, and service APIs: Content-Length and newline framings, a sans-IO core, blocking and async adapters, bounded non-blocking output, and hostile-input hardening.
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
//! 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 to encode a message and hand it to the sink, never while 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, as long as the
//! sink does not block: a sink that writes to a slow peer holds the lock for
//! the write, which is why [`Queued`](crate::Queued) exists.
//!
//! Deadlines fire on their own: the first request with one starts a timer
//! thread that sleeps until the earliest is due, expires it, and sleeps again.
//! It holds only a weak reference, so it never keeps the connection alive,
//! and it stops when the connection closes.

use std::{
    collections::{BTreeMap, BTreeSet},
    io, mem,
    panic::{self, AssertUnwindSafe},
    sync::{
        Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak,
        atomic::{AtomicBool, AtomicU64, Ordering},
    },
    thread::{self, ThreadId},
    time::{Duration, Instant},
};

use crate::{
    config::{Cancellation, Config},
    error::{CallError, Error},
    error_object::{ErrorCode, ErrorObject},
    handles::CancelToken,
    id::Id,
    message::{write_call, write_numbered_call, write_response},
    pending::Pending,
    raw::Json,
    sink::{Drain, Sink},
    slot::{self, Outcome, Slot, Waiter},
    stats::{Stats, Tally, bump},
    text,
    trace::event,
};

/// The encoding buffer is released after a message that grew it past this.
const SCRATCH_KEEP: usize = 64 * 1024;

/// The request a notification belongs to, checked under the lock it is sent
/// under, so it cannot go out after that request's response.
#[derive(Clone)]
pub(crate) enum Scope {
    /// No request: always sent.
    Free,
    /// A request answered by its handler's return value.
    Turn(Arc<Turn>),
    /// A deferred request: live while the in-flight entry under `id` is the
    /// one with this `serial`. A later request that reuses the id gets
    /// another serial, so a handle of the earlier one never reaches it.
    Deferred { id: Id<'static>, serial: u64 },
}

/// The state of a request answered by its handler's return value, shared by
/// its bound handles. Read and written only under the shared lock (atomics
/// so it can be shared between threads at all).
#[derive(Debug, Default)]
pub(crate) struct Turn {
    /// Set when the response is written.
    done: AtomicBool,
    /// The last progress value sent for the request, as `f64` bits; `NO_PROGRESS`
    /// before the first.
    progress: AtomicU64,
}

/// `Turn::progress` before any report: the bits of a NaN, which no report
/// can carry (reports are finite).
const NO_PROGRESS: u64 = u64::MAX;

impl Turn {
    pub(crate) fn new() -> Self {
        Self {
            done: AtomicBool::new(false),
            progress: AtomicU64::new(NO_PROGRESS),
        }
    }

    /// Marks the request answered; called under the lock the response is
    /// written under.
    pub(crate) fn finish(&self) {
        self.done.store(true, Ordering::Release);
    }
}

/// 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>;
    /// As `notify`, refused with `Error::AlreadyAnswered` once `scope`'s
    /// request is answered or cancelled. With `progress`, refused with
    /// `Error::ProgressNotIncreasing` unless it exceeds the last progress
    /// value sent for that request (bound scopes only).
    fn notify_in(
        &self,
        scope: &Scope,
        progress: Option<f64>,
        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);
    /// Answers the deferred request `id`, if the one in flight under it is
    /// still the one with `serial`.
    fn respond(
        &self,
        id: &Id<'static>,
        serial: u64,
        result: Result<&Json<'_>, &ErrorObject>,
    ) -> Result<(), Error>;
    fn on_endpoint_thread(&self) -> bool;
    fn is_closed(&self) -> bool;
    fn stats(&self) -> Stats;
}

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

pub(crate) struct Shared<K> {
    inner: Mutex<Inner<K>>,
    timer: Arc<Timer>,
    /// `Inner::closed`, readable without the lock.
    closed: Arc<AtomicBool>,
}

impl<K: Sink> Shared<K> {
    pub(crate) fn new(sink: K, config: &Config) -> Arc<Self> {
        let timer = Arc::new(Timer::default());
        let closed = Arc::new(AtomicBool::new(false));
        Arc::new_cyclic(|me| Self {
            timer: Arc::clone(&timer),
            closed: Arc::clone(&closed),
            inner: Mutex::new(Inner {
                me: Weak::clone(me),
                timer,
                closed_flag: closed,
                sink,
                sink_closed: false,
                closed: false,
                broken: None,
                corked: false,
                scratch: String::new(),
                pending: Pending::new(config.max_pending),
                in_flight: IdMap::default(),
                batches: BTreeMap::new(),
                next_batch: 0,
                next_serial: 0,
                gate: if config.gate.is_some() {
                    GateState::Closed
                } else {
                    GateState::Open
                },
                held: Vec::new(),
                held_bytes: 0,
                held_requests: BTreeSet::new(),
                stats: Stats::default(),
                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)
    }

    /// Whether the connection is closed, without taking the lock: a sender
    /// stuck in a slow sink does not hold this up.
    pub(crate) fn is_closed(&self) -> bool {
        self.closed.load(Ordering::Acquire)
    }
}

impl<K> Drop for Shared<K> {
    fn drop(&mut self) {
        self.timer.stop();
    }
}

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

    fn notify_in(
        &self,
        scope: &Scope,
        progress: Option<f64>,
        method: &str,
        params: Option<&Json<'_>>,
    ) -> Result<(), Error> {
        let mut inner = self.lock();
        if inner.closed {
            return Err(Error::Closed);
        }
        let last = match scope {
            Scope::Free => None,
            Scope::Turn(turn) => {
                if turn.done.load(Ordering::Acquire) {
                    return Err(Error::AlreadyAnswered);
                }
                let bits = turn.progress.load(Ordering::Acquire);
                (bits != NO_PROGRESS).then(|| f64::from_bits(bits))
            }
            Scope::Deferred { id, serial } => match inner.in_flight.get(id) {
                Some(request) if request.serial == *serial => request.progress,
                _ => return Err(Error::AlreadyAnswered),
            },
        };
        if let (Some(next), Some(last)) = (progress, last) {
            if next <= last {
                return Err(Error::ProgressNotIncreasing { last, next });
            }
        }
        inner.notify(method, params)?;
        if let Some(next) = progress {
            match scope {
                Scope::Free => {}
                Scope::Turn(turn) => turn.progress.store(next.to_bits(), Ordering::Release),
                Scope::Deferred { id, .. } => {
                    if let Some(request) = inner.in_flight.get_mut(id) {
                        request.progress = Some(next);
                    }
                }
            }
        }
        Ok(())
    }

    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>,
        serial: u64,
        result: Result<&Json<'_>, &ErrorObject>,
    ) -> Result<(), Error> {
        self.lock().respond_deferred(id, serial, result)
    }

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

    fn is_closed(&self) -> bool {
        Shared::is_closed(self)
    }

    fn stats(&self) -> Stats {
        self.lock().stats()
    }
}

/// 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,
    pub(crate) max_held_bytes: usize,
    pub(crate) timer: bool,
    pub(crate) omit_null_id: bool,
    pub(crate) overloaded_code: ErrorCode,
}

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,
            max_held_bytes: config.max_held_bytes,
            timer: config.timer,
            omit_null_id: config.omit_null_id,
            overloaded_code: config.overloaded_code,
        }
    }
}

/// When the timer thread should next wake, and whether it runs.
#[derive(Default)]
struct Timer {
    state: Mutex<TimerState>,
    wake: Condvar,
}

#[derive(Default)]
struct TimerState {
    /// The earliest deadline it knows of (it may have been settled since;
    /// waking for nothing is harmless).
    due: Option<Instant>,
    running: bool,
    stopped: bool,
}

impl Timer {
    fn lock(&self) -> MutexGuard<'_, TimerState> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Ends the timer thread, for good.
    fn stop(&self) {
        self.lock().stopped = true;
        self.wake.notify_all();
    }
}

/// The timer thread: sleeps until the earliest deadline, expires what is due,
/// and asks the state for the next one. Ends when the timer is stopped or the
/// shared state is gone.
fn run_timer<K: Sink>(timer: &Timer, shared: &Weak<Shared<K>>) {
    let mut state = timer.lock();
    while !state.stopped {
        let Some(due) = state.due else {
            state = timer
                .wake
                .wait(state)
                .unwrap_or_else(PoisonError::into_inner);
            continue;
        };
        let now = Instant::now();
        if due > now {
            state = timer
                .wake
                .wait_timeout(state, due - now)
                .unwrap_or_else(PoisonError::into_inner)
                .0;
            continue;
        }
        state.due = None;
        drop(state);
        let Some(shared) = shared.upgrade() else {
            return;
        };
        {
            let mut inner = shared.lock();
            inner.expire();
            inner.arm();
        }
        drop(shared);
        state = timer.lock();
    }
    state.running = false;
}

/// 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>,
    /// Unique to this request among all the connection's deferred requests:
    /// its handles carry it, so they never act on a later request that
    /// reuses the id.
    serial: u64,
    /// The last progress value sent for it, shared by all its handles.
    progress: Option<f64>,
}

/// Deferred requests by id. Integer, string, and other (lenient) ids are
/// kept apart, so a lookup borrows the id it is given (`&str` for a string)
/// instead of copying it into an owned key.
struct IdMap<V> {
    numbers: BTreeMap<i64, V>,
    strings: BTreeMap<Box<str>, V>,
    /// [`Id::RawNumber`] ids, by their text.
    raw_numbers: BTreeMap<Box<str>, V>,
    /// The one [`Id::Null`] request.
    null: Option<V>,
}

impl<V> Default for IdMap<V> {
    fn default() -> Self {
        Self {
            numbers: BTreeMap::new(),
            strings: BTreeMap::new(),
            raw_numbers: BTreeMap::new(),
            null: None,
        }
    }
}

impl<V> IdMap<V> {
    fn len(&self) -> usize {
        self.numbers.len()
            + self.strings.len()
            + self.raw_numbers.len()
            + usize::from(self.null.is_some())
    }

    fn contains(&self, id: &Id<'_>) -> bool {
        match id {
            Id::Number(n) => self.numbers.contains_key(n),
            Id::String(s) => self.strings.contains_key(&**s),
            Id::RawNumber(s) => self.raw_numbers.contains_key(&**s),
            Id::Null => self.null.is_some(),
        }
    }

    fn insert(&mut self, id: Id<'_>, value: V) -> Option<V> {
        match id {
            Id::Number(n) => self.numbers.insert(n, value),
            Id::String(s) => self.strings.insert(s.into_owned().into_boxed_str(), value),
            Id::RawNumber(s) => self
                .raw_numbers
                .insert(s.into_owned().into_boxed_str(), value),
            Id::Null => self.null.replace(value),
        }
    }

    fn get(&self, id: &Id<'_>) -> Option<&V> {
        match id {
            Id::Number(n) => self.numbers.get(n),
            Id::String(s) => self.strings.get(&**s),
            Id::RawNumber(s) => self.raw_numbers.get(&**s),
            Id::Null => self.null.as_ref(),
        }
    }

    fn get_mut(&mut self, id: &Id<'_>) -> Option<&mut V> {
        match id {
            Id::Number(n) => self.numbers.get_mut(n),
            Id::String(s) => self.strings.get_mut(&**s),
            Id::RawNumber(s) => self.raw_numbers.get_mut(&**s),
            Id::Null => self.null.as_mut(),
        }
    }

    fn remove(&mut self, id: &Id<'_>) -> Option<V> {
        match id {
            Id::Number(n) => self.numbers.remove(n),
            Id::String(s) => self.strings.remove(&**s),
            Id::RawNumber(s) => self.raw_numbers.remove(&**s),
            Id::Null => self.null.take(),
        }
    }

    fn into_values(self) -> impl Iterator<Item = V> {
        self.numbers
            .into_values()
            .chain(self.strings.into_values())
            .chain(self.raw_numbers.into_values())
            .chain(self.null)
    }
}

/// 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> {
    /// The state this sits in, for the timer thread.
    me: Weak<Shared<K>>,
    timer: Arc<Timer>,
    /// Mirrors `closed` for `Shared::is_closed`.
    closed_flag: Arc<AtomicBool>,
    sink: K,
    /// Whether `Sink::close` was called.
    sink_closed: bool,
    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<Waiter>,
    in_flight: IdMap<InFlight>,
    batches: BTreeMap<u64, Batch>,
    next_batch: u64,
    /// The serial the next deferred request gets.
    next_serial: u64,
    pub(crate) gate: GateState,
    held: Vec<Held>,
    /// The bytes of the bodies in `held`.
    held_bytes: usize,
    /// Ids of our requests in `held` and not abandoned since: lookups stay
    /// `O(log n)` however much is held.
    held_requests: BTreeSet<u64>,
    /// The counters; the gauges are filled in by `stats`.
    stats: Stats,
    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
    }

    /// A snapshot of the counters, with the gauges as they are now.
    pub(crate) fn stats(&self) -> Stats {
        Stats {
            pending: self.pending.len(),
            in_flight: self.in_flight.len(),
            held: self.held.len(),
            ..self.stats
        }
    }

    /// Counts an incoming body (or, with `tally.body` unset, a message the
    /// framing skipped).
    pub(crate) fn take_in(&mut self, tally: &Tally) {
        self.stats.take_in(tally);
    }

    /// Counts a contained handler panic.
    pub(crate) fn count_panic(&mut self) {
        bump(&mut self.stats.panics);
    }

    /// 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.
    /// How many of our requests wait on the peer with no deadline.
    #[cfg(feature = "net")]
    pub(crate) fn open_ended(&self) -> usize {
        self.pending.without_deadline()
    }

    pub(crate) fn next_deadline(&self) -> Option<Instant> {
        self.pending
            .next_deadline()
            .and_then(|at| self.epoch.checked_add(at))
    }

    /// Makes sure the timer thread wakes for the earliest deadline, starting
    /// it if it is not running. Without a thread (the timer is off, or one
    /// could not be started) deadlines are enforced lazily, as `expire` says.
    fn arm(&mut self) {
        if !self.settings.timer || self.closed {
            return;
        }
        let Some(due) = self.next_deadline() else {
            return;
        };
        let mut timer = self.timer.lock();
        if timer.stopped {
            return;
        }
        if timer.due.is_none_or(|at| due < at) {
            timer.due = Some(due);
            self.timer.wake.notify_all();
        }
        if !timer.running {
            let shared = Weak::clone(&self.me);
            let thread_timer = Arc::clone(&self.timer);
            let started = thread::Builder::new()
                .name("rpc-io-timer".into())
                .spawn(move || run_timer(&thread_timer, &shared));
            timer.running = started.is_ok();
        }
    }

    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: closes the sink (flushing it), tells every
    /// waiter it is over, and returns what the caller waits for once it has
    /// released the lock (the sink's [`Drain`]).
    pub(crate) fn close(&mut self) -> Option<Drain> {
        if self.closed {
            return None;
        }
        if let Err(error) = self.close_sink() {
            let _closed = self.fail(error);
        }
        self.shut();
        let drain = panic::catch_unwind(AssertUnwindSafe(|| self.sink.drain()));
        drain.unwrap_or(None)
    }

    /// Closes the sink, once: at the close, or after a send failed.
    fn close_sink(&mut self) -> io::Result<()> {
        if mem::replace(&mut self.sink_closed, true) {
            return Ok(());
        }
        guard(|| self.sink.close())
    }

    /// Marks the connection closed and releases everything waiting on it.
    fn shut(&mut self) {
        event!(debug, "the connection is closed");
        self.closed = true;
        self.closed_flag.store(true, Ordering::Release);
        self.timer.stop();
        for (_, waiter) in self.pending.drain() {
            waiter.send(Err(CallError::Closed));
        }
        for request in mem::take(&mut self.in_flight).into_values() {
            // Workers still answering see the cancellation and can stop.
            request.token.cancel();
        }
        self.batches.clear();
        self.held.clear();
        self.held_requests.clear();
        self.held_bytes = 0;
    }

    /// Records a sink failure and closes; returns the error for the sender.
    fn fail(&mut self, error: io::Error) -> Error {
        event!(warn, error = %error, "the transport failed; closing the connection");
        let copy = io::Error::new(error.kind(), error.to_string());
        if self.broken.is_none() {
            self.broken = Some(error);
        }
        // Best effort: the sink failed already, but it still gets to release
        // what it holds.
        let _released = self.close_sink();
        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 bytes = self.held_bytes.saturating_add(self.scratch.len());
            if bytes > self.settings.max_held_bytes {
                event!(
                    warn,
                    held = self.held.len(),
                    "too much is held behind the gate; a message was refused"
                );
                return Err(Error::Backlog);
            }
            self.held_bytes = bytes;
            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(());
        }
        bump(&mut self.stats.bodies_out);
        self.stats.bytes_out = self.stats.bytes_out.wrapping_add(self.scratch.len() as u64);
        match sending {
            Sending::Request(_) => bump(&mut self.stats.requests_out),
            Sending::Notification => bump(&mut self.stats.notifications_out),
            // Counted one by one in `respond`, batch elements included.
            Sending::Response => {}
        }
        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());
        }
        if self.scratch.capacity() > SCRATCH_KEEP {
            // A large message or batch grew the buffer; keep the usual size.
            self.scratch = String::new();
        }
        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) = slot::slot();
        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);
        }
        if deadline.is_some() {
            self.arm();
        }
        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) => {
                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: Waiter, reason: CallError) {
        match reason {
            CallError::TimedOut => {
                bump(&mut self.stats.timed_out);
                event!(debug, id, "our request timed out");
            }
            CallError::Evicted => {
                bump(&mut self.stats.evicted);
                event!(
                    warn,
                    id,
                    "our oldest request was evicted: too many are outstanding"
                );
            }
            _ => bump(&mut self.stats.cancelled_out),
        }
        // 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);
        }
        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);
        }
        bump(&mut self.stats.responses_out);
        if result.is_err() {
            bump(&mut self.stats.errors_out);
        }
        self.scratch.clear();
        write_response(&mut self.scratch, id, result, self.settings.omit_null_id);
        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);
        self.held_bytes = 0;
        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;
                let sending = message
                    .request
                    .map_or(Sending::Notification, Sending::Request);
                if self.deliver(sending).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) {
                        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 {
        self.in_flight.contains(id)
    }

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

    /// Answers a deferred request, if the one in flight under `id` is still
    /// the one with `serial`: a responder of an earlier request that was
    /// cancelled, whose id the peer has reused since, answers nothing.
    pub(crate) fn respond_deferred(
        &mut self,
        id: &Id<'static>,
        serial: u64,
        result: Result<&Json<'_>, &ErrorObject>,
    ) -> Result<(), Error> {
        let current = self
            .in_flight
            .get(id)
            .is_some_and(|request| request.serial == serial);
        match current.then(|| self.in_flight.remove(id)).flatten() {
            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) else {
            return false;
        };
        bump(&mut self.stats.cancelled_in);
        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")))
}