Repository navigation
Expand file tree
/
Copy pathserver.rs
More file actions
335 lines (294 loc) · 11.3 KB
/
Copy pathserver.rs
File metadata and controls
335 lines (294 loc) · 11.3 KB
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
//! Scheduling, I/O, and API endpoints.
use self::schedule::spawn_main_loop;
use crate::PositionEncoding;
use crate::capabilities::{ResolvedClientCapabilities, server_capabilities};
use crate::session::{ClientName, InitializationOptions, Session, warn_about_unknown_options};
use anyhow::Context;
use lsp_server::{Connection, ErrorCode, Message, Response};
use lsp_types::{
ClientCapabilities, InitializeParams, MessageType, Uri, WorkspaceFolders,
WorkspaceFoldersInitializeParams,
};
use ruff_db::system::System;
use std::num::NonZeroUsize;
use std::panic::{PanicHookInfo, RefUnwindSafe};
use std::sync::Arc;
mod api;
mod lazy_work_done_progress;
mod main_loop;
mod schedule;
use crate::session::client::Client;
pub(crate) use api::Error;
pub(crate) use api::publish_settings_diagnostics;
pub(crate) use main_loop::{
Action, ConnectionSender, Event, MainLoopReceiver, MainLoopSender, SendRequest,
};
pub(crate) type Result<T> = std::result::Result<T, api::Error>;
pub struct Server {
connection: Connection,
worker_threads: NonZeroUsize,
main_loop_receiver: MainLoopReceiver,
main_loop_sender: MainLoopSender,
session: Session,
}
impl Server {
pub fn new(
worker_threads: NonZeroUsize,
connection: Connection,
native_system: Arc<dyn System + 'static + Send + Sync + RefUnwindSafe>,
in_test: bool,
) -> crate::Result<Self> {
let (id, init_value) = connection.initialize_start()?;
let InitializeParams {
initialization_options,
capabilities: client_capabilities,
workspace_folders_initialize_params:
WorkspaceFoldersInitializeParams { workspace_folders },
client_info,
..
} = serde_json::from_value(init_value)
.context("Failed to deserialize initialization parameters")?;
let (initialization_options, deserialization_error) =
match InitializationOptions::from_value(initialization_options) {
Ok(options) => options,
Err(error) => {
connection.sender.send(Message::Response(Response::new_err(
id,
ErrorCode::InvalidParams as i32,
format!("Invalid initialization options: {error:#}"),
)))?;
return Err(error).context("Failed to deserialize initialization options");
}
};
if !in_test {
crate::logging::init_logging(
initialization_options.log_level.unwrap_or_default(),
initialization_options.log_file.as_deref(),
);
}
if let Some(error) = deserialization_error {
tracing::error!("Failed to deserialize initialization options: {error}");
}
tracing::debug!("Client info: {client_info:#?}");
tracing::debug!("Initialization options: {initialization_options:#?}");
let resolved_client_capabilities = ResolvedClientCapabilities::new(&client_capabilities);
tracing::debug!("Resolved client capabilities: {resolved_client_capabilities}");
let position_encoding = Self::find_best_position_encoding(&client_capabilities);
let server_capabilities =
server_capabilities(position_encoding, resolved_client_capabilities);
let version = ruff_db::program_version().unwrap_or("Unknown");
tracing::info!("Version: {version}");
connection.initialize_finish(
id,
serde_json::json!({
"capabilities": server_capabilities,
"serverInfo": {
"name": crate::SERVER_NAME,
"version": version
}
}),
)?;
// The number 32 was chosen arbitrarily. The main goal was to have enough capacity to queue
// some responses before blocking.
let (main_loop_sender, main_loop_receiver) = crossbeam::channel::bounded(32);
let client = Client::new(main_loop_sender.clone(), connection.sender.clone());
let unknown_options = &initialization_options.options.unknown;
if !unknown_options.is_empty() {
warn_about_unknown_options(&client, None, unknown_options);
}
// Get workspace URLs without settings - settings will come from workspace/configuration
let workspace_urls = workspace_folders
.and_then(|folders| {
if let WorkspaceFolders::WorkspaceFolderList(folders) = folders
&& !folders.is_empty()
{
Some(folders)
} else {
None
}
})
.map(|folders| {
folders
.into_iter()
.map(|folder| folder.uri)
.collect::<Vec<_>>()
})
.or_else(|| {
let current_dir = native_system
.current_directory()
.as_std_path()
.to_path_buf();
tracing::warn!(
"No workspace(s) were provided during initialization. \
Using the current working directory from the fallback system as a \
default workspace: {}",
current_dir.display()
);
let uri = Uri::from_file_path(current_dir).ok()?;
Some(vec![uri])
})
.ok_or_else(|| {
anyhow::anyhow!(
"Failed to get the current working directory while creating a \
default workspace."
)
})?;
Ok(Self {
connection,
worker_threads,
main_loop_receiver,
main_loop_sender,
session: Session::new(
resolved_client_capabilities,
position_encoding,
workspace_urls,
initialization_options,
native_system,
ClientName::from(client_info),
in_test,
)?,
})
}
pub fn run(mut self) -> crate::Result<()> {
let client = Client::new(
self.main_loop_sender.clone(),
self.connection.sender.clone(),
);
let _panic_hook = ServerPanicHookHandler::new(client);
spawn_main_loop(move || self.main_loop())?.join()
}
fn find_best_position_encoding(client_capabilities: &ClientCapabilities) -> PositionEncoding {
client_capabilities
.general
.as_ref()
.and_then(|general_capabilities| general_capabilities.position_encodings.as_ref())
.and_then(|encodings| {
encodings
.iter()
.filter_map(|encoding| PositionEncoding::try_from(encoding).ok())
.max() // this selects the highest priority position encoding
})
.unwrap_or_default()
}
}
type PanicHook = Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>;
struct ServerPanicHookHandler {
hook: Option<PanicHook>,
// Hold on to the strong reference for as long as the panic hook is set.
_client: Arc<Client>,
}
impl ServerPanicHookHandler {
fn new(client: Client) -> Self {
let hook = std::panic::take_hook();
let client = Arc::new(client);
// Use a weak reference to the client because it must be dropped when exiting or the
// io-threads join hangs forever (because client has a reference to the connection sender).
let hook_client = Arc::downgrade(&client);
// When we panic, try to notify the client.
std::panic::set_hook(Box::new(move |panic_info| {
use std::io::Write;
let backtrace = std::backtrace::Backtrace::force_capture();
tracing::error!("{panic_info}\n{backtrace}");
// we also need to print to stderr directly for when using `$logTrace` because
// the message won't be sent to the client.
// But don't use `eprintln` because `eprintln` itself may panic if the pipe is broken.
let mut stderr = std::io::stderr().lock();
writeln!(stderr, "{panic_info}\n{backtrace}").ok();
if let Some(client) = hook_client.upgrade() {
client.show_message(
"The ty language server exited with a panic. See the logs for more details.",
MessageType::Error,
);
}
}));
Self {
hook: Some(hook),
_client: client,
}
}
}
impl Drop for ServerPanicHookHandler {
fn drop(&mut self) {
if std::thread::panicking() {
// Calling `std::panic::set_hook` while panicking results in a panic.
return;
}
if let Some(hook) = self.hook.take() {
std::panic::set_hook(hook);
}
}
}
#[cfg(test)]
mod tests {
use std::num::NonZeroUsize;
use std::sync::Arc;
use lsp_server::{Connection, ErrorCode, Message, Notification, Request};
use ruff_db::system::OsSystem;
use serde_json::{Value, json};
use super::Server;
use crate::system::WorkspaceTrust;
#[test]
fn malformed_trust_rejects_initialization() -> anyhow::Result<()> {
let (connection, client) = initialize_connection(&json!({
"untrustedWorkspace": "true",
"logLevel": "invalid"
}))?;
assert!(
Server::new(
NonZeroUsize::MIN,
connection,
Arc::new(OsSystem::default()),
true,
)
.is_err()
);
let Message::Response(response) = client.receiver.try_recv()? else {
anyhow::bail!("Expected an initialization error response");
};
assert_eq!(response.id, 1.into());
let error = response.response_result.unwrap_err();
assert_eq!(error.code, ErrorCode::InvalidParams as i32);
assert_eq!(
error.message,
"Invalid initialization options: Invalid `untrustedWorkspace` setting: \
invalid type: string \"true\", expected a boolean",
);
Ok(())
}
#[test]
fn malformed_initialization_options_preserve_workspace_trust() -> anyhow::Result<()> {
let (connection, _client_connection) = initialize_connection(&json!({
"untrustedWorkspace": true,
"diagnosticMode": "invalid"
}))?;
let server = Server::new(
NonZeroUsize::MIN,
connection,
Arc::new(OsSystem::default()),
true,
)?;
assert_eq!(
server.session.initialization_options().workspace_trust,
WorkspaceTrust::Untrusted,
);
Ok(())
}
fn initialize_connection(
initialization_options: &Value,
) -> anyhow::Result<(Connection, Connection)> {
let (server, client) = Connection::memory();
client.sender.send(Message::Request(Request::new(
1.into(),
"initialize".into(),
json!({
"capabilities": {},
"initializationOptions": initialization_options
}),
)))?;
client.sender.send(Message::Notification(Notification::new(
"initialized".into(),
json!({}),
)))?;
Ok((server, client))
}
}