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
use super::{RemoteProcess, RemoteProcessError, RemoteStderr, RemoteStdin, RemoteStdout};
use crate::{client::Session, net::DataStream};
use futures::stream::{Stream, StreamExt};
use std::{
    fmt::Write,
    io::{self, Cursor, Read},
    ops::{Deref, DerefMut},
};
use tokio::{sync::mpsc, task::JoinHandle};

mod data;
pub use data::*;

/// Represents an LSP server process on a remote machine
#[derive(Debug)]
pub struct RemoteLspProcess {
    inner: RemoteProcess,
    pub stdin: Option<RemoteLspStdin>,
    pub stdout: Option<RemoteLspStdout>,
    pub stderr: Option<RemoteLspStderr>,
}

impl RemoteLspProcess {
    /// Spawns the specified process on the remote machine using the given session, treating
    /// the process like an LSP server
    pub async fn spawn<T>(
        tenant: String,
        session: Session<T>,
        cmd: String,
        args: Vec<String>,
    ) -> Result<Self, RemoteProcessError>
    where
        T: DataStream + 'static,
    {
        let mut inner = RemoteProcess::spawn(tenant, session, cmd, args).await?;
        let stdin = inner.stdin.take().map(RemoteLspStdin::new);
        let stdout = inner.stdout.take().map(RemoteLspStdout::new);
        let stderr = inner.stderr.take().map(RemoteLspStderr::new);

        Ok(RemoteLspProcess {
            inner,
            stdin,
            stdout,
            stderr,
        })
    }

    /// Waits for the process to terminate, returning the success status and an optional exit code
    pub async fn wait(self) -> Result<(bool, Option<i32>), RemoteProcessError> {
        self.inner.wait().await
    }
}

