ailloli_ui_widgets/files/
local_async.rs

1//! Single background worker for non-blocking local directory listings.
2
3use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
4use std::thread;
5
6use ailloli_ui_fs::{FileEntry, FileError, FileProvider, FileUri};
7use ailloli_ui_fs_local::LocalFileProvider;
8
9use super::store::FileTreeNodeId;
10use super::tree::{
11    should_include_file_entry, sort_file_entries, truncate_entries, FileTreeOptions,
12};
13
14/// Command sent to the local filesystem worker.
15///
16/// Requests are processed serially in send order by one background thread.
17///
18/// # Examples
19///
20/// ```
21/// use ailloli_ui_widgets::files::FileExplorerIoRequest;
22/// assert!(matches!(FileExplorerIoRequest::Shutdown, FileExplorerIoRequest::Shutdown));
23/// ```
24#[derive(Debug, Clone)]
25pub enum FileExplorerIoRequest {
26    /// Reads and normalizes one directory.
27    LoadDirectory {
28        /// Store-local node to correlate with the response.
29        node_id: FileTreeNodeId,
30        /// Directory URI passed to the local provider.
31        uri: FileUri,
32        /// Optional selected URI preserved through hidden/exclusion filters.
33        selected: Option<FileUri>,
34        /// Filtering, sorting, and truncation policy snapshot.
35        options: FileTreeOptions,
36    },
37    /// Stops the worker after all earlier queued requests.
38    Shutdown,
39}
40
41/// Completed local directory request returned by the worker.
42///
43/// `truncated` is meaningful only for a successful result; provider errors set
44/// it to `false`. Responses retain the request's node and URI for stale-result
45/// detection by the owner.
46///
47/// # Examples
48///
49/// ```
50/// use ailloli_ui_fs::{FileEntry, FileError, FileUri};
51/// use ailloli_ui_widgets::files::{FileExplorerIoResponse, FileTreeNodeId};
52/// let response = FileExplorerIoResponse {
53///     node_id: FileTreeNodeId(3),
54///     uri: FileUri::parse("file:///tmp")?,
55///     result: Ok::<Vec<FileEntry>, FileError>(Vec::new()),
56///     truncated: false,
57/// };
58/// assert_eq!(response.node_id, FileTreeNodeId(3));
59/// # Ok::<(), ailloli_ui_fs::FileError>(())
60/// ```
61#[derive(Debug, Clone)]
62pub struct FileExplorerIoResponse {
63    /// Store-local node copied from the request.
64    pub node_id: FileTreeNodeId,
65    /// Directory URI copied from the request.
66    pub uri: FileUri,
67    /// Normalized entries or the provider failure.
68    pub result: Result<Vec<FileEntry>, FileError>,
69    /// Whether the configured per-directory cap removed entries.
70    pub truncated: bool,
71}
72
73/// Owned request/response channels and worker thread for local listings.
74///
75/// Construction starts one thread and one [`LocalFileProvider`]. Dropping the
76/// handle requests shutdown but does not join the thread; the thread also exits
77/// when all request senders disconnect.
78///
79/// # Examples
80///
81/// ```
82/// use ailloli_ui_widgets::files::LocalFileExplorerIoWorker;
83/// let worker = LocalFileExplorerIoWorker::new();
84/// assert!(worker.try_recv_all().is_empty());
85/// ```
86pub struct LocalFileExplorerIoWorker {
87    /// Request producer consumed by the dedicated filesystem thread.
88    tx: Sender<FileExplorerIoRequest>,
89    /// Response consumer drained by the UI-side polling path.
90    rx: Receiver<FileExplorerIoResponse>,
91}
92
93/// Starts a worker using [`Self::new`].
94impl Default for LocalFileExplorerIoWorker {
95    fn default() -> Self {
96        Self::new()
97    }
98}
99
100impl LocalFileExplorerIoWorker {
101    /// Starts a background local-provider request loop.
102    ///
103    /// The channels are unbounded. This function returns immediately after
104    /// spawning and does not perform filesystem I/O on the caller's thread.
105    ///
106    /// # Examples
107    ///
108    /// ```
109    /// use ailloli_ui_widgets::files::LocalFileExplorerIoWorker;
110    /// let worker = LocalFileExplorerIoWorker::new();
111    /// assert!(worker.try_recv_all().is_empty());
112    /// ```
113    pub fn new() -> Self {
114        let (tx, request_rx) = mpsc::channel();
115        let (response_tx, rx) = mpsc::channel();
116        thread::spawn(move || {
117            let provider = LocalFileProvider::new();
118            while let Ok(request) = request_rx.recv() {
119                match request {
120                    FileExplorerIoRequest::LoadDirectory {
121                        node_id,
122                        uri,
123                        selected,
124                        options,
125                    } => {
126                        let result = provider
127                            .read_dir(&uri)
128                            .map(|entries| normalize_entries(entries, selected.as_ref(), options));
129                        let (result, truncated) = match result {
130                            Ok((entries, truncated)) => (Ok(entries), truncated),
131                            Err(err) => (Err(err), false),
132                        };
133                        let _ = response_tx.send(FileExplorerIoResponse {
134                            node_id,
135                            uri,
136                            result,
137                            truncated,
138                        });
139                    }
140                    FileExplorerIoRequest::Shutdown => break,
141                }
142            }
143        });
144        Self { tx, rx }
145    }
146
147    /// Queues a request without waiting for filesystem completion.
148    ///
149    /// # Errors
150    ///
151    /// Returns the channel error as a string if the worker has disconnected.
152    /// A successful send does not imply that a directory read will succeed.
153    ///
154    /// # Examples
155    ///
156    /// ```
157    /// use ailloli_ui_widgets::files::{FileExplorerIoRequest, LocalFileExplorerIoWorker};
158    /// let worker = LocalFileExplorerIoWorker::new();
159    /// worker.request(FileExplorerIoRequest::Shutdown)?;
160    /// # Ok::<(), String>(())
161    /// ```
162    pub fn request(&self, request: FileExplorerIoRequest) -> Result<(), String> {
163        self.tx.send(request).map_err(|err| err.to_string())
164    }
165
166    /// Drains every response currently available without blocking.
167    ///
168    /// Responses preserve completion order. An empty vector means no result is
169    /// ready or the response channel disconnected; it is not an error signal.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use ailloli_ui_widgets::files::LocalFileExplorerIoWorker;
175    /// let worker = LocalFileExplorerIoWorker::default();
176    /// let ready = worker.try_recv_all();
177    /// assert!(ready.is_empty());
178    /// ```
179    pub fn try_recv_all(&self) -> Vec<FileExplorerIoResponse> {
180        let mut out = Vec::new();
181        loop {
182            match self.rx.try_recv() {
183                Ok(response) => out.push(response),
184                Err(TryRecvError::Empty) => break,
185                Err(TryRecvError::Disconnected) => break,
186            }
187        }
188        out
189    }
190}
191
192impl Drop for LocalFileExplorerIoWorker {
193    fn drop(&mut self) {
194        let _ = self.tx.send(FileExplorerIoRequest::Shutdown);
195    }
196}
197
198/// Applies inclusion, deterministic directory-first sorting, and size capping.
199fn normalize_entries(
200    entries: Vec<FileEntry>,
201    selected: Option<&FileUri>,
202    options: FileTreeOptions,
203) -> (Vec<FileEntry>, bool) {
204    let mut entries = entries
205        .into_iter()
206        .filter(|entry| should_include_file_entry(entry, selected, options))
207        .collect::<Vec<_>>();
208    sort_file_entries(&mut entries);
209    let truncated = truncate_entries(&mut entries, options);
210    (entries, truncated)
211}
212
213#[cfg(test)]
214/// Exercises the real background thread against a bounded temporary directory.
215mod tests {
216    use std::fs;
217    use std::path::PathBuf;
218    use std::time::{Duration, SystemTime, UNIX_EPOCH};
219
220    use ailloli_ui_fs::FileKind;
221
222    use super::*;
223
224    /// Per-test directory removed on drop.
225    struct TempDir {
226        path: PathBuf,
227    }
228
229    impl TempDir {
230        /// Creates a process/time-namespaced directory under the OS temp root.
231        fn new(name: &str) -> Self {
232            let nanos = SystemTime::now()
233                .duration_since(UNIX_EPOCH)
234                .expect("time")
235                .as_nanos();
236            let path = std::env::temp_dir().join(format!(
237                "ailloli_ui_widgets_local_file_worker_{name}_{}_{}",
238                std::process::id(),
239                nanos
240            ));
241            fs::create_dir_all(&path).expect("temp dir");
242            Self { path }
243        }
244    }
245
246    impl Drop for TempDir {
247        fn drop(&mut self) {
248            let _ = fs::remove_dir_all(&self.path);
249        }
250    }
251
252    #[test]
253    fn worker_loads_directory_async() {
254        let temp = TempDir::new("load");
255        fs::create_dir_all(temp.path.join("src")).expect("src");
256        fs::write(temp.path.join("main.rs"), b"main").expect("main");
257        let uri = FileUri::local(&temp.path).expect("uri");
258        let worker = LocalFileExplorerIoWorker::new();
259
260        worker
261            .request(FileExplorerIoRequest::LoadDirectory {
262                node_id: FileTreeNodeId(7),
263                uri: uri.clone(),
264                selected: None,
265                options: FileTreeOptions::default(),
266            })
267            .expect("request");
268
269        let deadline = std::time::Instant::now() + Duration::from_secs(2);
270        let response = loop {
271            if let Some(response) = worker.try_recv_all().into_iter().next() {
272                break response;
273            }
274            assert!(std::time::Instant::now() < deadline, "worker timed out");
275            std::thread::sleep(Duration::from_millis(10));
276        };
277
278        assert_eq!(response.node_id, FileTreeNodeId(7));
279        let entries = response.result.expect("entries");
280        assert!(entries
281            .iter()
282            .any(|entry| entry.name == "src" && entry.metadata.kind == FileKind::Directory));
283        assert!(entries.iter().any(|entry| entry.name == "main.rs"));
284    }
285}