lspf 0.5.0

A Rust framework for building extensible LSP language servers
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
//! Lifecycle-hook coverage for the stable catalog boundary (issue #81).
//!
//! `on_initialized` runs at most once, only after a successful initialize
//! transaction; `on_exit` runs before the protocol engine records the close
//! cause that becomes the session `Outcome` and cannot change the LSP exit
//! code that Outcome carries. Every test drives the public `Server::serve`
//! transport seam and asserts on the returned `Outcome` plus what each hook
//! observed, so no assertion depends on a scheduler delay.

use std::borrow::Cow;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;

use bytes::Bytes;
use serde_json::{Value, json};
use tokio::sync::mpsc;

use lspf::types::notification::Notification;
use lspf::{
    Outcome, RawMessage, RequestId, Server, Transport, TransportError, TransportReader,
    TransportWriter,
};

/// A client-bound notification a hook can emit, proving its `Context` client
/// handle is live.
enum HookNotice {}

impl Notification for HookNotice {
    type Params = Value;
    const METHOD: &'static str = "test/hook-notice";
}

#[derive(Default)]
struct AppState {
    initialized_runs: AtomicUsize,
    exit_runs: AtomicUsize,
}

// --- In-memory transport -----------------------------------------------------

struct ChannelTransport {
    in_rx: mpsc::UnboundedReceiver<RawMessage>,
    out_tx: mpsc::UnboundedSender<RawMessage>,
}

struct ChannelReader {
    in_rx: mpsc::UnboundedReceiver<RawMessage>,
}

struct ChannelWriter {
    out_tx: mpsc::UnboundedSender<RawMessage>,
}

impl Transport for ChannelTransport {
    type Reader = ChannelReader;
    type Writer = ChannelWriter;

    fn split(self) -> (Self::Reader, Self::Writer) {
        (
            ChannelReader { in_rx: self.in_rx },
            ChannelWriter {
                out_tx: self.out_tx,
            },
        )
    }
}

impl TransportReader for ChannelReader {
    async fn recv(&mut self) -> Result<RawMessage, TransportError> {
        self.in_rx.recv().await.ok_or(TransportError::Closed)
    }
}

impl TransportWriter for ChannelWriter {
    async fn send(&mut self, msg: RawMessage) -> Result<(), TransportError> {
        self.out_tx.send(msg).map_err(|_| TransportError::Closed)
    }

    async fn shutdown(self) -> Result<(), TransportError> {
        Ok(())
    }
}

// --- Envelope helpers --------------------------------------------------------

fn request(id: i32, method: &'static str, params: serde_json::Value) -> RawMessage {
    RawMessage::Request {
        id: RequestId::Number(id),
        method: Cow::Borrowed(method),
        params: Bytes::from(serde_json::to_vec(&params).unwrap()),
    }
}

fn initialize_request(id: i32) -> RawMessage {
    request(
        id,
        "initialize",
        json!({ "processId": null, "rootUri": null, "capabilities": {} }),
    )
}

fn shutdown_request(id: i32) -> RawMessage {
    request(id, "shutdown", json!(null))
}

fn notification(method: &'static str, params: serde_json::Value) -> RawMessage {
    RawMessage::Notification {
        method: Cow::Borrowed(method),
        params: Bytes::from(serde_json::to_vec(&params).unwrap()),
    }
}

fn initialized() -> RawMessage {
    notification("initialized", json!({}))
}

fn exit() -> RawMessage {
    RawMessage::Notification {
        method: Cow::Borrowed("exit"),
        params: Bytes::from_static(b"null"),
    }
}

/// Drive `server` with `messages` in order, waiting for each request's
/// response before sending the next message. Drops the transport afterwards so
/// `serve` returns once everything is processed, and returns both the outbox
/// and the session [`Outcome`].
async fn drive<S: Send + Sync + 'static>(
    server: Server<S>,
    messages: Vec<RawMessage>,
) -> (Vec<RawMessage>, Outcome) {
    let (in_tx, in_rx) = mpsc::unbounded_channel::<RawMessage>();
    let (out_tx, mut out_rx) = mpsc::unbounded_channel::<RawMessage>();
    let transport = ChannelTransport { in_rx, out_tx };

    let mut handle = tokio::spawn(async move { server.serve(transport).await });
    let mut server_done = false;
    let mut outbox = Vec::new();

    'messages: for msg in messages {
        let response_id = msg.id().cloned();
        // A failed initialize transaction terminates the connection, so a send
        // can legitimately race the disconnect; stop feeding the channel
        // instead of panicking on `SendError`.
        if in_tx.send(msg).is_err() {
            break;
        }
        if let Some(response_id) = response_id {
            tokio::select! {
                response = out_rx.recv() => {
                    if let Some(response) = response {
                        assert_eq!(response.id(), Some(&response_id));
                        outbox.push(response);
                    } else {
                        (&mut handle)
                            .await
                            .expect("server task did not panic")
                            .expect("serve ended cleanly");
                        server_done = true;
                        break 'messages;
                    }
                }
                result = &mut handle => {
                    result
                        .expect("server task did not panic")
                        .expect("serve ended cleanly");
                    server_done = true;
                    break 'messages;
                }
            }
        }
    }
    drop(in_tx);

    let outcome = if !server_done {
        tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("serve returned within 2s")
            .expect("server task did not panic")
            .expect("serve ended cleanly")
    } else {
        handle
            .await
            .expect("server task did not panic")
            .expect("serve ended cleanly")
    };

    outbox.extend(std::iter::from_fn(|| out_rx.try_recv().ok()));
    (outbox, outcome)
}

