Skip to main content

dprint_core/plugins/process/
communicator.rs

1use serde::de::DeserializeOwned;
2use std::cell::RefCell;
3use std::io::BufRead;
4use std::io::ErrorKind;
5use std::io::Read;
6use std::io::Write;
7use std::path::Path;
8use std::path::PathBuf;
9use std::process::Child;
10use std::process::ChildStderr;
11use std::process::Command;
12use std::process::Stdio;
13use std::rc::Rc;
14use std::sync::Arc;
15use std::time::Duration;
16use tokio::sync::oneshot;
17use tokio_util::sync::CancellationToken;
18
19use super::PLUGIN_SCHEMA_VERSION;
20use super::messages::CheckConfigUpdatesMessageBody;
21use super::messages::CheckConfigUpdatesResponseBody;
22use super::messages::FormatMessageBody;
23use super::messages::HostFormatMessageBody;
24use super::messages::MessageBody;
25use super::messages::ProcessPluginMessage;
26use super::messages::RegisterConfigMessageBody;
27use super::messages::ResponseBody;
28use crate::async_runtime::DropGuardAction;
29use crate::async_runtime::LocalBoxFuture;
30use crate::communication::AtomicFlag;
31use crate::communication::IdGenerator;
32use crate::communication::MessageReader;
33use crate::communication::MessageWriter;
34use crate::communication::RcIdStore;
35use crate::communication::SingleThreadMessageWriter;
36use crate::configuration::ConfigKeyMap;
37use crate::configuration::ConfigurationDiagnostic;
38use crate::configuration::GlobalConfiguration;
39use crate::plugins::ConfigChange;
40use crate::plugins::CriticalFormatError;
41use crate::plugins::FILE_MATCHING_INFO_ERROR_MESSAGE;
42use crate::plugins::FileMatchingInfo;
43use crate::plugins::FormatConfigId;
44use crate::plugins::FormatError;
45use crate::plugins::FormatRange;
46use crate::plugins::FormatResult;
47use crate::plugins::HostFormatRequest;
48use crate::plugins::NullCancellationToken;
49use crate::plugins::PluginInfo;
50use crate::plugins::error_to_string;
51
52type Result<T> = std::result::Result<T, FormatError>;
53
54#[cfg(unix)]
55use std::os::unix::process::CommandExt;
56
57type DprintCancellationToken = Arc<dyn super::super::CancellationToken>;
58
59/// The detailed reason a schema version negotiation step failed.
60#[derive(Debug, thiserror::Error)]
61enum SchemaVersionError {
62  #[error("Failed asking for schema version: {0}")]
63  Ask(std::io::Error),
64  #[error("Failed flushing schema version request: {0}")]
65  Flush(std::io::Error),
66  #[error("Could not read success response: {0}")]
67  ReadAcknowledgement(std::io::Error),
68  #[error("Plugin response was unexpected ({0}).")]
69  UnexpectedAcknowledgement(u32),
70  #[error("Could not read schema version: {0}")]
71  ReadVersion(std::io::Error),
72}
73
74/// Errors that can occur while communicating with a process plugin.
75#[derive(Debug, thiserror::Error)]
76enum CommunicatorError {
77  #[error("Error starting {executable} with args [{args}]. {error}")]
78  StartProcess { executable: String, args: String, error: std::io::Error },
79  #[error(
80    "Error starting {executable} with args [{args}]. {error}\n\nThe executable exists, but the system is likely missing the dynamic loader or interpreter it needs in order to run (ex. a binary linked against glibc on NixOS, which can be worked around with nix-ld)."
81  )]
82  StartProcessMissingLoader { executable: String, args: String, error: std::io::Error },
83  #[error("Failed plugin schema verification. This may indicate you are using an old version of the dprint CLI or plugin and should upgrade")]
84  SchemaVerification(#[from] SchemaVersionError),
85  #[error(
86    "This plugin is too old to run in the dprint CLI and you will need to manually upgrade it (version was {actual}, but expected {expected}).\n\nUpgrade instructions: https://github.com/dprint/dprint/issues/731"
87  )]
88  PluginTooOld { actual: u32, expected: u32 },
89  #[error("Your dprint CLI is too old to run this plugin (version was {actual}, but expected {expected}). Try running: dprint upgrade")]
90  CliTooOld { actual: u32, expected: u32 },
91  #[error("Error waiting on message ({message_id}). {error}")]
92  WaitOnMessage {
93    message_id: u32,
94    error: tokio::sync::oneshot::error::RecvError,
95  },
96  #[error("Unexpected data channel for success response: {0}")]
97  UnexpectedDataForSuccess(u32),
98  #[error("Unexpected format channel for success response: {0}")]
99  UnexpectedFormatForSuccess(u32),
100  #[error("Unexpected success channel for data response: {0}")]
101  UnexpectedSuccessForData(u32),
102  #[error("Unexpected format channel for data response: {0}")]
103  UnexpectedFormatForData(u32),
104  #[error("Unexpected success channel for format response: {0}")]
105  UnexpectedSuccessForFormat(u32),
106  #[error("Unexpected data channel for format response: {0}")]
107  UnexpectedDataForFormat(u32),
108  #[error("Unknown message kind: {0}")]
109  UnknownMessageKind(u32),
110  #[error("Could not find host format callback for message id: {0}")]
111  HostFormatCallbackNotFound(u32),
112}
113
114impl From<CommunicatorError> for FormatError {
115  fn from(err: CommunicatorError) -> Self {
116    FormatError::new(err)
117  }
118}
119
120pub type HostFormatCallback = Rc<dyn Fn(HostFormatRequest) -> LocalBoxFuture<'static, FormatResult>>;
121
122pub struct ProcessPluginCommunicatorFormatRequest {
123  pub file_path: PathBuf,
124  pub file_bytes: Arc<Vec<u8>>,
125  pub range: FormatRange,
126  pub config_id: FormatConfigId,
127  pub override_config: ConfigKeyMap,
128  pub on_host_format: HostFormatCallback,
129  pub token: DprintCancellationToken,
130}
131
132enum MessageResponseChannel {
133  Acknowledgement(oneshot::Sender<Result<()>>),
134  Data(oneshot::Sender<Result<Vec<u8>>>),
135  Format(oneshot::Sender<Result<Option<Vec<u8>>>>),
136}
137
138struct Context {
139  stdin_writer: SingleThreadMessageWriter<ProcessPluginMessage>,
140  shutdown_flag: Arc<AtomicFlag>,
141  id_generator: IdGenerator,
142  messages: RcIdStore<MessageResponseChannel>,
143  format_request_tokens: RcIdStore<Arc<CancellationToken>>,
144  host_format_callbacks: RcIdStore<HostFormatCallback>,
145}
146
147/// Communicates with a process plugin.
148pub struct ProcessPluginCommunicator {
149  child: RefCell<Option<Child>>,
150  #[cfg(windows)]
151  job: Option<ProcessJob>,
152  context: Rc<Context>,
153}
154
155impl Drop for ProcessPluginCommunicator {
156  fn drop(&mut self) {
157    self.kill();
158  }
159}
160
161impl ProcessPluginCommunicator {
162  pub async fn new(executable_file_path: &Path, on_std_err: impl Fn(String) + Clone + Send + Sync + 'static) -> Result<Self> {
163    ProcessPluginCommunicator::new_internal(executable_file_path, false, on_std_err).await
164  }
165
166  /// Provides the `--init` CLI flag to tell the process plugin to do any initialization necessary
167  pub async fn new_with_init(executable_file_path: &Path, on_std_err: impl Fn(String) + Clone + Send + Sync + 'static) -> Result<Self> {
168    ProcessPluginCommunicator::new_internal(executable_file_path, true, on_std_err).await
169  }
170
171  async fn new_internal(executable_file_path: &Path, is_init: bool, on_std_err: impl Fn(String) + Clone + Send + Sync + 'static) -> Result<Self> {
172    let mut args = vec!["--parent-pid".to_string(), std::process::id().to_string()];
173    if is_init {
174      args.push("--init".to_string());
175    }
176
177    let shutdown_flag = Arc::new(AtomicFlag::default());
178    let mut command = Command::new(executable_file_path);
179    command.args(&args).stdin(Stdio::piped()).stderr(Stdio::piped()).stdout(Stdio::piped());
180    #[cfg(unix)]
181    command.process_group(0);
182    let mut child = command.spawn().map_err(|err| start_process_error(executable_file_path, &args, err))?;
183    // assign the job right away so that it includes anything the plugin spawns
184    #[cfg(windows)]
185    let job = ProcessJob::for_child(&child);
186
187    // read and output stderr prefixed
188    let stderr = child.stderr.take().unwrap();
189    crate::async_runtime::spawn_blocking({
190      let shutdown_flag = shutdown_flag.clone();
191      let on_std_err = on_std_err.clone();
192      move || {
193        std_err_redirect(shutdown_flag, stderr, on_std_err);
194      }
195    });
196
197    // verify the schema version
198    let mut stdout_reader = MessageReader::new(child.stdout.take().unwrap());
199    let mut stdin_writer = MessageWriter::new(child.stdin.take().unwrap());
200
201    let (mut stdout_reader, stdin_writer, schema_version) = crate::async_runtime::spawn_blocking(move || {
202      let schema_version = get_plugin_schema_version(&mut stdout_reader, &mut stdin_writer).map_err(CommunicatorError::SchemaVerification)?;
203      Ok::<_, FormatError>((stdout_reader, stdin_writer, schema_version))
204    })
205    .await??;
206
207    if schema_version != PLUGIN_SCHEMA_VERSION {
208      // kill the child to prevent it from ouputting to stderr
209      let _ = child.kill();
210      let err = if schema_version < PLUGIN_SCHEMA_VERSION {
211        CommunicatorError::PluginTooOld {
212          actual: schema_version,
213          expected: PLUGIN_SCHEMA_VERSION,
214        }
215      } else {
216        CommunicatorError::CliTooOld {
217          actual: schema_version,
218          expected: PLUGIN_SCHEMA_VERSION,
219        }
220      };
221      return Err(err.into());
222    }
223
224    let stdin_writer = SingleThreadMessageWriter::for_stdin(stdin_writer);
225    let context = Rc::new(Context {
226      id_generator: Default::default(),
227      shutdown_flag,
228      stdin_writer,
229      messages: Default::default(),
230      format_request_tokens: Default::default(),
231      host_format_callbacks: Default::default(),
232    });
233
234    // read from stdout
235    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
236    crate::async_runtime::spawn_blocking({
237      let shutdown_flag = context.shutdown_flag.clone();
238      let on_std_err = on_std_err.clone();
239      move || {
240        loop {
241          match ProcessPluginMessage::read(&mut stdout_reader) {
242            Ok(message) => {
243              if tx.send(message).is_err() {
244                break; // closed
245              }
246            }
247            Err(err) if err.kind() == ErrorKind::BrokenPipe => {
248              break;
249            }
250            Err(err) => {
251              if !shutdown_flag.is_raised() {
252                on_std_err(format!("Error reading stdout message: {:#}", err));
253              }
254              break;
255            }
256          }
257        }
258      }
259    });
260    crate::async_runtime::spawn({
261      let context = context.clone();
262      async move {
263        while let Some(message) = rx.recv().await {
264          if let Err(err) = handle_stdout_message(message, &context) {
265            if !context.shutdown_flag.is_raised() {
266              on_std_err(format!("Error reading stdout message: {:#}", err));
267            }
268            break;
269          }
270        }
271        // clear out all the messages
272        context.messages.take_all();
273      }
274    });
275
276    Ok(Self {
277      #[cfg(windows)]
278      job,
279      child: RefCell::new(Some(child)),
280      context,
281    })
282  }
283
284  /// Perform a graceful shutdown.
285  pub async fn shutdown(&self) {
286    if self.context.shutdown_flag.raise() {
287      // attempt to exit nicely
288      tokio::select! {
289        // we wait for acknowledgement in order to give the process
290        // plugin a chance to clean up (ex. in case it has spawned
291        // any processes it needs to kill or something like that)
292        _ = self.send_with_acknowledgement(MessageBody::Close) => {
293          // the plugin stops handling messages once it closes, but it
294          // doesn't exit until its stdin closes, so fail the messages still
295          // in flight rather than leaving them waiting on a response
296          self.context.messages.take_all();
297        }
298        _ = tokio::time::sleep(Duration::from_millis(250)) => {
299          self.kill();
300        }
301      }
302    } else {
303      self.kill();
304    }
305  }
306
307  pub fn kill(&self) {
308    self.context.shutdown_flag.raise();
309    if let Some(mut child) = self.child.borrow_mut().take() {
310      #[cfg(unix)]
311      unsafe {
312        libc::kill(-(child.id() as i32), libc::SIGKILL);
313      }
314      #[cfg(windows)]
315      if let Some(job) = &self.job {
316        job.terminate();
317      }
318      let _ignore = child.kill();
319    }
320  }
321
322  pub async fn register_config(&self, config_id: FormatConfigId, global_config: &GlobalConfiguration, plugin_config: &ConfigKeyMap) -> Result<()> {
323    let global_config = serde_json::to_vec(global_config)?;
324    let plugin_config = serde_json::to_vec(plugin_config)?;
325    self
326      .send_with_acknowledgement(MessageBody::RegisterConfig(RegisterConfigMessageBody {
327        config_id,
328        global_config,
329        plugin_config,
330      }))
331      .await?;
332    Ok(())
333  }
334
335  pub async fn release_config(&self, config_id: FormatConfigId) -> Result<()> {
336    self.send_with_acknowledgement(MessageBody::ReleaseConfig(config_id)).await?;
337    Ok(())
338  }
339
340  pub async fn ask_is_alive(&self) -> bool {
341    self.send_with_acknowledgement(MessageBody::IsAlive).await.is_ok()
342  }
343
344  pub async fn plugin_info(&self) -> Result<PluginInfo> {
345    self.send_receiving_data(MessageBody::GetPluginInfo).await
346  }
347
348  pub async fn license_text(&self) -> Result<String> {
349    self.send_receiving_string(MessageBody::GetLicenseText).await
350  }
351
352  pub async fn resolved_config(&self, config_id: FormatConfigId) -> Result<String> {
353    self.send_receiving_string(MessageBody::GetResolvedConfig(config_id)).await
354  }
355
356  pub async fn file_matching_info(&self, config_id: FormatConfigId) -> Result<FileMatchingInfo> {
357    let data = self.send_receiving_bytes(MessageBody::GetFileMatchingInfo(config_id)).await??;
358    serde_json::from_slice(&data).map_err(|err| FormatError::new(format!("{FILE_MATCHING_INFO_ERROR_MESSAGE}\n\n{err:#}")))
359  }
360
361  pub async fn config_diagnostics(&self, config_id: FormatConfigId) -> Result<Vec<ConfigurationDiagnostic>> {
362    self.send_receiving_data(MessageBody::GetConfigDiagnostics(config_id)).await
363  }
364
365  pub async fn check_config_updates(&self, message: &CheckConfigUpdatesMessageBody) -> Result<Vec<ConfigChange>> {
366    let bytes = serde_json::to_vec(&message)?;
367    let response: CheckConfigUpdatesResponseBody = self.send_receiving_data(MessageBody::CheckConfigUpdates(bytes)).await?;
368    Ok(response.changes)
369  }
370
371  pub async fn format_text(&self, request: ProcessPluginCommunicatorFormatRequest) -> FormatResult {
372    let (tx, rx) = oneshot::channel::<Result<Option<Vec<u8>>>>();
373
374    let message_id = self.context.id_generator.next();
375    let store_guard = self.context.host_format_callbacks.store_with_guard(message_id, request.on_host_format);
376    let maybe_result = self
377      .send_message_with_id(
378        message_id,
379        MessageBody::FormatShared(FormatMessageBody {
380          file_path: request.file_path,
381          file_bytes: request.file_bytes,
382          range: request.range,
383          config_id: request.config_id,
384          override_config: serde_json::to_vec(&request.override_config).unwrap(),
385        }),
386        MessageResponseChannel::Format(tx),
387        rx,
388        request.token.clone(),
389      )
390      .await;
391
392    drop(store_guard); // explicit for clarity
393
394    if request.token.is_cancelled() {
395      Ok(None)
396    } else {
397      match maybe_result {
398        Ok(result) => result,
399        Err(err) => Err(CriticalFormatError(err).into()),
400      }
401    }
402  }
403
404  /// Checks if the process is functioning.
405  pub async fn is_process_alive(&self) -> bool {
406    if self.context.shutdown_flag.is_raised() {
407      false
408    } else {
409      self.ask_is_alive().await
410    }
411  }
412
413  async fn send_with_acknowledgement(&self, body: MessageBody) -> Result<()> {
414    let (tx, rx) = oneshot::channel::<Result<()>>();
415    self
416      .send_message(body, MessageResponseChannel::Acknowledgement(tx), rx, Arc::new(NullCancellationToken))
417      .await?
418  }
419
420  async fn send_receiving_string(&self, body: MessageBody) -> Result<String> {
421    let data = self.send_receiving_bytes(body).await??;
422    Ok(String::from_utf8(data)?)
423  }
424
425  async fn send_receiving_data<T: DeserializeOwned>(&self, body: MessageBody) -> Result<T> {
426    let data = self.send_receiving_bytes(body).await??;
427    Ok(serde_json::from_slice(&data)?)
428  }
429
430  async fn send_receiving_bytes(&self, body: MessageBody) -> Result<Result<Vec<u8>>> {
431    let (tx, rx) = oneshot::channel::<Result<Vec<u8>>>();
432    self
433      .send_message(body, MessageResponseChannel::Data(tx), rx, Arc::new(NullCancellationToken))
434      .await
435  }
436
437  async fn send_message<T: Default>(
438    &self,
439    body: MessageBody,
440    response_channel: MessageResponseChannel,
441    receiver: oneshot::Receiver<Result<T>>,
442    token: Arc<dyn super::super::CancellationToken>,
443  ) -> Result<Result<T>> {
444    let message_id = self.context.id_generator.next();
445    self.send_message_with_id(message_id, body, response_channel, receiver, token).await
446  }
447
448  async fn send_message_with_id<T: Default>(
449    &self,
450    message_id: u32,
451    body: MessageBody,
452    response_channel: MessageResponseChannel,
453    receiver: oneshot::Receiver<Result<T>>,
454    token: Arc<dyn super::super::CancellationToken>,
455  ) -> Result<Result<T>> {
456    let mut drop_guard = DropGuardAction::new(|| {
457      // clear up memory
458      self.context.messages.take(message_id);
459      // send cancellation to the client
460      let _ = self.context.stdin_writer.send(ProcessPluginMessage {
461        id: self.context.id_generator.next(),
462        body: MessageBody::CancelFormat(message_id),
463      });
464    });
465
466    self.context.messages.store(message_id, response_channel);
467    self.context.stdin_writer.send(ProcessPluginMessage { id: message_id, body })?;
468    tokio::select! {
469      _ = token.wait_cancellation() => {
470        drop(drop_guard); // explicit
471        Ok(Ok(Default::default()))
472      }
473      response = receiver => {
474        drop_guard.forget(); // we completed, so don't run the drop guard
475        match response {
476          Ok(data) => Ok(data),
477          Err(err) => Err(CommunicatorError::WaitOnMessage { message_id, error: err }.into()),
478        }
479      }
480    }
481  }
482}
483
484fn start_process_error(executable_file_path: &Path, args: &[String], error: std::io::Error) -> CommunicatorError {
485  let executable = executable_file_path.display().to_string();
486  let args = args.join(" ");
487  // the kernel reports a missing ELF interpreter (dynamic loader) or shebang
488  // interpreter the same as the executable itself not existing
489  if cfg!(unix) && error.kind() == ErrorKind::NotFound && executable_file_path.is_file() {
490    CommunicatorError::StartProcessMissingLoader { executable, args, error }
491  } else {
492    CommunicatorError::StartProcess { executable, args, error }
493  }
494}
495
496fn get_plugin_schema_version<TRead: Read + Unpin, TWrite: Write + Unpin>(
497  reader: &mut MessageReader<TRead>,
498  writer: &mut MessageWriter<TWrite>,
499) -> std::result::Result<u32, SchemaVersionError> {
500  // since this is the setup, identify exactly where it failed
501  writer.send_u32(0).map_err(SchemaVersionError::Ask)?; // ask for schema version
502  writer.flush().map_err(SchemaVersionError::Flush)?;
503  let acknowledgement_response = reader.read_u32().map_err(SchemaVersionError::ReadAcknowledgement)?;
504  if acknowledgement_response != 0 {
505    return Err(SchemaVersionError::UnexpectedAcknowledgement(acknowledgement_response));
506  }
507  reader.read_u32().map_err(SchemaVersionError::ReadVersion)
508}
509
510fn std_err_redirect(shutdown_flag: Arc<AtomicFlag>, stderr: ChildStderr, on_std_err: impl Fn(String) + Send + Sync + 'static) {
511  let reader = std::io::BufReader::new(stderr);
512  for line in reader.lines() {
513    match line {
514      Ok(line) => on_std_err(line),
515      Err(err) => {
516        if shutdown_flag.is_raised() || err.kind() == ErrorKind::BrokenPipe {
517          return;
518        } else {
519          on_std_err(format!("Error reading line from process plugin stderr. {:#}", err));
520        }
521      }
522    }
523  }
524}
525
526fn handle_stdout_message(message: ProcessPluginMessage, context: &Rc<Context>) -> Result<()> {
527  match message.body {
528    MessageBody::Success(message_id) => match context.messages.take(message_id) {
529      Some(MessageResponseChannel::Acknowledgement(channel)) => {
530        let _ignore = channel.send(Ok(()));
531      }
532      Some(MessageResponseChannel::Data(channel)) => {
533        let _ignore = channel.send(Err(CommunicatorError::UnexpectedDataForSuccess(message_id).into()));
534      }
535      Some(MessageResponseChannel::Format(channel)) => {
536        let _ignore = channel.send(Err(CommunicatorError::UnexpectedFormatForSuccess(message_id).into()));
537      }
538      None => {}
539    },
540    MessageBody::DataResponse(response) => match context.messages.take(response.message_id) {
541      Some(MessageResponseChannel::Acknowledgement(channel)) => {
542        let _ignore = channel.send(Err(CommunicatorError::UnexpectedSuccessForData(response.message_id).into()));
543      }
544      Some(MessageResponseChannel::Data(channel)) => {
545        let _ignore = channel.send(Ok(response.data));
546      }
547      Some(MessageResponseChannel::Format(channel)) => {
548        let _ignore = channel.send(Err(CommunicatorError::UnexpectedFormatForData(response.message_id).into()));
549      }
550      None => {}
551    },
552    MessageBody::Error(response) => {
553      let err: FormatError = String::from_utf8_lossy(&response.data).into_owned().into();
554      match context.messages.take(response.message_id) {
555        Some(MessageResponseChannel::Acknowledgement(channel)) => {
556          let _ignore = channel.send(Err(err));
557        }
558        Some(MessageResponseChannel::Data(channel)) => {
559          let _ignore = channel.send(Err(err));
560        }
561        Some(MessageResponseChannel::Format(channel)) => {
562          let _ignore = channel.send(Err(err));
563        }
564        None => {}
565      }
566    }
567    MessageBody::FormatResponse(response) => match context.messages.take(response.message_id) {
568      Some(MessageResponseChannel::Acknowledgement(channel)) => {
569        let _ignore = channel.send(Err(CommunicatorError::UnexpectedSuccessForFormat(response.message_id).into()));
570      }
571      Some(MessageResponseChannel::Data(channel)) => {
572        let _ignore = channel.send(Err(CommunicatorError::UnexpectedDataForFormat(response.message_id).into()));
573      }
574      Some(MessageResponseChannel::Format(channel)) => {
575        let _ignore = channel.send(Ok(response.data));
576      }
577      None => {}
578    },
579    MessageBody::CancelFormat(message_id) => {
580      if let Some(token) = context.format_request_tokens.take(message_id) {
581        token.cancel();
582      }
583      context.host_format_callbacks.take(message_id);
584      // do not clear from context.messages here because the cancellation will do that
585    }
586    MessageBody::HostFormat(body) => {
587      // spawn a task to do the host formatting, then send a message back to the
588      // plugin with the result
589      let context = context.clone();
590      crate::async_runtime::spawn(async move {
591        let result = host_format(context.clone(), message.id, body).await;
592
593        // ignore failure, as this means that the process shut down
594        // at which point handling would have occurred elsewhere
595        let _ignore = context.stdin_writer.send(ProcessPluginMessage {
596          id: context.id_generator.next(),
597          body: match result {
598            Ok(result) => MessageBody::FormatResponse(ResponseBody {
599              message_id: message.id,
600              data: result,
601            }),
602            Err(err) => MessageBody::Error(ResponseBody {
603              message_id: message.id,
604              data: error_to_string(&err).into_bytes(),
605            }),
606          },
607        });
608      });
609    }
610    MessageBody::IsAlive => {
611      // the CLI is not documented as supporting this, but we might as well respond
612      let _ = context.stdin_writer.send(ProcessPluginMessage {
613        id: context.id_generator.next(),
614        body: MessageBody::Success(message.id),
615      });
616    }
617    MessageBody::Format(_)
618    | MessageBody::FormatShared(_)
619    | MessageBody::Close
620    | MessageBody::GetPluginInfo
621    | MessageBody::GetLicenseText
622    | MessageBody::RegisterConfig(_)
623    | MessageBody::ReleaseConfig(_)
624    | MessageBody::GetConfigDiagnostics(_)
625    | MessageBody::GetFileMatchingInfo(_)
626    | MessageBody::GetResolvedConfig(_)
627    | MessageBody::CheckConfigUpdates(_) => {
628      let _ = context.stdin_writer.send(ProcessPluginMessage {
629        id: context.id_generator.next(),
630        body: MessageBody::Error(ResponseBody {
631          message_id: message.id,
632          data: "Unsupported plugin to CLI message.".as_bytes().to_vec(),
633        }),
634      });
635    }
636    // If encountered, process plugin should exit and
637    // the CLI should kill the process plugin.
638    MessageBody::Unknown(message_kind) => {
639      return Err(CommunicatorError::UnknownMessageKind(message_kind).into());
640    }
641  }
642
643  Ok(())
644}
645
646async fn host_format(context: Rc<Context>, message_id: u32, body: HostFormatMessageBody) -> FormatResult {
647  let Some(callback) = context.host_format_callbacks.get_cloned(body.original_message_id) else {
648    return FormatResult::Err(CommunicatorError::HostFormatCallbackNotFound(body.original_message_id).into());
649  };
650
651  let token = Arc::new(CancellationToken::new());
652  let store_guard = context.format_request_tokens.store_with_guard(message_id, token.clone());
653  let result = callback(HostFormatRequest {
654    file_path: body.file_path,
655    file_bytes: body.file_text,
656    range: body.range,
657    override_config: serde_json::from_slice(&body.override_config).unwrap(),
658    token,
659  })
660  .await;
661  drop(store_guard); // explicit for clarity
662  result
663}
664
665/// A Windows job object the process plugin is assigned to so that any
666/// subprocesses it spawns get killed along with it.
667#[cfg(windows)]
668struct ProcessJob(winapi::um::winnt::HANDLE);
669
670#[cfg(windows)]
671impl ProcessJob {
672  /// Creates a job and assigns the child to it. Processes the child spawns
673  /// from this point on are automatically part of the job.
674  fn for_child(child: &Child) -> Option<Self> {
675    use std::os::windows::io::AsRawHandle;
676    use winapi::um::jobapi2::AssignProcessToJobObject;
677    use winapi::um::jobapi2::CreateJobObjectW;
678
679    unsafe {
680      let handle = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());
681      if handle.is_null() {
682        return None;
683      }
684      let job = Self(handle);
685      if AssignProcessToJobObject(job.0, child.as_raw_handle() as _) == 0 {
686        return None;
687      }
688      Some(job)
689    }
690  }
691
692  /// Kills every process in the job.
693  fn terminate(&self) {
694    unsafe {
695      winapi::um::jobapi2::TerminateJobObject(self.0, 1);
696    }
697  }
698}
699
700#[cfg(windows)]
701impl Drop for ProcessJob {
702  fn drop(&mut self) {
703    unsafe {
704      winapi::um::handleapi::CloseHandle(self.0);
705    }
706  }
707}
708
709#[cfg(all(test, unix))]
710mod test {
711  use super::*;
712
713  #[test]
714  fn start_process_error_missing_loader() {
715    let dir = std::env::temp_dir().join(format!("dprint-core-missing-loader-{}", std::process::id()));
716    std::fs::create_dir_all(&dir).unwrap();
717    let executable = dir.join("plugin");
718    // exec fails with ENOENT because the interpreter doesn't exist, the same
719    // as a binary whose dynamic loader doesn't exist
720    //
721    // the script is written by a child process because if this process opened
722    // it for writing, a process concurrently forked by another test could
723    // inherit that fd and cause exec to fail with ETXTBSY
724    let status = Command::new("sh")
725      .arg("-c")
726      .arg("printf '#!/dprint-non-existent/interpreter\\n' > \"$1\" && chmod 755 \"$1\"")
727      .arg("sh")
728      .arg(&executable)
729      .status()
730      .unwrap();
731    assert!(status.success());
732    let args = vec!["--init".to_string()];
733
734    let err = Command::new(&executable).args(&args).spawn().unwrap_err();
735    let err = start_process_error(&executable, &args, err);
736    assert!(matches!(err, CommunicatorError::StartProcessMissingLoader { .. }), "{err}");
737    assert!(err.to_string().contains("missing the dynamic loader"), "{err}");
738
739    // an executable that really doesn't exist keeps the regular error
740    let missing_executable = dir.join("missing");
741    let err = Command::new(&missing_executable).spawn().unwrap_err();
742    let err = start_process_error(&missing_executable, &args, err);
743    assert!(matches!(err, CommunicatorError::StartProcess { .. }), "{err}");
744
745    std::fs::remove_dir_all(&dir).unwrap();
746  }
747}