mcpls-core 0.8.0

Core library for MCP to LSP protocol translation
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
//! Delivery of `textDocument/publishDiagnostics` from a server's message loop
//! to the bridge.
//!
//! A server may publish for many files in one burst, faster than the bridge
//! drains them. A bounded channel would drop the tail silently, so
//! diagnostics travel through a per-server mailbox instead: one pending
//! publish per file (a later publish supersedes an earlier one), bounded in
//! files and in bytes. A publish the mailbox cannot hold is not discarded
//! quietly: its file is recorded as lost, and the reader hands the lost files
//! over so the cache can say so ([`PublishDelivery::Lost`],
//! [`PublishDelivery::LostUnnamed`]).

use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, Instant};

use lsp_types::{LogMessageParams, PublishDiagnosticsParams, ShowMessageParams, Uri};
use tokio::sync::{Notify, mpsc};
use tracing::{debug, warn};

use crate::bridge::{BoundedDiagnostics, DiagnosticsKey, MAX_DIAGNOSTIC_ENTRIES};
use crate::util::{MAX_LOG_STRING_BYTES, WarnLimiter, escape_bounded, lock_std};

/// Most files with an undelivered publish; as many as the cache holds, so the
/// mailbox is never the narrower bound.
pub const MAX_PENDING_PUBLISHES: usize = MAX_DIAGNOSTIC_ENTRIES;

/// Most bytes of undelivered diagnostics per server.
pub const MAILBOX_MAX_BYTES: usize = 64 * 1024 * 1024;

/// Most lost files remembered per server before only the fact of a loss is.
const MAX_LOST_FILES: usize = MAX_DIAGNOSTIC_ENTRIES;

/// Period of the dropped-frame warning of one lane.
pub const DROP_WARN_PERIOD: Duration = WarnLimiter::DEFAULT_PERIOD;

/// What the mailbox holds at most.
#[derive(Debug, Clone, Copy)]
pub struct MailboxLimits {
    /// Most files with an undelivered publish.
    pub max_pending: usize,
    /// Most bytes of undelivered diagnostics.
    pub max_bytes: usize,
}

impl Default for MailboxLimits {
    fn default() -> Self {
        Self {
            max_pending: MAX_PENDING_PUBLISHES,
            max_bytes: MAILBOX_MAX_BYTES,
        }
    }
}

/// Counts dropped frames and says when one is worth a warning: at most once
/// per [`DROP_WARN_PERIOD`], so a flood cannot flood the log.
#[derive(Debug, Default)]
pub struct DropCounter {
    warn: WarnLimiter,
    suppressed: usize,
}

impl DropCounter {
    /// A counter whose first drop warns at once.
    pub const fn new() -> Self {
        Self {
            warn: WarnLimiter::new(),
            suppressed: 0,
        }
    }

    /// Records one drop at `now`. `Some(n)` when a warning is due, with `n` the
    /// drops silenced since the previous warning; the caller logs it once it
    /// holds no lock.
    pub fn record(&mut self, now: Instant) -> Option<usize> {
        if self.warn.due(now, DROP_WARN_PERIOD) {
            Some(std::mem::take(&mut self.suppressed))
        } else {
            self.suppressed = self.suppressed.saturating_add(1);
            None
        }
    }
}

/// A `publishDiagnostics` whose diagnostics are already bounded the way the
/// cache stores them, so no later stage bounds them again.
#[derive(Debug)]
pub struct BoundedPublish {
    uri: Uri,
    version: Option<i32>,
    diagnostics: BoundedDiagnostics,
}

impl BoundedPublish {
    fn new(params: PublishDiagnosticsParams) -> (Self, usize) {
        let PublishDiagnosticsParams {
            uri,
            diagnostics,
            version,
        } = params;
        let diagnostics = BoundedDiagnostics::new(&uri, diagnostics);
        let bytes = diagnostics
            .buffered_bytes()
            .saturating_add(AsRef::<str>::as_ref(&uri).len());
        (
            Self {
                uri,
                version,
                diagnostics,
            },
            bytes,
        )
    }

