1use std::fs::File;
16use std::path::PathBuf;
17use std::sync::{Arc, OnceLock};
18
19use tokio::sync::oneshot;
20
21use crate::pool::JobPool;
22
23const IO_THREADS: usize = 4;
24
25fn pool() -> Result<&'static JobPool, std::io::Error> {
26 static POOL: OnceLock<Result<JobPool, String>> = OnceLock::new();
27 if cfg!(target_family = "wasm") {
29 return Err(std::io::ErrorKind::Unsupported.into());
30 }
31 POOL.get_or_init(|| JobPool::start("tilo-io", IO_THREADS).map_err(|error| error.to_string()))
32 .as_ref()
33 .map_err(|message| std::io::Error::other(message.clone()))
34}
35
36pub async fn run<R, F>(op: F) -> std::io::Result<R>
37where
38 F: FnOnce() -> std::io::Result<R> + Send + 'static,
39 R: Send + 'static,
40{
41 let (tx, rx) = oneshot::channel();
42 let submitted = pool()?.submit(move || {
43 if !tx.is_closed() {
44 let _ = tx.send(op());
45 }
46 });
47 if !submitted {
48 return Err(std::io::Error::other("the I/O pool has stopped"));
49 }
50 rx.await
51 .map_err(|_| std::io::Error::other("an I/O operation panicked"))?
52}
53
54pub async fn read(path: impl Into<PathBuf>) -> std::io::Result<Vec<u8>> {
55 let path = path.into();
56 run(move || std::fs::read(path)).await
57}
58
59pub async fn write(path: impl Into<PathBuf>, contents: Vec<u8>) -> std::io::Result<()> {
60 let path = path.into();
61 run(move || std::fs::write(path, contents)).await
62}
63
64pub async fn read_at(file: Arc<File>, offset: u64, len: usize) -> std::io::Result<Vec<u8>> {
65 run(move || {
66 let mut buffer = vec![0_u8; len];
67 let mut filled = 0_usize;
68 while let Some(rest) = buffer.get_mut(filled..).filter(|rest| !rest.is_empty()) {
69 let at = offset.saturating_add(u64::try_from(filled).unwrap_or(u64::MAX));
70 match positioned::read(&file, rest, at) {
71 Ok(0) => break,
72 Ok(read) => filled = filled.saturating_add(read),
73 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
74 Err(error) => return Err(error),
75 }
76 }
77 buffer.truncate(filled);
78 Ok(buffer)
79 })
80 .await
81}
82
83pub async fn write_all_at(file: Arc<File>, offset: u64, data: Vec<u8>) -> std::io::Result<()> {
84 run(move || {
85 let mut written = 0_usize;
86 while let Some(rest) = data.get(written..).filter(|rest| !rest.is_empty()) {
87 let at = offset.saturating_add(u64::try_from(written).unwrap_or(u64::MAX));
88 match positioned::write(&file, rest, at) {
89 Ok(0) => return Err(std::io::ErrorKind::WriteZero.into()),
90 Ok(count) => written = written.saturating_add(count),
91 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
92 Err(error) => return Err(error),
93 }
94 }
95 Ok(())
96 })
97 .await
98}
99
100pub async fn sync_all(file: Arc<File>) -> std::io::Result<()> {
101 run(move || file.sync_all()).await
102}
103
104#[cfg(unix)]
105mod positioned {
106 use std::fs::File;
107 use std::os::unix::fs::FileExt;
108
109 pub(super) fn read(file: &File, buffer: &mut [u8], offset: u64) -> std::io::Result<usize> {
110 file.read_at(buffer, offset)
111 }
112
113 pub(super) fn write(file: &File, data: &[u8], offset: u64) -> std::io::Result<usize> {
114 file.write_at(data, offset)
115 }
116}
117
118#[cfg(windows)]
119mod positioned {
120 use std::fs::File;
121 use std::os::windows::fs::FileExt;
122
123 pub(super) fn read(file: &File, buffer: &mut [u8], offset: u64) -> std::io::Result<usize> {
124 file.seek_read(buffer, offset)
125 }
126
127 pub(super) fn write(file: &File, data: &[u8], offset: u64) -> std::io::Result<usize> {
128 file.seek_write(data, offset)
129 }
130}
131
132#[cfg(not(any(unix, windows)))]
133mod positioned {
134 use std::fs::File;
135 use std::io::{Error, ErrorKind};
136
137 pub(super) fn read(_file: &File, _buffer: &mut [u8], _offset: u64) -> std::io::Result<usize> {
138 Err(Error::from(ErrorKind::Unsupported))
139 }
140
141 pub(super) fn write(_file: &File, _data: &[u8], _offset: u64) -> std::io::Result<usize> {
142 Err(Error::from(ErrorKind::Unsupported))
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149
150 fn scratch(name: &str) -> PathBuf {
151 let dir = std::env::current_dir()
152 .unwrap()
153 .join("target")
154 .join("tilo-rt-io-tests");
155 std::fs::create_dir_all(&dir).unwrap();
156 dir.join(format!("{name}-{}", std::process::id()))
157 }
158
159 #[test]
160 fn file_io_round_trips_off_the_runtime_and_returns_errors() {
161 {
162 let path = scratch("round-trip");
163 crate::block_on(async {
164 write(path.clone(), b"hello world".to_vec()).await.unwrap();
165 assert_eq!(read(path.clone()).await.unwrap(), b"hello world");
166 let file = Arc::new(
167 std::fs::OpenOptions::new()
168 .read(true)
169 .write(true)
170 .open(&path)
171 .unwrap(),
172 );
173 write_all_at(Arc::clone(&file), 6, b"tilo!".to_vec())
174 .await
175 .unwrap();
176 sync_all(Arc::clone(&file)).await.unwrap();
177 assert_eq!(read_at(Arc::clone(&file), 6, 64).await.unwrap(), b"tilo!");
178 let thread = run(|| Ok(std::thread::current().name().map(str::to_owned)))
179 .await
180 .unwrap();
181 assert!(thread.unwrap().starts_with("tilo-io-"));
182 })
183 .unwrap();
184 std::fs::remove_file(path).unwrap();
185 }
186 {
187 let missing = scratch("missing").join("absent");
188 let error = crate::block_on(read(missing)).unwrap().unwrap_err();
189 assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
190 }
191 }
192}