Debian Codegraph @

helix-lsp/src/file_event.rs

raw symbols SCIP
1 use std::{collections::HashMap, path::PathBuf, sync::Weak};
2
3 use globset::{GlobBuilder, GlobSetBuilder};
4 use tokio::sync::mpsc;
5
6 use crate::{lsp, Client, LanguageServerId};
7
8 enum Event {
9 FileChanged {
10 path: PathBuf,
11 },
12 Register {
13 client_id: LanguageServerId,
14 client: Weak<Client>,
15 registration_id: String,
16 options: lsp::DidChangeWatchedFilesRegistrationOptions,
17 },
18 Unregister {
19 client_id: LanguageServerId,
20 registration_id: String,
21 },
22 RemoveClient {
23 client_id: LanguageServerId,
24 },
25 }
26
27 #[derive(Default)]
28 struct ClientState {
29 client: Weak<Client>,
30 registered: HashMap<String, globset::GlobSet>,
31 }
32
33 /// The Handler uses a dedicated tokio task to respond to file change events by
34 /// forwarding changes to LSPs that have registered for notifications with a
35 /// matching glob.
36 ///
37 /// When an LSP registers for the DidChangeWatchedFiles notification, the
38 /// Handler is notified by sending the registration details in addition to a
39 /// weak reference to the LSP client. This is done so that the Handler can have
40 /// access to the client without preventing the client from being dropped if it
41 /// is closed and the Handler isn't properly notified.
42 #[derive(Clone, Debug)]
43 pub struct Handler {
44 tx: mpsc::UnboundedSender<Event>,
45 }
46
47 impl Default for Handler {
48 fn default() -> Self {
49 Self::new()
50 }
51 }
52
53 impl Handler {
54 pub fn new() -> Self {
55 let (tx, rx) = mpsc::unbounded_channel();
56 tokio::spawn(Self::run(rx));
57 Self { tx }
58 }
59
60 pub fn register(
61 &self,
62 client_id: LanguageServerId,
63 client: Weak<Client>,
64 registration_id: String,
65 options: lsp::DidChangeWatchedFilesRegistrationOptions,
66 ) {
67 let _ = self.tx.send(Event::Register {
68 client_id,
69 client,
70 registration_id,
71 options,
72 });
73 }
74
75 pub fn unregister(&self, client_id: LanguageServerId, registration_id: String) {
76 let _ = self.tx.send(Event::Unregister {
77 client_id,
78 registration_id,
79 });
80 }
81
82 pub fn file_changed(&self, path: PathBuf) {
83 let _ = self.tx.send(Event::FileChanged { path });
84 }
85
86 pub fn remove_client(&self, client_id: LanguageServerId) {
87 let _ = self.tx.send(Event::RemoveClient { client_id });
88 }
89
90 async fn run(mut rx: mpsc::UnboundedReceiver<Event>) {
91 let mut state: HashMap<LanguageServerId, ClientState> = HashMap::new();
92 while let Some(event) = rx.recv().await {
93 match event {
94 Event::FileChanged { path } => {
95 log::debug!("Received file event for {:?}", &path);
96
97 state.retain(|id, client_state| {
98 if !client_state
99 .registered
100 .values()
101 .any(|glob| glob.is_match(&path))
102 {
103 return true;
104 }
105 let Some(client) = client_state.client.upgrade() else {
106 log::warn!("LSP client was dropped: {id}");
107 return false;
108 };
109 let Ok(uri) = lsp::Url::from_file_path(&path) else {
110 return true;
111 };
112 log::debug!(
113 "Sending didChangeWatchedFiles notification to client '{}'",
114 client.name()
115 );
116 client.did_change_watched_files(vec![lsp::FileEvent {
117 uri,
118 // We currently always send the CHANGED state
119 // since we don't actually have more context at
120 // the moment.
121 typ: lsp::FileChangeType::CHANGED,
122 }]);
123 true
124 });
125 }
126 Event::Register {
127 client_id,
128 client,
129 registration_id,
130 options: ops,
131 } => {
132 log::debug!(
133 "Registering didChangeWatchedFiles for client '{}' with id '{}'",
134 client_id,
135 registration_id
136 );
137
138 let entry = state.entry(client_id).or_default();
139 entry.client = client;
140
141 let mut builder = GlobSetBuilder::new();
142 for watcher in ops.watchers {
143 if let lsp::GlobPattern::String(pattern) = watcher.glob_pattern {
144 if let Ok(glob) = GlobBuilder::new(&pattern).build() {
145 builder.add(glob);
146 }
147 }
148 }
149 match builder.build() {
150 Ok(globset) => {
151 entry.registered.insert(registration_id, globset);
152 }
153 Err(err) => {
154 // Remove any old state for that registration id and
155 // remove the entire client if it's now empty.
156 entry.registered.remove(&registration_id);
157 if entry.registered.is_empty() {
158 state.remove(&client_id);
159 }
160 log::warn!(
161 "Unable to build globset for LSP didChangeWatchedFiles {err}"
162 )
163 }
164 }
165 }
166 Event::Unregister {
167 client_id,
168 registration_id,
169 } => {
170 log::debug!(
171 "Unregistering didChangeWatchedFiles with id '{}' for client '{}'",
172 registration_id,
173 client_id
174 );
175 if let Some(client_state) = state.get_mut(&client_id) {
176 client_state.registered.remove(&registration_id);
177 if client_state.registered.is_empty() {
178 state.remove(&client_id);
179 }
180 }
181 }
182 Event::RemoveClient { client_id } => {
183 log::debug!("Removing LSP client: {client_id}");
184 state.remove(&client_id);
185 }
186 }
187 }
188 }
189 }