    /// The file the server published for, exactly as it spelled it.
    #[must_use]
    pub const fn uri(&self) -> &Uri {
        &self.uri
    }

    /// The document version the diagnostics are for, if the server said.
    #[must_use]
    pub const fn version(&self) -> Option<i32> {
        self.version
    }

    /// The bounded diagnostics.
    #[must_use]
    pub const fn diagnostics(&self) -> &BoundedDiagnostics {
        &self.diagnostics
    }

    /// The URI, version and bounded diagnostics.
    #[must_use]
    pub fn into_parts(self) -> (Uri, Option<i32>, BoundedDiagnostics) {
        (self.uri, self.version, self.diagnostics)
    }
}

/// A non-empty list of files whose publish the mailbox could not deliver,
/// oldest loss first.
#[derive(Debug, PartialEq, Eq)]
pub struct LostFiles(Vec<Uri>);

impl LostFiles {
    fn new(uris: Vec<Uri>) -> Option<Self> {
        (!uris.is_empty()).then_some(Self(uris))
    }

    /// The lost files.
    #[must_use]
    pub fn uris(&self) -> &[Uri] {
        &self.0
    }
}

/// One thing the reader takes out of the mailbox.
#[derive(Debug)]
pub enum PublishDelivery {
    /// The latest pending publish of a file.
    Publish(BoundedPublish),
    /// Named files whose publish never made it into the mailbox.
    Lost(LostFiles),
    /// More files were lost than the mailbox could name. Handed over on its
    /// own, after the pending publishes.
    LostUnnamed,
}

/// A frame of the log and `showMessage` lane.
#[derive(Debug)]
pub enum ServerMessage {
    /// A `window/logMessage`.
    Log(LogMessageParams),
    /// A `window/showMessage`.
    Show(ShowMessageParams),
}

#[derive(Debug)]
struct Pending {
    publish: BoundedPublish,
    bytes: usize,
    /// Position in `State::order`; a replacement keeps it, a new publish of
    /// a file whose earlier one was withdrawn gets a fresh one.
    seq: u64,
}

#[derive(Debug, Default)]
struct State {
    pending: HashMap<DiagnosticsKey, Pending>,
    /// Arrival order of the pending publishes as `(key, seq)`; an entry whose
    /// `seq` is not the pending publish's (withdrawn, taken or republished
    /// later) is skipped.
    order: VecDeque<(DiagnosticsKey, u64)>,
    next_seq: u64,
    bytes: usize,
    lost: Vec<Uri>,
    lost_keys: HashSet<DiagnosticsKey>,
    lost_overflowed: bool,
    drops: DropCounter,
    writer_gone: bool,
    reader_gone: bool,
}

#[derive(Debug)]
struct Shared {
    state: StdMutex<State>,
    wake: Notify,
    limits: MailboxLimits,
}

/// Whether `seq` is the sequence number of the pending publish of `key`.
fn is_current(pending: &HashMap<DiagnosticsKey, Pending>, key: &DiagnosticsKey, seq: u64) -> bool {
    pending.get(key).is_some_and(|pending| pending.seq == seq)
}

impl State {
    /// Appends `key` to the arrival order under a fresh sequence number.
    fn enqueue(&mut self, key: DiagnosticsKey) -> u64 {
        let seq = self.next_seq;
        self.next_seq = seq.saturating_add(1);
        self.order.push_back((key, seq));
        seq
    }

    fn withdraw(&mut self, key: &DiagnosticsKey) {
        if let Some(pending) = self.pending.remove(key) {
            self.bytes = self.bytes.saturating_sub(pending.bytes);
        }
    }

    /// Drops the entries of `order` that no longer match a pending publish
    /// once they outnumber what the mailbox can hold twice over, so a stalled
    /// reader cannot make the queue grow with withdrawn files.
    fn compact_order(&mut self, max_pending: usize) {
        if self.order.len() > max_pending.saturating_mul(2).max(16) {
            let pending = &self.pending;
            self.order
                .retain(|(key, seq)| is_current(pending, key, *seq));
        }
    }

