1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
macro_rules! async_file_ext {
($file: ty, $file_name: literal) => {
use std::io::Result;
#[doc = concat!("Extension trait for `", $file_name, "` which provides allocation and locking methods.")]
///
/// ## Notes on File Locks
///
/// This library provides whole-file locks in both shared (read) and exclusive
/// (read-write) varieties.
///
/// File locks are a cross-platform hazard since the file lock APIs exposed by
/// operating system kernels vary in subtle and not-so-subtle ways.
///
/// The API exposed by this library can be safely used across platforms as long
/// as the following rules are followed:
///
/// * Multiple locks should not be created on an individual `File` instance
/// concurrently.
/// * Duplicated files should not be locked without great care.
/// * Files to be locked should be opened with at least read or write
/// permissions.
/// * File locks may only be relied upon to be advisory.
///
/// File locks are released automatically when the file handle is closed (for
/// example when the owning `File` is dropped), so calling [`AsyncFileExt::unlock`]
/// explicitly is optional.
///
/// File locks are implemented with
/// [`flock(2)`](http://man7.org/linux/man-pages/man2/flock.2.html) on Unix and
/// [`LockFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex)
/// on Windows. The `lock_*` and `try_lock_*` methods are synchronous because
/// the underlying system calls are blocking. The separate
/// [`AsyncFileExt::unlock_async`] method is provided for convenience inside
/// async code, but the underlying `unlock` syscall is still blocking.
pub trait AsyncFileExt {
/// Returns the amount of physical space allocated for a file.
fn allocated_size(&self) -> impl core::future::Future<Output = Result<u64>>;
/// Ensures that at least `len` bytes of disk space are allocated for the
/// file. After a successful call to `allocate`, subsequent writes to the
/// file within the specified length are guaranteed not to fail because of
/// lack of disk space.
///
/// On most platforms the file's logical size is also extended to `len`
/// bytes. On Windows, if the file's existing cluster-aligned allocation
/// already covers `len`, the logical size is left unchanged to work around
/// buffered-I/O quirks observed when the end-of-file pointer is moved
/// inside an already-allocated cluster.
fn allocate(&self, len: u64) -> impl core::future::Future<Output = Result<()>>;
/// Acquires a shared lock on the file, blocking until the lock can be
/// acquired.
fn lock_shared(&self) -> Result<()>;
/// Acquires an exclusive lock on the file, blocking until the lock can be
/// acquired. Mirrors [`std::fs::File::lock`].
fn lock(&self) -> Result<()>;
/// Attempts to acquire a shared lock on the file, without blocking.
///
/// Returns `Ok(())` if the lock was acquired, or
/// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)`
/// if the file is currently locked.
fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError>;
/// Attempts to acquire an exclusive lock on the file, without blocking.
///
/// Returns `Ok(())` if the lock was acquired, or
/// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)`
/// if the file is currently locked.
fn try_lock(&self) -> std::result::Result<(), crate::TryLockError>;
/// Releases any lock held on the file. The lock is also released
/// automatically when the file handle is closed.
fn unlock(&self) -> Result<()>;
/// Releases any lock held on the file.
///
/// **Note:** This method is not truly async; the underlying system call is
/// still blocking. It exists for convenience when used from an async
/// context.
fn unlock_async(&self) -> impl core::future::Future<Output = Result<()>>;
}
impl AsyncFileExt for $file {
async fn allocated_size(&self) -> Result<u64> {
sys::allocated_size(self).await
}
async fn allocate(&self, len: u64) -> Result<()> {
sys::allocate(self, len).await
}
fn lock_shared(&self) -> Result<()> {
sys::lock_shared(self)
}
fn lock(&self) -> Result<()> {
sys::lock(self)
}
fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError> {
sys::try_lock_shared(self)
}
fn try_lock(&self) -> std::result::Result<(), crate::TryLockError> {
sys::try_lock(self)
}
fn unlock(&self) -> Result<()> {
sys::unlock(self)
}
async fn unlock_async(&self) -> Result<()> {
sys::unlock(self)
}
}
}
}
macro_rules! test_mod {
($annotation:meta, $($use_stmt:item)*) => {
#[cfg(test)]
mod test {
extern crate tempfile;
use crate::{allocation_granularity, TryLockError};
$(
$use_stmt
)*
/// Tests shared file lock operations.
#[$annotation]
async fn lock_shared() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file1 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let file2 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let file3 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
// Concurrent shared access is OK, but not shared and exclusive.
file1.lock_shared().unwrap();
file2.lock_shared().unwrap();
assert!(matches!(file3.try_lock(), Err(TryLockError::WouldBlock)));
file1.unlock().unwrap();
assert!(matches!(file3.try_lock(), Err(TryLockError::WouldBlock)));
// Once all shared file locks are dropped, an exclusive lock may be created;
file2.unlock().unwrap();
file3.lock().unwrap();
}
/// `unlock_async` is a thin async wrapper over the
/// blocking `unlock` syscall. Verifies the forwarder
/// actually releases the lock.
#[$annotation]
async fn unlock_async_releases_lock() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file1 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let file2 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
file1.lock().unwrap();
assert!(matches!(file2.try_lock(), Err(TryLockError::WouldBlock)));
file1.unlock_async().await.unwrap();
file2.lock().unwrap();
file2.unlock_async().await.unwrap();
}
/// Tests exclusive file lock operations.
#[$annotation]
async fn lock_exclusive() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file1 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let file2 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
// No other access is possible once an exclusive lock is created.
file1.lock().unwrap();
assert!(matches!(file2.try_lock(), Err(TryLockError::WouldBlock)));
assert!(matches!(
file2.try_lock_shared(),
Err(TryLockError::WouldBlock),
));
// Once the exclusive lock is dropped, the second file is able to create a lock.
file1.unlock().unwrap();
file2.lock().unwrap();
}
/// Tests that a lock is released after the file that owns it is dropped.
#[$annotation]
async fn lock_cleanup() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file1 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let file2 = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
file1.lock().unwrap();
assert!(matches!(
file2.try_lock_shared(),
Err(TryLockError::WouldBlock),
));
// Drop file1; the lock should be released.
drop(file1);
file2.lock_shared().unwrap();
}
/// Tests file allocation.
#[$annotation]
async fn allocate() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file = fs::OpenOptions::new()
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let blksize = allocation_granularity(&path).unwrap();
// New files are created with no allocated size.
assert_eq!(0, file.allocated_size().await.unwrap());
assert_eq!(0, file.metadata().await.unwrap().len());
// Allocate space for the file, checking that the allocated size steps
// up by block size, and the file length matches the allocated size.
file.allocate(2 * blksize - 1).await.unwrap();
assert_eq!(2 * blksize, file.allocated_size().await.unwrap());
assert_eq!(2 * blksize - 1, file.metadata().await.unwrap().len());
// Truncate the file, checking that the allocated size steps down by
// block size.
file.set_len(blksize + 1).await.unwrap();
assert_eq!(2 * blksize, file.allocated_size().await.unwrap());
assert_eq!(blksize + 1, file.metadata().await.unwrap().len());
}
/// Regression for issue #13: on Windows, re-`allocate`-ing
/// inside an already-allocated cluster must not move the EOF
/// pointer (the old path called `set_len`, which triggered
/// Windows buffered-I/O quirks). The trait doc carves this
/// out from the general "file size is at least `len`"
/// contract, so this test asserts the strict invariant on
/// Windows and a loose one on Unix.
#[$annotation]
async fn allocate_preserves_eof_within_cluster() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file = fs::OpenOptions::new()
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let blksize = allocation_granularity(&path).unwrap();
file.allocate(2 * blksize - 1).await.unwrap();
assert_eq!(2 * blksize - 1, file.metadata().await.unwrap().len());
file.allocate(2 * blksize).await.unwrap();
#[cfg(windows)]
assert_eq!(
2 * blksize - 1,
file.metadata().await.unwrap().len(),
"Windows allocate must not extend EOF inside an already-allocated cluster (#13)",
);
#[cfg(unix)]
assert!(file.metadata().await.unwrap().len() >= 2 * blksize - 1);
}
/// Regression: `allocate` on a sparse file must reserve
/// blocks even when logical EOF already covers `len`. The
/// previous Unix implementation short-circuited on
/// `metadata().len()`, which for a file extended via
/// `set_len` is true with zero blocks allocated, so the
/// documented preallocation contract silently became a
/// no-op. Gated to Linux where `set_len` reliably
/// produces a sparse file and `st_blocks` reliably
/// reflects `fallocate` reservations.
#[cfg(target_os = "linux")]
#[$annotation]
async fn allocate_reserves_blocks_on_sparse_file() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file = fs::OpenOptions::new()
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let blksize = allocation_granularity(&path).unwrap();
file.set_len(4 * blksize).await.unwrap();
assert_eq!(4 * blksize, file.metadata().await.unwrap().len());
assert_eq!(0, file.allocated_size().await.unwrap());
file.allocate(4 * blksize).await.unwrap();
assert!(
file.allocated_size().await.unwrap() >= 4 * blksize,
"allocate on a sparse file must reserve blocks",
);
}
/// Exercises the `Err` arm of the Unix `fallocate` call
/// by invoking `allocate` on a read-only file
/// descriptor, which returns `EBADF`. Without this test
/// the error conversion
/// (`std::io::Error::from_raw_os_error`) and the
/// `Err(...) => Err(...)` match arm are uncovered. Gated
/// to Unix: Windows has a separate `allocate` with its
/// own error path.
#[cfg(unix)]
#[$annotation]
async fn allocate_forwards_fallocate_error() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
// Create then close the file.
drop(
fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&path)
.await
.unwrap(),
);
// Re-open read-only. `fallocate` requires a writable
// fd; the syscall fails with EBADF and the error is
// propagated through the match arm.
let file = fs::OpenOptions::new()
.read(true)
.open(&path)
.await
.unwrap();
let err = file.allocate(4096).await.unwrap_err();
assert!(
err.raw_os_error().is_some(),
"expected a raw OS error from fallocate, got {err:?}",
);
}
/// Regression test for issue #15: re-allocating the same length must
/// not fail on macOS.
#[$annotation]
async fn allocate_idempotent() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file = fs::OpenOptions::new()
.write(true)
.create(true)
.open(&path)
.await
.unwrap();
let blksize = allocation_granularity(&path).unwrap();
file.allocate(2 * blksize).await.unwrap();
file.allocate(2 * blksize).await.unwrap();
file.allocate(blksize).await.unwrap();
assert!(file.metadata().await.unwrap().len() >= 2 * blksize);
}
/// Checks filesystem space methods.
///
/// Uses a single `statvfs` call + destructure so the three
/// numbers are read atomically; calling `free_space` /
/// `available_space` / `total_space` separately makes the
/// assertions race with concurrent filesystem activity
/// from other tests.
///
/// Does not assert `available_space <= free_space`: on
/// macOS APFS the kernel reports `f_bavail > f_bfree`
/// because purgeable space (snapshots, cached data) is
/// counted as available but not as free, so the usual
/// POSIX invariant does not hold.
#[$annotation]
async fn filesystem_space() {
let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap();
let crate::FsStats {
free_space,
available_space,
total_space,
..
} = crate::statvfs(tempdir.path()).unwrap();
assert!(total_space >= free_space);
assert!(total_space >= available_space);
}
}
};
}
cfg_async_std! {
pub(crate) mod async_std_impl;
}
cfg_fs_err2_tokio! {
pub(crate) mod fs_err2_tokio_impl;
}
cfg_fs_err3_tokio! {
pub(crate) mod fs_err3_tokio_impl;
}
cfg_smol! {
pub(crate) mod smol_impl;
}
cfg_tokio! {
pub(crate) mod tokio_impl;
}