fn hook_notices(outbox: &[RawMessage]) -> usize {
    outbox
        .iter()
        .filter(|m| m.method() == Some("test/hook-notice"))
        .count()
}

// --- Tests -------------------------------------------------------------------

/// The initialized hook runs exactly once, and only for the first
/// running-state `initialized` notification: a repeat is a no-op.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn initialized_hook_runs_once_after_successful_initialize() {
    let state = Arc::new(AppState::default());
    let server = Server::builder(Arc::clone(&state))
        .on_initialized(|state, _ctx, _params| async move {
            state.initialized_runs.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("server builds");

    let (outbox, outcome) = drive(
        server,
        vec![initialize_request(1), initialized(), initialized(), exit()],
    )
    .await;

    assert_eq!(outcome, Outcome::Exit { code: 1 });
    assert_eq!(
        state.initialized_runs.load(Ordering::SeqCst),
        1,
        "the hook runs once, for the first running-state initialized"
    );
    assert_eq!(hook_notices(&outbox), 0);
}

/// The initialized hook receives typed params and a live `Context`: its client
/// handle can send a notification that reaches the wire.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn initialized_hook_receives_typed_params_and_a_live_context() {
    let state = Arc::new(AppState::default());
    let server = Server::builder(Arc::clone(&state))
        .on_initialized(|state, ctx, params| async move {
            state.initialized_runs.fetch_add(1, Ordering::SeqCst);
            // The hook dispatches on typed, decoded `InitializedParams`.
            let _ = params;
            let _ = ctx
                .client()
                .notify::<HookNotice>(json!({ "from": "initialized" }));
        })
        .build()
        .expect("server builds");

    let (outbox, outcome) = drive(server, vec![initialize_request(1), initialized(), exit()]).await;

    assert_eq!(outcome, Outcome::Exit { code: 1 });
    assert_eq!(state.initialized_runs.load(Ordering::SeqCst), 1);
    assert_eq!(
        hook_notices(&outbox),
        1,
        "the hook's client notification reached the wire"
    );
}