    /// The next delivery that is ready: lost files, then pending publishes in
    /// arrival order, then the unnamed losses.
    fn next_ready(&mut self) -> Option<PublishDelivery> {
        if let Some(lost) = self.take_lost_files() {
            return Some(PublishDelivery::Lost(lost));
        }
        while let Some((key, seq)) = self.order.pop_front() {
            let Entry::Occupied(entry) = self.pending.entry(key) else {
                continue;
            };
            if entry.get().seq != seq {
                continue;
            }
            let pending = entry.remove();
            self.bytes = self.bytes.saturating_sub(pending.bytes);
            return Some(PublishDelivery::Publish(pending.publish));
        }
        std::mem::take(&mut self.lost_overflowed).then_some(PublishDelivery::LostUnnamed)
    }

    fn mark_lost(&mut self, key: DiagnosticsKey, uri: Uri) {
        if self.lost_keys.contains(&key) {
            return;
        }
        if self.lost.len() >= MAX_LOST_FILES {
            self.lost_overflowed = true;
            return;
        }
        self.lost_keys.insert(key);
        self.lost.push(uri);
    }

    fn take_lost_files(&mut self) -> Option<LostFiles> {
        let lost = LostFiles::new(std::mem::take(&mut self.lost))?;
        self.lost_keys.clear();
        Some(lost)
    }

    /// Counts one dropped publish; `Some(n)` when a warning is due.
    fn count_drop(&mut self) -> Option<usize> {
        self.drops.record(Instant::now())
    }
}

/// The message loop's side of the mailbox. Dropping it closes the mailbox, so
/// the reader ends once what is pending is taken.
#[derive(Debug)]
pub struct PublishWriter {
    shared: Arc<Shared>,
}

/// The bridge's side of the mailbox. Dropping it discards what is pending and
/// makes the writer stop buffering.
#[derive(Debug)]
pub struct PublishReader {
    shared: Arc<Shared>,
}

/// A mailbox bounded by `limits`: the message loop's writer and the bridge's
/// reader of one server's `publishDiagnostics`.
pub fn mailbox(limits: MailboxLimits) -> (PublishWriter, PublishReader) {
    let shared = Arc::new(Shared {
        state: StdMutex::new(State::default()),
        wake: Notify::new(),
        limits,
    });
    (
        PublishWriter {
            shared: Arc::clone(&shared),
        },
        PublishReader { shared },
    )
}

impl PublishWriter {
    /// Buffers `params`, replacing a pending publish of the same file.
    ///
    /// The diagnostics are bounded like the cache bounds an entry before they
    /// are counted. A publish that does not fit is dropped and its file
    /// recorded as lost; when a replacement does not fit, the older pending
    /// publish of the file is withdrawn too, so the file never reads as
    /// published with content older than what the server last said.
    pub fn publish(&self, params: PublishDiagnosticsParams) {
        let (publish, bytes) = BoundedPublish::new(params);
        let key = DiagnosticsKey::of(publish.uri());
        let limits = self.shared.limits;
        let mut state = lock_std(&self.shared.state);
        if state.reader_gone {
            debug!(
                "dropping a publish for {}: nobody reads the mailbox",
                publish.uri().as_ref()
            );
            return;
        }
        let replaced = state
            .pending
            .get(&key)
            .map(|pending| (pending.bytes, pending.seq));
        let is_new = replaced.is_none();
        let fits = state
            .bytes
            .saturating_sub(replaced.map_or(0, |(bytes, _)| bytes))
            .saturating_add(bytes)
            <= limits.max_bytes
            && (!is_new || state.pending.len() < limits.max_pending);
        state.compact_order(limits.max_pending);
        state.withdraw(&key);
        let warn_due = if fits {
            state.bytes = state.bytes.saturating_add(bytes);
            let seq = match replaced {
                Some((_, seq)) => seq,
                None => state.enqueue(key.clone()),
            };
            state.pending.insert(
                key,
                Pending {
                    publish,
                    bytes,
                    seq,
                },
            );
            None
        } else {
            let (uri, ..) = publish.into_parts();
            state.mark_lost(key, uri);
            state.count_drop()
        };
        drop(state);
        if let Some(suppressed) = warn_due {
            warn!(
                "publishDiagnostics mailbox is full: dropped a publish ({suppressed} others \
                 since the last warning); the files read as evicted until the server publishes \
                 again"
            );
        }
        self.shared.wake.notify_one();
    }
}

