Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lsp: Gracefully shutdown language servers, fix unwraps in transport #287

Merged
merged 3 commits into from
Jun 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions helix-lsp/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,21 @@ impl Client {
self.notify::<lsp::notification::Exit>(())
}

/// Tries to shut down the language server but returns
/// early if server responds with an error.
pub async fn shutdown_and_exit(&self) -> Result<()> {
self.shutdown().await?;
self.exit().await
}

/// Forcefully shuts down the language server ignoring any errors.
pub async fn force_shutdown(&self) -> Result<()> {
if let Err(e) = self.shutdown().await {
log::warn!("language server failed to terminate gracefully - {}", e);
}
self.exit().await
}

// -------------------------------------------------------------------------------------------
// Text document
// -------------------------------------------------------------------------------------------
Expand Down
4 changes: 4 additions & 0 deletions helix-lsp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,10 @@ impl Registry {
Err(Error::LspNotDefined)
}
}

pub fn iter_clients(&self) -> impl Iterator<Item = &Arc<Client>> {
self.inner.values().map(|(_, client)| client)
}
}

#[derive(Debug)]
Expand Down
11 changes: 7 additions & 4 deletions helix-lsp/src/transport.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::Result;
use anyhow::Context;
use jsonrpc_core as jsonrpc;
use log::{error, info};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -90,7 +91,7 @@ impl Transport {

match (parts.next(), parts.next(), parts.next()) {
(Some("Content-Length"), Some(value), None) => {
content_length = Some(value.parse().unwrap());
content_length = Some(value.parse().context("invalid content length")?);
}
(Some(_), Some(_), None) => {}
_ => {
Expand All @@ -103,12 +104,12 @@ impl Transport {
}
}

let content_length = content_length.unwrap();
let content_length = content_length.context("missing content length")?;

//TODO: reuse vector
let mut content = vec![0; content_length];
reader.read_exact(&mut content).await?;
let msg = String::from_utf8(content).unwrap();
let msg = String::from_utf8(content).context("invalid utf8 from server")?;

info!("<- {}", msg);

Expand Down Expand Up @@ -162,7 +163,9 @@ impl Transport {
match msg {
ServerMessage::Output(output) => self.process_request_response(output).await?,
ServerMessage::Call(call) => {
self.client_tx.send((self.id, call)).unwrap();
self.client_tx
.send((self.id, call))
.context("failed to send a message to server")?;
// let notification = Notification::parse(&method, params);
}
};
Expand Down
4 changes: 3 additions & 1 deletion helix-term/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crossterm::{

use tui::layout::Rect;

use futures_util::stream::FuturesUnordered;
use futures_util::{future, stream::FuturesUnordered};

type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
pub type LspCallback =
Expand Down Expand Up @@ -406,6 +406,8 @@ impl Application {

self.event_loop().await;

self.editor.close_language_servers(None).await;

// reset cursor shape
write!(stdout, "\x1B[2 q");

Expand Down
1 change: 1 addition & 0 deletions helix-view/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ once_cell = "1.8"
url = "2"

tokio = { version = "1", features = ["full"] }
futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false }

slotmap = "1"

Expand Down
20 changes: 20 additions & 0 deletions helix-view/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use crate::{theme::Theme, tree::Tree, Document, DocumentId, RegisterSelection, V
use tui::layout::Rect;
use tui::terminal::CursorKind;

use futures_util::future;
use std::path::PathBuf;
use std::time::Duration;

use slotmap::SlotMap;

Expand Down Expand Up @@ -270,4 +272,22 @@ impl Editor {
(None, CursorKind::Hidden)
}
}

/// Closes language servers with timeout. The default timeout is 500 ms, use
/// `timeout` parameter to override this.
pub async fn close_language_servers(
&self,
timeout: Option<u64>,
) -> Result<(), tokio::time::error::Elapsed> {
tokio::time::timeout(
Duration::from_millis(timeout.unwrap_or(500)),
future::join_all(
self.language_servers
.iter_clients()
.map(|client| client.force_shutdown()),
),
)
.await
.map(|_| ())
}
}