/// An `initialized` notification received before `initialize` is ignored
/// without consuming the hook, so the later, valid notification still runs it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn initialized_before_initialize_is_ignored_and_does_not_consume_the_hook() {
    let state = Arc::new(AppState::default());
    let server = Server::builder(Arc::clone(&state))
        .on_initialized(|state, _ctx, _params| async move {
            state.initialized_runs.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("server builds");

    let (outbox, outcome) = drive(
        server,
        vec![initialized(), initialize_request(1), initialized(), exit()],
    )
    .await;

    assert_eq!(outcome, Outcome::Exit { code: 1 });
    assert_eq!(
        state.initialized_runs.load(Ordering::SeqCst),
        1,
        "only the running-state initialized notification runs the hook"
    );
    assert_eq!(hook_notices(&outbox), 0);
}

/// An `initialized` notification after `shutdown` is ignored like any other
/// user work in the shutting-down state, without running the hook.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn initialized_after_shutdown_is_ignored() {
    let state = Arc::new(AppState::default());
    let server = Server::builder(Arc::clone(&state))
        .on_initialized(|state, _ctx, _params| async move {
            state.initialized_runs.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("server builds");

    let (outbox, outcome) = drive(
        server,
        vec![
            initialize_request(1),
            shutdown_request(2),
            initialized(),
            exit(),
        ],
    )
    .await;

    assert_eq!(outcome, Outcome::Exit { code: 0 });
    assert_eq!(
        state.initialized_runs.load(Ordering::SeqCst),
        0,
        "initialized after shutdown never runs the hook"
    );
    assert_eq!(hook_notices(&outbox), 0);
}

/// Malformed `initialized` params are dropped without running the hook, and
/// the session continues. Both wire spellings of the empty params object —
/// `{}` and `null` — are accepted.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn malformed_initialized_params_skip_the_hook_but_valid_empty_ones_run_it() {
    let state = Arc::new(AppState::default());
    let server = Server::builder(Arc::clone(&state))
        .on_initialized(|state, _ctx, _params| async move {
            state.initialized_runs.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("server builds");

    // `initialized` with a non-object payload decodes as malformed and is
    // dropped; `null` (no params at all) is the other accepted spelling.
    let (outbox, outcome) = drive(
        server,
        vec![
            initialize_request(1),
            notification("initialized", json!(17)),
            RawMessage::Notification {
                method: Cow::Borrowed("initialized"),
                params: Bytes::from_static(b"null"),
            },
            exit(),
        ],
    )
    .await;

    assert_eq!(outcome, Outcome::Exit { code: 1 });
    assert_eq!(
        state.initialized_runs.load(Ordering::SeqCst),
        1,
        "the malformed notification is dropped; the null-params one runs the hook"
    );
    assert_eq!(hook_notices(&outbox), 0);
}

/// The exit hook runs before the engine records the close cause and observes
/// a live `Context`, yet the reported exit code stays engine-owned: 1 without
/// a preceding `shutdown`.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exit_hook_runs_with_a_live_context_and_cannot_change_the_outcome() {
    let state = Arc::new(AppState::default());
    let server = Server::builder(Arc::clone(&state))
        .on_exit(|state, ctx| async move {
            state.exit_runs.fetch_add(1, Ordering::SeqCst);
            let _ = ctx.client().notify::<HookNotice>(json!({ "from": "exit" }));
        })
        .build()
        .expect("server builds");

    let (outbox, outcome) = drive(server, vec![initialize_request(1), exit()]).await;

    assert_eq!(
        outcome,
        Outcome::Exit { code: 1 },
        "the hook cannot override the lifecycle-derived exit code"
    );
    assert_eq!(state.exit_runs.load(Ordering::SeqCst), 1);
    assert_eq!(
        hook_notices(&outbox),
        1,
        "the exit hook's client notification is drained before the writer shuts down"
    );
}

/// After a successful `shutdown` the exit hook still runs, and the outcome
/// still reports the engine-owned code 0.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exit_hook_runs_after_shutdown_with_code_zero() {
    let state = Arc::new(AppState::default());
    let server = Server::builder(Arc::clone(&state))
        .on_exit(|state, _ctx| async move {
            state.exit_runs.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("server builds");

    let (outbox, outcome) = drive(
        server,
        vec![initialize_request(1), shutdown_request(2), exit()],
    )
    .await;

    assert_eq!(outcome, Outcome::Exit { code: 0 });
    assert_eq!(state.exit_runs.load(Ordering::SeqCst), 1);
    assert_eq!(hook_notices(&outbox), 0);
}

/// An `exit` received before `initialize` has no established Workspace to hand
/// the hook, so it is skipped and the connection still closes with code 1.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exit_before_initialize_skips_the_hook_and_reports_code_one() {
    let state = Arc::new(AppState::default());
    let server = Server::builder(Arc::clone(&state))
        .on_exit(|state, _ctx| async move {
            state.exit_runs.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("server builds");

    let (outbox, outcome) = drive(server, vec![exit()]).await;

    assert_eq!(outcome, Outcome::Exit { code: 1 });
    assert_eq!(state.exit_runs.load(Ordering::SeqCst), 0);
    assert_eq!(hook_notices(&outbox), 0);
}

/// The exit hook observes the post-initialize Workspace: the same handle every
/// handler reads, already carrying the initialize params.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exit_hook_observes_the_established_workspace() {
    let observed_root = Arc::new(AtomicBool::new(false));
    let root_flag = Arc::clone(&observed_root);
    let server = Server::builder(AppState::default())
        .on_exit(move |_state, ctx| {
            let root_flag = Arc::clone(&root_flag);
            async move {
                root_flag.store(ctx.workspace().root_uri().is_some(), Ordering::SeqCst);
            }
        })
        .build()
        .expect("server builds");

    let (in_tx, in_rx) = mpsc::unbounded_channel::<RawMessage>();
    let (out_tx, mut out_rx) = mpsc::unbounded_channel::<RawMessage>();
    let transport = ChannelTransport { in_rx, out_tx };
    let serving = tokio::spawn(async move { server.serve(transport).await });

    in_tx
        .send(request(
            1,
            "initialize",
            json!({
                "processId": null,
                "rootUri": "file:///project",
                "capabilities": {}
            }),
        ))
        .unwrap();
    let response = tokio::time::timeout(Duration::from_secs(2), out_rx.recv())
        .await
        .expect("initialize response within 2s")
        .expect("outgoing channel open");
    assert_eq!(response.id(), Some(&RequestId::Number(1)));

    in_tx.send(exit()).unwrap();

    let outcome = tokio::time::timeout(Duration::from_secs(2), serving)
        .await
        .expect("serving returned within 2s")
        .expect("serving did not panic")
        .expect("serve ended cleanly");
    assert_eq!(outcome, Outcome::Exit { code: 1 });
    assert!(
        observed_root.load(Ordering::SeqCst),
        "the exit hook reads the Workspace established from InitializeParams"
    );
}