impl Drop for PublishWriter {
    fn drop(&mut self) {
        lock_std(&self.shared.state).writer_gone = true;
        self.shared.wake.notify_one();
    }
}

impl PublishReader {
    /// A reader of a mailbox nothing will ever be written to.
    #[must_use]
    pub fn closed() -> Self {
        mailbox(MailboxLimits::default()).1
    }

    /// The next delivery if one is ready now, without waiting.
    pub fn try_recv(&mut self) -> Option<PublishDelivery> {
        lock_std(&self.shared.state).next_ready()
    }

    /// The next delivery: lost files first, then pending publishes in arrival
    /// order; `None` once the writer is gone and nothing is left.
    pub async fn recv(&mut self) -> Option<PublishDelivery> {
        loop {
            {
                let mut state = lock_std(&self.shared.state);
                if let Some(delivery) = state.next_ready() {
                    return Some(delivery);
                }
                if state.writer_gone {
                    return None;
                }
            }
            self.shared.wake.notified().await;
        }
    }
}

impl Drop for PublishReader {
    fn drop(&mut self) {
        let mut state = lock_std(&self.shared.state);
        state.reader_gone = true;
        state.order.clear();
        state.bytes = 0;
        let pending = std::mem::take(&mut state.pending);
        drop(state);
        drop(pending);
    }
}

/// The message loop's handle for everything a server notifies on the
/// notification lane: log and `showMessage` frames take a bounded channel and
/// yield under pressure, diagnostics take the mailbox and are never dropped
/// unrecorded.
#[derive(Debug)]
pub struct NotificationSink {
    messages: mpsc::Sender<ServerMessage>,
    publishes: PublishWriter,
}

impl NotificationSink {
    /// A sink over `messages` with a mailbox of the default limits.
    pub fn new(messages: mpsc::Sender<ServerMessage>) -> (Self, PublishReader) {
        Self::with_limits(messages, MailboxLimits::default())
    }

    /// As [`Self::new`] with explicit mailbox limits.
    pub fn with_limits(
        messages: mpsc::Sender<ServerMessage>,
        limits: MailboxLimits,
    ) -> (Self, PublishReader) {
        let (publishes, reader) = mailbox(limits);
        (
            Self {
                messages,
                publishes,
            },
            reader,
        )
    }

    /// The channel log and `showMessage` frames go through.
    pub const fn messages(&self) -> &mpsc::Sender<ServerMessage> {
        &self.messages
    }

    /// The mailbox diagnostics go through.
    pub const fn publishes(&self) -> &PublishWriter {
        &self.publishes
    }
}

/// Everything a server's notification lane delivers to the bridge: log and
/// `showMessage` frames from a bounded channel, and the diagnostics mailbox.
#[derive(Debug)]
pub struct NotificationInbox {
    /// The log/showMessage channel.
    pub messages: mpsc::Receiver<ServerMessage>,
    /// The diagnostics mailbox.
    pub publishes: PublishReader,
}

impl NotificationInbox {
    /// An inbox over `messages` and `publishes`.
    #[must_use]
    pub const fn new(messages: mpsc::Receiver<ServerMessage>, publishes: PublishReader) -> Self {
        Self {
            messages,
            publishes,
        }
    }
}

#[cfg(test)]
impl From<mpsc::Receiver<ServerMessage>> for NotificationInbox {
    fn from(messages: mpsc::Receiver<ServerMessage>) -> Self {
        Self::new(messages, PublishReader::closed())
    }
}

/// A notification lane that can drop a frame under pressure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lane {
    /// Log and `showMessage` frames.
    Notification,
    /// `$/progress` `begin`/`end` and unrecognized notifications.
    Lifecycle,
}

impl Lane {
    const fn name(self) -> &'static str {
        match self {
            Self::Notification => "notification",
            Self::Lifecycle => "lifecycle",
        }
    }
}

