Skip to main content

file_storage/op/file/write/
write_op.rs

1use crate::system::LocalWriteOp;
2use std::io::Write;
3
4/// A write operation.
5///
6/// # Close
7/// The write is only guaranteed to be committed by `close`. `flush` is not a durability point:
8/// backends that upload in parts, such as Cloudflare R2, cannot commit a trailing partial part
9/// before the operation is closed. Dropping the operation without calling `close` discards the
10/// write on those backends.
11pub struct WriteOp {
12    pub(crate) inner: WriteOpInner,
13}
14
15/// A file-system-specific write operation.
16pub(crate) enum WriteOpInner {
17    /// A local write operation.
18    Local(LocalWriteOp),
19
20    /// A cloudflare R2 write operation.
21    #[cfg(feature = "r2")]
22    R2(crate::R2WriteOp),
23}
24
25impl Write for WriteOp {
26    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
27        match &mut self.inner {
28            WriteOpInner::Local(op) => op.write(buf),
29            #[cfg(feature = "r2")]
30            WriteOpInner::R2(op) => op.write(buf),
31        }
32    }
33
34    /// Flushes what the backend is able to commit before the operation is closed.
35    ///
36    /// See the `Close` section on `WriteOp`: this is not a durability point.
37    fn flush(&mut self) -> std::io::Result<()> {
38        match &mut self.inner {
39            WriteOpInner::Local(op) => op.flush(),
40            #[cfg(feature = "r2")]
41            WriteOpInner::R2(op) => op.flush(),
42        }
43    }
44}
45
46impl WriteOp {
47    //! Close
48
49    /// Ensures the file has been completely written and closes the file.
50    ///
51    /// This must be called. Dropping the operation instead discards the write on backends that
52    /// upload in parts, such as Cloudflare R2.
53    pub fn close(self) -> Result<(), std::io::Error> {
54        match self.inner {
55            WriteOpInner::Local(op) => op.close(),
56            #[cfg(feature = "r2")]
57            WriteOpInner::R2(op) => op.close(),
58        }
59    }
60}