impl Deref for RemoteLspProcess {
    type Target = RemoteProcess;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for RemoteLspProcess {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

/// A handle to a remote LSP process' standard input (stdin)
#[derive(Debug)]
pub struct RemoteLspStdin {
    inner: RemoteStdin,
    buf: Option<String>,
}

impl RemoteLspStdin {
    pub fn new(inner: RemoteStdin) -> Self {
        Self { inner, buf: None }
    }

    /// Writes data to the stdin of a specific remote process
    pub async fn write(&mut self, data: &str) -> io::Result<()> {
        // Create or insert into our buffer
        match &mut self.buf {
            Some(buf) => buf.push_str(data),
            None => self.buf = Some(data.to_string()),
        }

        // Read LSP messages from our internal buffer
        let buf = self.buf.take().unwrap();
        let (remainder, queue) = read_lsp_messages(buf)?;
        self.buf = remainder;

        // Process and then send out each LSP message in our queue
        for mut data in queue {
            // Convert distant:// to file://
            data.mut_content().convert_distant_scheme_to_local();
            data.refresh_content_length();
            self.inner.write(&data.to_string()).await?;
        }

        Ok(())
    }
}

/// A handle to a remote LSP process' standard output (stdout)
#[derive(Debug)]
pub struct RemoteLspStdout {
    read_task: JoinHandle<()>,
    rx: mpsc::Receiver<io::Result<String>>,
}

impl RemoteLspStdout {
    pub fn new(inner: RemoteStdout) -> Self {
        let (read_task, rx) = spawn_read_task(Box::pin(futures::stream::unfold(
            inner,
            |mut inner| async move {
                match inner.read().await {
                    Ok(res) => Some((res, inner)),
                    Err(_) => None,
                }
            },
        )));

        Self { read_task, rx }
    }

    pub async fn read(&mut self) -> io::Result<String> {
        self.rx
            .recv()
            .await
            .ok_or_else(|| io::Error::from(io::ErrorKind::BrokenPipe))?
    }
}

impl Drop for RemoteLspStdout {
    fn drop(&mut self) {
        self.read_task.abort();
        self.rx.close();
    }
}

/// A handle to a remote LSP process' stderr
#[derive(Debug)]
pub struct RemoteLspStderr {
    read_task: JoinHandle<()>,
    rx: mpsc::Receiver<io::Result<String>>,
}

impl RemoteLspStderr {
    pub fn new(inner: RemoteStderr) -> Self {
        let (read_task, rx) = spawn_read_task(Box::pin(futures::stream::unfold(
            inner,
            |mut inner| async move {
                match inner.read().await {
                    Ok(res) => Some((res, inner)),
                    Err(_) => None,
                }
            },
        )));

        Self { read_task, rx }
    }

    pub async fn read(&mut self) -> io::Result<String> {
        self.rx
            .recv()
            .await
            .ok_or_else(|| io::Error::from(io::ErrorKind::BrokenPipe))?
    }
}

impl Drop for RemoteLspStderr {
    fn drop(&mut self) {
        self.read_task.abort();
        self.rx.close();
    }
}

fn spawn_read_task<S>(mut stream: S) -> (JoinHandle<()>, mpsc::Receiver<io::Result<String>>)
where
    S: Stream<Item = String> + Send + Unpin + 'static,
{
    let (tx, rx) = mpsc::channel::<io::Result<String>>(1);
    let read_task = tokio::spawn(async move {
        let mut task_buf: Option<String> = None;

        while let Some(data) = stream.next().await {
            // Create or insert into our buffer
            match &mut task_buf {
                Some(buf) => buf.push_str(&data),
                None => task_buf = Some(data),
            }

            // Read LSP messages from our internal buffer
            let buf = task_buf.take().unwrap();
            let (remainder, queue) = match read_lsp_messages(buf) {
                Ok(x) => x,
                Err(x) => {
                    let _ = tx.send(Err(x)).await;
                    break;
                }
            };
            task_buf = remainder;

            // Process and then add each LSP message as output
            if !queue.is_empty() {
                let mut out = String::new();
                for mut data in queue {
                    // Convert file:// to distant://
                    data.mut_content().convert_local_scheme_to_distant();
                    data.refresh_content_length();
                    write!(&mut out, "{}", data).unwrap();
                }
                if tx.send(Ok(out)).await.is_err() {
                    break;
                }
            }
        }
    });

    (read_task, rx)
}

fn read_lsp_messages(input: String) -> io::Result<(Option<String>, Vec<LspData>)> {
    let mut queue = Vec::new();

    // Continue to read complete messages from the input until we either fail to parse or we reach
    // end of input, resetting cursor position back to last successful parse as otherwise the
    // cursor may have moved partially from lsp successfully reading the start of a message
    let mut cursor = Cursor::new(input);
    let mut pos = 0;
    while let Ok(data) = LspData::from_buf_reader(&mut cursor) {
        queue.push(data);
        pos = cursor.position();
    }
    cursor.set_position(pos);

    // Keep remainder of string not processed as LSP message in buffer
    let remainder = if (cursor.position() as usize) < cursor.get_ref().len() {
        let mut buf = String::new();
        cursor.read_to_string(&mut buf)?;
        Some(buf)
    } else {
        None
    };

    Ok((remainder, queue))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        data::{Request, RequestData, Response, ResponseData},
        net::{InmemoryStream, Transport},
    };
    use std::{future::Future, time::Duration};

    /// Timeout used with timeout function
    const TIMEOUT: Duration = Duration::from_millis(50);

    // Configures an lsp process with a means to send & receive data from outside
    async fn spawn_lsp_process() -> (Transport<InmemoryStream>, RemoteLspProcess) {
        let (mut t1, t2) = Transport::make_pair();
        let session = Session::initialize(t2).unwrap();
        let spawn_task = tokio::spawn(RemoteLspProcess::spawn(
            String::from("test-tenant"),
            session,
            String::from("cmd"),
            vec![String::from("arg")],
        ));

        // Wait until we get the request from the session
        let req = t1.receive::<Request>().await.unwrap().unwrap();

        // Send back a response through the session
        t1.send(Response::new(
            "test-tenant",
            Some(req.id),
            vec![ResponseData::ProcStart { id: rand::random() }],
        ))
        .await
        .unwrap();

        // Wait for the process to be ready
        let proc = spawn_task.await.unwrap().unwrap();
        (t1, proc)
    }

    fn make_lsp_msg<T>(value: T) -> String
    where
        T: serde::Serialize,
    {
        let content = serde_json::to_string_pretty(&value).unwrap();
        format!("Content-Length: {}\r\n\r\n{}", content.len(), content)
    }

    async fn timeout<F, R>(duration: Duration, f: F) -> io::Result<R>
    where
        F: Future<Output = R>,
    {
        tokio::select! {
            res = f => {
                Ok(res)
            }
            _ = tokio::time::sleep(duration) => {
                Err(io::Error::from(io::ErrorKind::TimedOut))
            }
        }
    }

    #[tokio::test]
    async fn stdin_write_should_only_send_out_complete_lsp_messages() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        proc.stdin
            .as_mut()
            .unwrap()
            .write(&make_lsp_msg(serde_json::json!({
                "field1": "a",
                "field2": "b",
            })))
            .await
            .unwrap();

        // Validate that the outgoing req is a complete LSP message
        let req = transport.receive::<Request>().await.unwrap().unwrap();
        assert_eq!(req.payload.len(), 1, "Unexpected payload size");
        match &req.payload[0] {
            RequestData::ProcStdin { data, .. } => {
                assert_eq!(
                    data,
                    &make_lsp_msg(serde_json::json!({
                        "field1": "a",
                        "field2": "b",
                    }))
                );
            }
            x => panic!("Unexpected request: {:?}", x),
        }
    }