/// Counts the frames one lane dropped and warns about them at most once per
/// [`DROP_WARN_PERIOD`], naming the lane and the count since the last warning.
#[derive(Debug)]
pub struct DropLog {
    lane: Lane,
    drops: StdMutex<DropCounter>,
}

impl DropLog {
    const fn new(lane: Lane) -> Self {
        Self {
            lane,
            drops: StdMutex::new(DropCounter::new()),
        }
    }

    /// The log of `lane`; shared by every server, so a flood on one lane warns
    /// once a period.
    pub fn of(lane: Lane) -> &'static Self {
        static NOTIFICATION: DropLog = DropLog::new(Lane::Notification);
        static LIFECYCLE: DropLog = DropLog::new(Lane::Lifecycle);
        match lane {
            Lane::Notification => &NOTIFICATION,
            Lane::Lifecycle => &LIFECYCLE,
        }
    }

    /// Records one dropped frame of `method`; the frame itself is logged at
    /// DEBUG only.
    pub fn record(&self, method: &str) {
        let lane = self.lane.name();
        let method = escape_bounded(method, MAX_LOG_STRING_BYTES);
        debug!("dropping notification: lane={lane}, method={method}");
        let warn_due = lock_std(&self.drops).record(Instant::now());
        if let Some(suppressed) = warn_due {
            warn!(
                "dropped a notification on the {lane} lane ({suppressed} others since the last \
                 warning; channel full or closed)"
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use lsp_types::Diagnostic;

    use super::*;

    fn uri(n: usize) -> Uri {
        Uri::from(format!("file:///ws/f{n}.rs"))
    }

    fn publish_of(n: usize, message: &str) -> PublishDiagnosticsParams {
        PublishDiagnosticsParams {
            uri: uri(n),
            diagnostics: vec![Diagnostic {
                message: message.to_owned().into(),
                ..Diagnostic::default()
            }],
            version: None,
        }
    }

    fn bytes_of(n: usize, message: &str) -> usize {
        BoundedPublish::new(publish_of(n, message)).1
    }

    /// #738: the method of a dropped frame is escaped and bounded in the log.
    #[test]
    fn drop_log_escapes_and_bounds_the_method() {
        use tracing_subscriber::layer::SubscriberExt as _;

        let captured = crate::test_lsp::CapturedLogs::default();
        let guard =
            tracing::subscriber::set_default(tracing_subscriber::registry().with(captured.clone()));

        DropLog::of(Lane::Notification).record(&format!("evil\nFORGED{}", "x".repeat(10_000)));
        drop(guard);

        let line = captured
            .messages()
            .into_iter()
            .find(|message| message.contains("dropping notification"))
            .expect("the drop is logged at debug");
        assert!(!line.contains('\n'), "{line:.80}");
        assert!(line.contains("evil\\nFORGED"), "{line:.80}");
        assert!(line.len() < 2 * MAX_LOG_STRING_BYTES, "{}", line.len());
    }

    /// #738: the URI text counts toward the byte budget.
    #[test]
    fn publish_bytes_include_the_uri() {
        let params = publish_of(1, "x");
        let diagnostics = BoundedDiagnostics::new(&params.uri, params.diagnostics.clone());

        assert_eq!(
            bytes_of(1, "x"),
            diagnostics.buffered_bytes() + "file:///ws/f1.rs".len()
        );
    }

    /// #742: a republished file is delivered at its new arrival position, not
    /// at the place a withdrawn publish held.
    #[tokio::test]
    async fn republished_file_follows_arrival_order_after_a_withdrawal() {
        let one = bytes_of(1, "x");
        let (writer, mut reader) = mailbox(small(10, one * 2 + one / 2));
        writer.publish(publish_of(1, "x"));
        writer.publish(publish_of(1, &"y".repeat(one * 4)));
        writer.publish(publish_of(2, "x"));
        writer.publish(publish_of(1, "x"));
        drop(writer);

        let Some(PublishDelivery::Lost(lost)) = reader.recv().await else {
            panic!("expected the lost file first");
        };
        assert_eq!(lost.uris(), [uri(1)]);
        assert_eq!(next_publish(&mut reader).await.uri(), &uri(2));
        assert_eq!(next_publish(&mut reader).await.uri(), &uri(1));
        assert!(reader.recv().await.is_none());
    }

    fn small(max_pending: usize, max_bytes: usize) -> MailboxLimits {
        MailboxLimits {
            max_pending,
            max_bytes,
        }
    }

    async fn next_publish(reader: &mut PublishReader) -> BoundedPublish {
        match reader.recv().await {
            Some(PublishDelivery::Publish(publish)) => publish,
            other => panic!("expected a publish, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn burst_below_the_cap_is_delivered_whole_in_order() {
        let (writer, mut reader) = mailbox(small(10, usize::MAX));
        for n in 0..10 {
            writer.publish(publish_of(n, "e"));
        }
        drop(writer);

        for n in 0..10 {
            assert_eq!(next_publish(&mut reader).await.uri(), &uri(n));
        }
        assert!(reader.recv().await.is_none());
    }

    #[tokio::test]
    async fn later_publish_replaces_the_pending_one_of_the_same_file() {
        let (writer, mut reader) = mailbox(small(10, usize::MAX));
        writer.publish(publish_of(1, "old"));
        writer.publish(publish_of(1, "new"));
        drop(writer);

        let delivered = next_publish(&mut reader).await;
        assert_eq!(delivered.diagnostics().as_slice().len(), 1);
        assert_eq!(
            delivered
                .diagnostics()
                .as_slice()
                .first()
                .map(|d| d.message.clone()),
            Some("new".to_owned().into())
        );
        assert!(reader.recv().await.is_none());
    }

    #[tokio::test]
    async fn publish_over_the_file_cap_is_reported_lost_not_dropped_quietly() {
        let (writer, mut reader) = mailbox(small(2, usize::MAX));
        for n in 0..4 {
            writer.publish(publish_of(n, "e"));
        }

        let Some(PublishDelivery::Lost(lost)) = reader.recv().await else {
            panic!("the loss must be handed over first");
        };
        assert_eq!(lost.uris(), [uri(2), uri(3)]);
        assert_eq!(next_publish(&mut reader).await.uri(), &uri(0));
        assert_eq!(next_publish(&mut reader).await.uri(), &uri(1));
    }

    /// A replacement that does not fit withdraws the older pending publish
    /// too, so the file reads lost rather than with older content.
    #[tokio::test]
    async fn oversized_replacement_withdraws_the_older_publish_and_marks_the_file_lost() {
        let one = bytes_of(1, "x");
        let (writer, mut reader) = mailbox(small(10, one + one / 2));
        writer.publish(publish_of(1, "x"));
        writer.publish(publish_of(1, &"y".repeat(one * 2)));
        drop(writer);

        let Some(PublishDelivery::Lost(lost)) = reader.recv().await else {
            panic!("expected the lost file");
        };
        assert_eq!(lost.uris(), [uri(1)]);
        assert!(reader.recv().await.is_none());
    }

    /// A stalled reader cannot make the arrival queue grow with withdrawn files.
    #[tokio::test]
    async fn arrival_queue_stays_bounded_under_withdrawals() {
        let one = bytes_of(0, "x");
        let (writer, _reader) = mailbox(small(4, one * 2));
        for n in 0..1000 {
            writer.publish(publish_of(n, "x"));
            writer.publish(publish_of(n, &"y".repeat(one * 4)));
        }

        assert!(lock_std(&writer.shared.state).order.len() <= 16);
    }

    #[tokio::test]
    async fn replacement_after_order_compaction_is_still_delivered() {
        let one = bytes_of(0, "x");
        let (writer, mut reader) = mailbox(small(4, one * 2));
        for n in 0..16 {
            writer.publish(publish_of(n, "x"));
            writer.publish(publish_of(n, &"y".repeat(one * 4)));
        }
        writer.publish(publish_of(100, "x"));
        writer.publish(publish_of(100, "z"));
        drop(writer);

        let mut delivered = None;
        while let Some(delivery) = reader.recv().await {
            if let PublishDelivery::Publish(params) = delivery {
                delivered = Some(params);
            }
        }
        let delivered = delivered.expect("the replaced publish must reach the reader");
        assert_eq!(delivered.uri(), &uri(100));
        assert_eq!(
            delivered
                .diagnostics()
                .as_slice()
                .first()
                .map(|d| d.message.clone()),
            Some("z".to_owned().into())
        );
    }

    #[tokio::test]
    async fn delivered_publish_carries_bounded_diagnostics() {
        let (writer, mut reader) = mailbox(small(10, usize::MAX));
        let oversized = 512 * 1024;
        writer.publish(publish_of(1, &"m".repeat(oversized)));
        drop(writer);

        let delivered = next_publish(&mut reader).await;

        let message = delivered
            .diagnostics()
            .as_slice()
            .first()
            .map(|d| d.message.clone());
        assert_matches!(
            message,
            Some(lsp_types::Message::String(text)) if text.len() < oversized
        );
    }

    #[test]
    fn drop_counter_warns_once_per_period_and_counts_the_silenced() {
        let mut counter = DropCounter::new();
        let start = Instant::now();
        let at = |secs| start + Duration::from_secs(secs);

        assert_eq!(counter.record(at(0)), Some(0));
        assert_eq!(counter.record(at(1)), None);
        assert_eq!(counter.record(at(2)), None);
        assert_eq!(counter.record(at(61)), Some(2));
    }

    #[test]
    fn each_lane_has_its_own_drop_log() {
        for lane in [Lane::Notification, Lane::Lifecycle] {
            assert_eq!(DropLog::of(lane).lane, lane);
        }
    }

    #[tokio::test]
    async fn byte_cap_bounds_what_is_buffered() {
        let one = bytes_of(0, "e");
        let (writer, mut reader) = mailbox(small(100, one * 3));
        for n in 0..10 {
            writer.publish(publish_of(n, "e"));
        }
        drop(writer);

        let mut delivered = 0;
        let mut lost = 0;
        while let Some(item) = reader.recv().await {
            match item {
                PublishDelivery::Publish(_) => delivered += 1,
                PublishDelivery::Lost(files) => lost += files.uris().len(),
                PublishDelivery::LostUnnamed => panic!("no unnamed losses expected"),
            }
        }
        assert_eq!((delivered, lost), (3, 7));
    }

    #[tokio::test]
    async fn lost_list_is_capped_and_then_only_the_fact_is_kept() {
        let (writer, mut reader) = mailbox(small(0, usize::MAX));
        for n in 0..=MAX_LOST_FILES {
            writer.publish(publish_of(n, "e"));
        }
        drop(writer);

        let Some(PublishDelivery::Lost(lost)) = reader.recv().await else {
            panic!("expected losses");
        };
        assert_eq!(lost.uris().len(), MAX_LOST_FILES);
        assert_matches!(reader.recv().await, Some(PublishDelivery::LostUnnamed));
        assert!(reader.recv().await.is_none());
    }

    #[tokio::test]
    async fn dropping_the_writer_ends_the_reader_and_dropping_the_reader_stops_buffering() {
        let (writer, reader) = mailbox(small(10, usize::MAX));
        writer.publish(publish_of(1, "e"));
        drop(reader);
        writer.publish(publish_of(2, "e"));
        assert_eq!(lock_std(&writer.shared.state).bytes, 0);
        assert!(lock_std(&writer.shared.state).pending.is_empty());

        let (writer, mut reader) = mailbox(small(10, usize::MAX));
        drop(writer);
        assert!(reader.recv().await.is_none());
    }

    #[tokio::test]
    async fn a_waiting_reader_wakes_for_a_new_publish() {
        let (writer, mut reader) = mailbox(small(10, usize::MAX));
        let waiting = tokio::spawn(async move { next_publish(&mut reader).await.uri });
        tokio::task::yield_now().await;

        writer.publish(publish_of(7, "e"));

        assert_eq!(waiting.await.unwrap(), uri(7));
    }
}