on master help sign in
lsp: Don't send notifications until initialize completes

Then send open events for all documents with the LSP attached.

commit46f3c69f06cc55f36bcc6244a9f96c2481836dea authorBlaž Hrastnik <blaz@mxxn.io> dateThu 2 Sep 2021, 13:55 (5 years ago) parent2793ff3
4 files changed+111−52
helix-lsp/src/lib.rs+49−49 helix-lsp/src/transport.rs+28−1 helix-term/src/application.rs+31 helix-view/src/editor.rs+3−2
helix-lsp/src/lib.rs+49−49
@@ -226,6 +226,8 @@ impl MethodCall {
226226
227227#[derive(Debug, PartialEq, Clone)]
228228pub enum Notification {
229+ // we inject this notification to signal the LSP is ready
230+ Initialized,
229231 PublishDiagnostics(lsp::PublishDiagnosticsParams),
230232 ShowMessage(lsp::ShowMessageParams),
231233 LogMessage(lsp::LogMessageParams),
@@ -237,6 +239,7 @@ impl Notification {
237239 use lsp::notification::Notification as _;
238240
239241 let notification = match method {
242+ lsp::notification::Initialized::METHOD => Self::Initialized,
240243 lsp::notification::PublishDiagnostics::METHOD => {
241244 let params: lsp::PublishDiagnosticsParams = params
242245 .parse()
@@ -294,7 +297,7 @@ impl Registry {
294297 }
295298 }
296299
297− pub fn get_by_id(&mut self, id: usize) -> Option<&Client> {
300+ pub fn get_by_id(&self, id: usize) -> Option<&Client> {
298301 self.inner
299302 .values()
300303 .find(|(client_id, _)| client_id == &id)
@@ -302,55 +305,52 @@ impl Registry {
302305 }
303306
304307 pub fn get(&mut self, language_config: &LanguageConfiguration) -> Result<Arc<Client>> {
305− if let Some(config) = &language_config.language_server {
306− // avoid borrow issues
307− let inner = &mut self.inner;
308− let s_incoming = &mut self.incoming;
309−
310− match inner.entry(language_config.scope.clone()) {
311− Entry::Occupied(entry) => Ok(entry.get().1.clone()),
312− Entry::Vacant(entry) => {
313− // initialize a new client
314− let id = self.counter.fetch_add(1, Ordering::Relaxed);
315− let (client, incoming, initialize_notify) = Client::start(
316− &config.command,
317− &config.args,
318− serde_json::from_str(language_config.config.as_deref().unwrap_or("")).ok(),
319− id,
320− )?;
321− s_incoming.push(UnboundedReceiverStream::new(incoming));
322− let client = Arc::new(client);
323−
324− let _client = client.clone();
325− // Initialize the client asynchronously
326− tokio::spawn(async move {
327− use futures_util::TryFutureExt;
328− let value = _client
329− .capabilities
330− .get_or_try_init(|| {
331− _client
332− .initialize()
333− .map_ok(|response| response.capabilities)
334− })
335− .await;
336−
337− value.expect("failed to initialize capabilities");
338−
339− // next up, notify<initialized>
340− _client
341− .notify::<lsp::notification::Initialized>(lsp::InitializedParams {})
342− .await
343− .unwrap();
344−
345− initialize_notify.notify_one();
346− });
347−
348− entry.insert((id, client.clone()));
349− Ok(client)
350− }
308+ let config = match &language_config.language_server {
309+ Some(config) => config,
310+ None => return Err(Error::LspNotDefined),
311+ };
312+
313+ match self.inner.entry(language_config.scope.clone()) {
314+ Entry::Occupied(entry) => Ok(entry.get().1.clone()),
315+ Entry::Vacant(entry) => {
316+ // initialize a new client
317+ let id = self.counter.fetch_add(1, Ordering::Relaxed);
318+ let (client, incoming, initialize_notify) = Client::start(
319+ &config.command,
320+ &config.args,
321+ serde_json::from_str(language_config.config.as_deref().unwrap_or("")).ok(),
322+ id,
323+ )?;
324+ self.incoming.push(UnboundedReceiverStream::new(incoming));
325+ let client = Arc::new(client);
326+
327+ // Initialize the client asynchronously
328+ let _client = client.clone();
329+ tokio::spawn(async move {
330+ use futures_util::TryFutureExt;
331+ let value = _client
332+ .capabilities
333+ .get_or_try_init(|| {
334+ _client
335+ .initialize()
336+ .map_ok(|response| response.capabilities)
337+ })
338+ .await;
339+
340+ value.expect("failed to initialize capabilities");
341+
342+ // next up, notify<initialized>
343+ _client
344+ .notify::<lsp::notification::Initialized>(lsp::InitializedParams {})
345+ .await
346+ .unwrap();
347+
348+ initialize_notify.notify_one();
349+ });
350+
351+ entry.insert((id, client.clone()));
352+ Ok(client)
351353 }
352− } else {
353− Err(Error::LspNotDefined)
354354 }
355355 }
356356
helix-lsp/src/transport.rs+28−1
@@ -64,11 +64,16 @@ impl Transport {
6464
6565 let transport = Arc::new(transport);
6666
67− tokio::spawn(Self::recv(transport.clone(), server_stdout, client_tx));
67+ tokio::spawn(Self::recv(
68+ transport.clone(),
69+ server_stdout,
70+ client_tx.clone(),
71+ ));
6872 tokio::spawn(Self::err(transport.clone(), server_stderr));
6973 tokio::spawn(Self::send(
7074 transport,
7175 server_stdin,
76+ client_tx,
7277 client_rx,
7378 notify.clone(),
7479 ));
@@ -269,6 +274,7 @@ impl Transport {
269274 async fn send(
270275 transport: Arc<Self>,
271276 mut server_stdin: BufWriter<ChildStdin>,
277+ mut client_tx: UnboundedSender<(usize, jsonrpc::Call)>,
272278 mut client_rx: UnboundedReceiver<Payload>,
273279 initialize_notify: Arc<Notify>,
274280 ) {
@@ -303,6 +309,22 @@ impl Transport {
303309 _ = initialize_notify.notified() => { // TODO: notified is technically not cancellation safe
304310 // server successfully initialized
305311 is_pending = false;
312+
313+ use lsp_types::notification::Notification;
314+ // Hack: inject an initialized notification so we trigger code that needs to happen after init
315+ let notification = ServerMessage::Call(jsonrpc::Call::Notification(jsonrpc::Notification {
316+ jsonrpc: None,
317+
318+ method: lsp_types::notification::Initialized::METHOD.to_string(),
319+ params: jsonrpc::Params::None,
320+ }));
321+ match transport.process_server_message(&mut client_tx, notification).await {
322+ Ok(_) => {}
323+ Err(err) => {
324+ error!("err: <- {:?}", err);
325+ }
326+ }
327+
306328 // drain the pending queue and send payloads to server
307329 for msg in pending_messages.drain(..) {
308330 log::info!("Draining pending message {:?}", msg);
@@ -317,6 +339,11 @@ impl Transport {
317339 msg = client_rx.recv() => {
318340 if let Some(msg) = msg {
319341 if is_pending && !is_initialize(&msg) {
342+ // ignore notifications
343+ if let Payload::Notification(_) = msg {
344+ continue;
345+ }
346+
320347 log::info!("Language server not initialized, delaying request");
321348 pending_messages.push(msg);
322349 } else {
helix-term/src/application.rs+31
@@ -275,6 +275,37 @@ impl Application {
275275 };
276276
277277 match notification {
278+ Notification::Initialized => {
279+ let language_server =
280+ match self.editor.language_servers.get_by_id(server_id) {
281+ Some(language_server) => language_server,
282+ None => {
283+ warn!("can't find language server with id `{}`", server_id);
284+ return;
285+ }
286+ };
287+
288+ let docs = self.editor.documents().filter(|doc| {
289+ doc.language_server().map(|server| server.id()) == Some(server_id)
290+ });
291+
292+ // trigger textDocument/didOpen for docs that are already open
293+ for doc in docs {
294+ // TODO: extract and share with editor.open
295+ let language_id = doc
296+ .language()
297+ .and_then(|s| s.split('.').last()) // source.rust
298+ .map(ToOwned::to_owned)
299+ .unwrap_or_default();
300+
301+ tokio::spawn(language_server.text_document_did_open(
302+ doc.url().unwrap(),
303+ doc.version(),
304+ doc.text(),
305+ language_id,
306+ ));
307+ }
308+ }
278309 Notification::PublishDiagnostics(params) => {
279310 let path = params.uri.to_file_path().unwrap();
280311 let doc = self.editor.document_by_path_mut(&path);
helix-view/src/editor.rs+3−2
@@ -255,20 +255,21 @@ impl Editor {
255255 .and_then(|language| self.language_servers.get(language).ok());
256256
257257 if let Some(language_server) = language_server {
258− doc.set_language_server(Some(language_server.clone()));
259−
260258 let language_id = doc
261259 .language()
262260 .and_then(|s| s.split('.').last()) // source.rust
263261 .map(ToOwned::to_owned)
264262 .unwrap_or_default();
265263
264+ // TODO: this now races with on_init code if the init happens too quickly
266265 tokio::spawn(language_server.text_document_did_open(
267266 doc.url().unwrap(),
268267 doc.version(),
269268 doc.text(),
270269 language_id,
271270 ));
271+
272+ doc.set_language_server(Some(language_server));
272273 }
273274
274275 let id = self.documents.insert(doc);