    #[tokio::test]
    async fn stdin_write_should_support_buffering_output_until_a_complete_lsp_message_is_composed()
    {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));
        let (msg_a, msg_b) = msg.split_at(msg.len() / 2);

        // Write part of the message that isn't finished
        proc.stdin.as_mut().unwrap().write(msg_a).await.unwrap();

        // Verify that nothing has been sent out yet
        // NOTE: Yield to ensure that data would be waiting at the transport if it was sent
        tokio::task::yield_now().await;
        let result = timeout(TIMEOUT, transport.receive::<Request>()).await;
        assert!(result.is_err(), "Unexpectedly got data: {:?}", result);

        // Write remainder of message
        proc.stdin.as_mut().unwrap().write(msg_b).await.unwrap();

        // Validate that the outgoing req is a complete LSP message
        let req = transport.receive::<Request>().await.unwrap().unwrap();
        assert_eq!(req.payload.len(), 1, "Unexpected payload size");
        match &req.payload[0] {
            RequestData::ProcStdin { data, .. } => {
                assert_eq!(
                    data,
                    &make_lsp_msg(serde_json::json!({
                        "field1": "a",
                        "field2": "b",
                    }))
                );
            }
            x => panic!("Unexpected request: {:?}", x),
        }
    }

    #[tokio::test]
    async fn stdin_write_should_only_consume_a_complete_lsp_message_even_if_more_is_written() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));

        let extra = "Content-Length: 123";

        // Write a full message plus some extra
        proc.stdin
            .as_mut()
            .unwrap()
            .write(&format!("{}{}", msg, extra))
            .await
            .unwrap();

        // Validate that the outgoing req is a complete LSP message
        let req = transport.receive::<Request>().await.unwrap().unwrap();
        assert_eq!(req.payload.len(), 1, "Unexpected payload size");
        match &req.payload[0] {
            RequestData::ProcStdin { data, .. } => {
                assert_eq!(
                    data,
                    &make_lsp_msg(serde_json::json!({
                        "field1": "a",
                        "field2": "b",
                    }))
                );
            }
            x => panic!("Unexpected request: {:?}", x),
        }

        // Also validate that the internal buffer still contains the extra
        assert_eq!(
            proc.stdin.unwrap().buf.unwrap(),
            extra,
            "Extra was not retained"
        );
    }

    #[tokio::test]
    async fn stdin_write_should_support_sending_out_multiple_lsp_messages_if_all_received_at_once()
    {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg_1 = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));
        let msg_2 = make_lsp_msg(serde_json::json!({
            "field1": "c",
            "field2": "d",
        }));

        // Write two full messages at once
        proc.stdin
            .as_mut()
            .unwrap()
            .write(&format!("{}{}", msg_1, msg_2))
            .await
            .unwrap();

        // Validate that the first outgoing req is a complete LSP message matching first
        let req = transport.receive::<Request>().await.unwrap().unwrap();
        assert_eq!(req.payload.len(), 1, "Unexpected payload size");
        match &req.payload[0] {
            RequestData::ProcStdin { data, .. } => {
                assert_eq!(
                    data,
                    &make_lsp_msg(serde_json::json!({
                        "field1": "a",
                        "field2": "b",
                    }))
                );
            }
            x => panic!("Unexpected request: {:?}", x),
        }

        // Validate that the second outgoing req is a complete LSP message matching second
        let req = transport.receive::<Request>().await.unwrap().unwrap();
        assert_eq!(req.payload.len(), 1, "Unexpected payload size");
        match &req.payload[0] {
            RequestData::ProcStdin { data, .. } => {
                assert_eq!(
                    data,
                    &make_lsp_msg(serde_json::json!({
                        "field1": "c",
                        "field2": "d",
                    }))
                );
            }
            x => panic!("Unexpected request: {:?}", x),
        }
    }

    #[tokio::test]
    async fn stdin_write_should_convert_content_with_distant_scheme_to_file_scheme() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        proc.stdin
            .as_mut()
            .unwrap()
            .write(&make_lsp_msg(serde_json::json!({
                "field1": "distant://some/path",
                "field2": "file://other/path",
            })))
            .await
            .unwrap();

        // Validate that the outgoing req is a complete LSP message
        let req = transport.receive::<Request>().await.unwrap().unwrap();
        assert_eq!(req.payload.len(), 1, "Unexpected payload size");
        match &req.payload[0] {
            RequestData::ProcStdin { data, .. } => {
                // Verify the contents AND headers are as expected; in this case,
                // this will also ensure that the Content-Length is adjusted
                // when the distant scheme was changed to file
                assert_eq!(
                    data,
                    &make_lsp_msg(serde_json::json!({
                        "field1": "file://some/path",
                        "field2": "file://other/path",
                    }))
                );
            }
            x => panic!("Unexpected request: {:?}", x),
        }
    }

    #[tokio::test]
    async fn stdout_read_should_yield_lsp_messages_as_strings() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        // Send complete LSP message as stdout to process
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStdout {
                    id: proc.id(),
                    data: make_lsp_msg(serde_json::json!({
                        "field1": "a",
                        "field2": "b",
                    })),
                }],
            ))
            .await
            .unwrap();

        // Receive complete message as stdout from process
        let out = proc.stdout.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            out,
            make_lsp_msg(serde_json::json!({
                "field1": "a",
                "field2": "b",
            }))
        );
    }

    #[tokio::test]
    async fn stdout_read_should_only_yield_complete_lsp_messages() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));
        let (msg_a, msg_b) = msg.split_at(msg.len() / 2);

        // Send half of LSP message over stdout
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStdout {
                    id: proc.id(),
                    data: msg_a.to_string(),
                }],
            ))
            .await
            .unwrap();

        // Verify that remote process has not received a complete message yet
        // NOTE: Yield to ensure that data would be waiting at the transport if it was sent
        tokio::task::yield_now().await;
        let result = timeout(TIMEOUT, proc.stdout.as_mut().unwrap().read()).await;
        assert!(result.is_err(), "Unexpectedly got data: {:?}", result);

        // Send other half of LSP message over stdout
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStdout {
                    id: proc.id(),
                    data: msg_b.to_string(),
                }],
            ))
            .await
            .unwrap();

        // Receive complete message as stdout from process
        let out = proc.stdout.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            out,
            make_lsp_msg(serde_json::json!({
                "field1": "a",
                "field2": "b",
            }))
        );
    }

    #[tokio::test]
    async fn stdout_read_should_only_consume_a_complete_lsp_message_even_if_more_output_is_available(
    ) {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));
        let extra = "some extra content";

        // Send complete LSP message as stdout to process
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStdout {
                    id: proc.id(),
                    data: format!("{}{}", msg, extra),
                }],
            ))
            .await
            .unwrap();

        // Receive complete message as stdout from process
        let out = proc.stdout.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            out,
            make_lsp_msg(serde_json::json!({
                "field1": "a",
                "field2": "b",
            }))
        );

        // Verify nothing else was sent
        let result = timeout(TIMEOUT, proc.stdout.as_mut().unwrap().read()).await;
        assert!(
            result.is_err(),
            "Unexpected extra content received on stdout"
        );
    }

    #[tokio::test]
    async fn stdout_read_should_support_yielding_multiple_lsp_messages_if_all_received_at_once() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg_1 = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));
        let msg_2 = make_lsp_msg(serde_json::json!({
            "field1": "c",
            "field2": "d",
        }));

        // Send complete LSP message as stdout to process
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStdout {
                    id: proc.id(),
                    data: format!("{}{}", msg_1, msg_2),
                }],
            ))
            .await
            .unwrap();

        // Should send both messages back together as a single string
        let out = proc.stdout.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            out,
            format!(
                "{}{}",
                make_lsp_msg(serde_json::json!({
                    "field1": "a",
                    "field2": "b",
                })),
                make_lsp_msg(serde_json::json!({
                    "field1": "c",
                    "field2": "d",
                }))
            )
        );
    }

    #[tokio::test]
    async fn stdout_read_should_convert_content_with_file_scheme_to_distant_scheme() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        // Send complete LSP message as stdout to process
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStdout {
                    id: proc.id(),
                    data: make_lsp_msg(serde_json::json!({
                        "field1": "distant://some/path",
                        "field2": "file://other/path",
                    })),
                }],
            ))
            .await
            .unwrap();

        // Receive complete message as stdout from process
        let out = proc.stdout.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            out,
            make_lsp_msg(serde_json::json!({
                "field1": "distant://some/path",
                "field2": "distant://other/path",
            }))
        );
    }

    #[tokio::test]
    async fn stderr_read_should_yield_lsp_messages_as_strings() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        // Send complete LSP message as stderr to process
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStderr {
                    id: proc.id(),
                    data: make_lsp_msg(serde_json::json!({
                        "field1": "a",
                        "field2": "b",
                    })),
                }],
            ))
            .await
            .unwrap();

        // Receive complete message as stderr from process
        let err = proc.stderr.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            err,
            make_lsp_msg(serde_json::json!({
                "field1": "a",
                "field2": "b",
            }))
        );
    }

    #[tokio::test]
    async fn stderr_read_should_only_yield_complete_lsp_messages() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));
        let (msg_a, msg_b) = msg.split_at(msg.len() / 2);

        // Send half of LSP message over stderr
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStderr {
                    id: proc.id(),
                    data: msg_a.to_string(),
                }],
            ))
            .await
            .unwrap();

        // Verify that remote process has not received a complete message yet
        // NOTE: Yield to ensure that data would be waiting at the transport if it was sent
        tokio::task::yield_now().await;
        let result = timeout(TIMEOUT, proc.stderr.as_mut().unwrap().read()).await;
        assert!(result.is_err(), "Unexpectedly got data: {:?}", result);

        // Send other half of LSP message over stderr
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStderr {
                    id: proc.id(),
                    data: msg_b.to_string(),
                }],
            ))
            .await
            .unwrap();

        // Receive complete message as stderr from process
        let err = proc.stderr.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            err,
            make_lsp_msg(serde_json::json!({
                "field1": "a",
                "field2": "b",
            }))
        );
    }

    #[tokio::test]
    async fn stderr_read_should_only_consume_a_complete_lsp_message_even_if_more_errput_is_available(
    ) {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));
        let extra = "some extra content";

        // Send complete LSP message as stderr to process
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStderr {
                    id: proc.id(),
                    data: format!("{}{}", msg, extra),
                }],
            ))
            .await
            .unwrap();

        // Receive complete message as stderr from process
        let err = proc.stderr.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            err,
            make_lsp_msg(serde_json::json!({
                "field1": "a",
                "field2": "b",
            }))
        );

        // Verify nothing else was sent
        let result = timeout(TIMEOUT, proc.stderr.as_mut().unwrap().read()).await;
        assert!(
            result.is_err(),
            "Unexpected extra content received on stderr"
        );
    }

    #[tokio::test]
    async fn stderr_read_should_support_yielding_multiple_lsp_messages_if_all_received_at_once() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        let msg_1 = make_lsp_msg(serde_json::json!({
            "field1": "a",
            "field2": "b",
        }));
        let msg_2 = make_lsp_msg(serde_json::json!({
            "field1": "c",
            "field2": "d",
        }));

        // Send complete LSP message as stderr to process
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStderr {
                    id: proc.id(),
                    data: format!("{}{}", msg_1, msg_2),
                }],
            ))
            .await
            .unwrap();

        // Should send both messages back together as a single string
        let err = proc.stderr.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            err,
            format!(
                "{}{}",
                make_lsp_msg(serde_json::json!({
                    "field1": "a",
                    "field2": "b",
                })),
                make_lsp_msg(serde_json::json!({
                    "field1": "c",
                    "field2": "d",
                }))
            )
        );
    }

    #[tokio::test]
    async fn stderr_read_should_convert_content_with_file_scheme_to_distant_scheme() {
        let (mut transport, mut proc) = spawn_lsp_process().await;

        // Send complete LSP message as stderr to process
        transport
            .send(Response::new(
                "test-tenant",
                None,
                vec![ResponseData::ProcStderr {
                    id: proc.id(),
                    data: make_lsp_msg(serde_json::json!({
                        "field1": "distant://some/path",
                        "field2": "file://other/path",
                    })),
                }],
            ))
            .await
            .unwrap();

        // Receive complete message as stderr from process
        let err = proc.stderr.as_mut().unwrap().read().await.unwrap();
        assert_eq!(
            err,
            make_lsp_msg(serde_json::json!({
                "field1": "distant://some/path",
                "field2": "distant://other/path",
            }))
        );
    }
}