1use std::collections::HashMap;
14use std::path::Path;
15use std::sync::{Arc, Weak};
16
17use async_trait::async_trait;
18use futures::future::BoxFuture;
19use tokio::sync::Mutex;
20use tokio_util::sync::CancellationToken;
21
22use crate::error::{FileError, FileErrorCode};
23use crate::path_utils::normalize_tool_path;
24
25pub const MAX_FILE_IO_BYTES: usize = 256 * 1024;
26
27#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
28pub struct FileIOCapabilities {
29 pub read_text: bool,
30 pub write_text: bool,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum FileIOReadRange {
35 Lines { offset_1based: u32, limit: u32 },
38 Complete,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum FileIORequest {
44 ReadText {
45 absolute_path: String,
46 range: FileIOReadRange,
47 max_bytes: usize,
48 },
49 WriteText {
50 absolute_path: String,
51 content: String,
52 },
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum FileIOResponse {
57 Text { content: String },
58 Written,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum FileIOErrorCode {
63 Unsupported,
64 Denied,
65 NotFound,
66 InvalidResponse,
67 TooLarge,
68 Timeout,
69 Cancelled,
70 Disconnected,
71 InvalidPath,
72}
73
74#[derive(Debug, Clone, thiserror::Error)]
75#[error("{code:?}: {message}")]
76pub struct FileIOError {
77 pub code: FileIOErrorCode,
78 pub message: String,
79}
80
81impl FileIOError {
82 pub fn new(code: FileIOErrorCode, message: impl Into<String>) -> Self {
83 Self {
84 code,
85 message: message.into(),
86 }
87 }
88}
89
90impl From<FileIOError> for FileError {
93 fn from(error: FileIOError) -> Self {
94 let code = match error.code {
95 FileIOErrorCode::Unsupported => FileErrorCode::NotSupported,
96 FileIOErrorCode::Denied => FileErrorCode::PermissionDenied,
97 FileIOErrorCode::NotFound => FileErrorCode::NotFound,
98 FileIOErrorCode::Cancelled => FileErrorCode::Aborted,
99 FileIOErrorCode::InvalidPath
100 | FileIOErrorCode::InvalidResponse
101 | FileIOErrorCode::TooLarge => FileErrorCode::Invalid,
102 FileIOErrorCode::Timeout | FileIOErrorCode::Disconnected => FileErrorCode::Unknown,
103 };
104 FileError::new(code, error.to_string()).with_source(Box::new(error))
105 }
106}
107
108#[async_trait]
109pub trait FileIOBackend: Send + Sync {
110 async fn request(
114 &self,
115 request: FileIORequest,
116 cancel: CancellationToken,
117 ) -> Result<FileIOResponse, FileIOError>;
118}
119
120#[derive(Debug, Clone, Copy)]
121pub enum FileIOOperation {
122 Read,
123 Write,
124 Edit,
125}
126
127#[derive(Default, Clone)]
128struct Configuration {
129 capabilities: FileIOCapabilities,
130 backend: Option<Arc<dyn FileIOBackend>>,
131}
132
133#[derive(Default)]
134pub struct FileIORouter {
135 configuration: Mutex<Configuration>,
136 queues: Mutex<HashMap<String, Weak<Mutex<()>>>>,
137}
138
139impl FileIORouter {
140 pub fn new() -> Self {
141 Self::default()
142 }
143
144 pub async fn configure(
148 &self,
149 capabilities: FileIOCapabilities,
150 backend: Option<Arc<dyn FileIOBackend>>,
151 ) -> Result<(), FileIOError> {
152 if (capabilities.read_text || capabilities.write_text) && backend.is_none() {
153 return Err(FileIOError::new(
154 FileIOErrorCode::Unsupported,
155 "selected client I/O requires a backend",
156 ));
157 }
158 *self.configuration.lock().await = Configuration {
159 capabilities,
160 backend,
161 };
162 Ok(())
163 }
164
165 pub async fn select(
167 &self,
168 operation: FileIOOperation,
169 ) -> Result<Option<FileIOSnapshot>, FileIOError> {
170 let config = self.configuration.lock().await.clone();
171 let caps = config.capabilities;
172 let client = match operation {
173 FileIOOperation::Read => caps.read_text,
174 FileIOOperation::Write if caps.read_text && !caps.write_text => {
175 return Err(FileIOError::new(
176 FileIOErrorCode::Unsupported,
177 "write requires client write_text when client read_text is selected",
178 ));
179 }
180 FileIOOperation::Write => caps.write_text,
181 FileIOOperation::Edit if caps.read_text != caps.write_text => {
182 return Err(FileIOError::new(
183 FileIOErrorCode::Unsupported,
184 "edit requires both client read_text and write_text",
185 ));
186 }
187 FileIOOperation::Edit => caps.read_text && caps.write_text,
188 };
189 if !client {
190 return Ok(None);
191 }
192 let backend = config.backend.ok_or_else(|| {
193 FileIOError::new(FileIOErrorCode::Unsupported, "client backend unavailable")
194 })?;
195 Ok(Some(FileIOSnapshot {
196 backend,
197 capabilities: caps,
198 }))
199 }
200
201 pub(crate) async fn with_mutation_queue<F, R>(
203 &self,
204 absolute_path: &str,
205 cancel: &CancellationToken,
206 f: F,
207 ) -> Result<R, FileError>
208 where
209 F: for<'a> FnOnce(&'a CancellationToken) -> BoxFuture<'a, Result<R, FileError>>,
210 R: Send + 'static,
211 {
212 let mutex = {
213 let mut queues = self.queues.lock().await;
214 queues.retain(|_, value| value.strong_count() > 0);
215 if let Some(existing) = queues.get(absolute_path).and_then(Weak::upgrade) {
216 existing
217 } else {
218 let mutex = Arc::new(Mutex::new(()));
219 queues.insert(absolute_path.to_owned(), Arc::downgrade(&mutex));
220 mutex
221 }
222 };
223 let _guard = mutex.lock().await;
224 f(cancel).await
225 }
226}
227
228pub(crate) async fn with_tool_mutation_queue<F, R>(
230 router: Option<&FileIORouter>,
231 env: &dyn crate::file_mutation_queue::MutatingEnv,
232 path: &str,
233 cancel: &CancellationToken,
234 f: F,
235) -> Result<R, FileError>
236where
237 F: for<'a> FnOnce(&'a CancellationToken) -> BoxFuture<'a, Result<R, FileError>>,
238 R: Send + 'static,
239{
240 match router {
241 Some(router) => router.with_mutation_queue(path, cancel, f).await,
242 None => crate::file_mutation_queue::with_file_mutation_queue(env, path, cancel, f).await,
243 }
244}
245
246#[derive(Clone)]
248pub struct FileIOSnapshot {
249 backend: Arc<dyn FileIOBackend>,
250 capabilities: FileIOCapabilities,
251}
252
253impl FileIOSnapshot {
254 pub async fn read_text(
255 &self,
256 path: &str,
257 range: FileIOReadRange,
258 cancel: &CancellationToken,
259 ) -> Result<String, FileIOError> {
260 if !self.capabilities.read_text {
261 return Err(FileIOError::new(
262 FileIOErrorCode::Unsupported,
263 "client text read not selected",
264 ));
265 }
266 check_cancel(cancel)?;
267 let response = self
268 .backend
269 .request(
270 FileIORequest::ReadText {
271 absolute_path: path.to_owned(),
272 range,
273 max_bytes: MAX_FILE_IO_BYTES,
274 },
275 cancel.clone(),
276 )
277 .await;
278 check_cancel(cancel)?;
279 match response? {
280 FileIOResponse::Text { content } => {
281 check_text_size(&content)?;
282 if let FileIOReadRange::Lines { limit, .. } = range {
283 if crate::truncate::split_lines_for_counting(&content).len() > limit as usize {
285 return Err(FileIOError::new(
286 FileIOErrorCode::InvalidResponse,
287 "client returned more lines than requested",
288 ));
289 }
290 }
291 Ok(content)
292 }
293 _ => Err(FileIOError::new(
294 FileIOErrorCode::InvalidResponse,
295 "expected client text response",
296 )),
297 }
298 }
299
300 pub async fn write_text(
301 &self,
302 path: &str,
303 content: String,
304 cancel: &CancellationToken,
305 ) -> Result<(), FileIOError> {
306 if !self.capabilities.write_text {
307 return Err(FileIOError::new(
308 FileIOErrorCode::Unsupported,
309 "client text write not selected",
310 ));
311 }
312 check_cancel(cancel)?;
313 check_text_size(&content)?;
314 let response = self
315 .backend
316 .request(
317 FileIORequest::WriteText {
318 absolute_path: path.to_owned(),
319 content,
320 },
321 cancel.clone(),
322 )
323 .await;
324 check_cancel(cancel)?;
325 match response? {
326 FileIOResponse::Written => Ok(()),
327 _ => Err(FileIOError::new(
328 FileIOErrorCode::InvalidResponse,
329 "expected client write acknowledgment",
330 )),
331 }
332 }
333}
334
335fn check_cancel(cancel: &CancellationToken) -> Result<(), FileIOError> {
336 if cancel.is_cancelled() {
337 return Err(FileIOError::new(
338 FileIOErrorCode::Cancelled,
339 "operation cancelled; a dispatched write may already have committed",
340 ));
341 }
342 Ok(())
343}
344
345fn check_text_size(content: &str) -> Result<(), FileIOError> {
346 if content.len() > MAX_FILE_IO_BYTES {
347 return Err(FileIOError::new(
348 FileIOErrorCode::TooLarge,
349 "client text exceeds 256 KiB UTF-8 limit",
350 ));
351 }
352 Ok(())
353}
354
355pub fn resolve_client_path(cwd: &Path, path: &str) -> Result<String, FileIOError> {
361 fn invalid() -> FileIOError {
362 FileIOError::new(
363 FileIOErrorCode::InvalidPath,
364 "unsupported or ambiguous client path",
365 )
366 }
367 fn absolute(value: &str) -> Result<Option<(String, String, bool)>, FileIOError> {
368 if value.starts_with("\\\\?\\")
369 || value.starts_with("\\\\.\\")
370 || value.starts_with("//?/")
371 || value.starts_with("//./")
372 {
373 return Err(invalid());
374 }
375 if value.starts_with("\\\\") || value.starts_with("//") {
376 let normalized = value.replace('\\', "/");
377 let mut parts = normalized[2..].split('/');
378 let server = parts.next().unwrap_or("");
379 let share = parts.next().unwrap_or("");
380 if server.is_empty()
381 || share.is_empty()
382 || [server, share]
383 .iter()
384 .any(|v| *v == "." || *v == ".." || v.contains(':'))
385 {
386 return Err(invalid());
387 }
388 return Ok(Some((
389 format!("//{server}/{share}/"),
390 parts.collect::<Vec<_>>().join("/"),
391 true,
392 )));
393 }
394 if value.as_bytes().get(1) == Some(&b':') {
395 if !value.as_bytes()[0].is_ascii_alphabetic()
396 || !matches!(value.as_bytes().get(2), Some(b'/') | Some(b'\\'))
397 {
398 return Err(invalid());
399 }
400 return Ok(Some((
401 format!("{}/", &value[..2]),
402 value[3..].replace('\\', "/"),
403 true,
404 )));
405 }
406 if value.starts_with('/') {
407 return Ok(Some(("/".into(), value[1..].into(), false)));
408 }
409 if value.starts_with('\\') {
410 return Err(invalid());
411 }
412 Ok(None)
413 }
414 let path = normalize_tool_path(path);
415 if path.is_empty() || path.contains('\0') || path.starts_with('~') || path.contains("://") {
416 return Err(invalid());
417 }
418 let (root, tail, windows) = if let Some(abs) = absolute(&path)? {
419 abs
420 } else {
421 let cwd = cwd.to_str().ok_or_else(invalid)?;
422 let (root, base, windows) = absolute(cwd)?.ok_or_else(invalid)?;
423 (root, format!("{base}/{path}"), windows)
424 };
425 if tail.contains(':') || (!windows && tail.contains('\\')) {
426 return Err(invalid());
427 }
428 let tail = if windows {
429 tail.replace('\\', "/")
430 } else {
431 tail
432 };
433 let mut components = Vec::new();
434 for part in tail.split('/') {
435 match part {
436 "" | "." => {}
437 ".." => {
438 components.pop();
439 }
440 _ => components.push(part),
441 }
442 }
443 Ok(format!("{root}{}", components.join("/")))
444}
445
446#[cfg(test)]
447#[path = "file_io_tests.rs"]
448mod tests;