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