Skip to main content

qubit_fs/write/
async_file_writer.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Concrete asynchronous file writer handle.
9
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::fmt::Result as FmtResult;
13use std::io::Error as IoError;
14use std::io::ErrorKind as IoErrorKind;
15use std::io::Result as IoResult;
16use std::pin::Pin;
17use std::task::Context;
18use std::task::Poll;
19
20use qubit_io::AsyncOutput;
21
22use crate::error::FsEffectState;
23use crate::error::FsError;
24use crate::error::FsErrorKind;
25use crate::error::FsOperation;
26use crate::error::RecoveryCleanupState;
27use crate::facade::facade_core::FacadeCore;
28use crate::facade::internal::ByteBudget;
29use crate::facade::internal::FileSystemResource;
30use crate::facade::internal::RecoveryCleanupGuard;
31use crate::metadata::AchievedAtomicity;
32use crate::metadata::AtomicityRequirement;
33use crate::metadata::DurabilityRequirement;
34use crate::metadata::OpenedFileInfo;
35use crate::metadata::WriteOutcome;
36use crate::spi::AsyncFileWriteSession;
37use crate::spi::SpiFuture;
38use crate::write::WriteAbortOutcome;
39use crate::write::WriteFailure;
40use crate::write::WriteFailureState;
41use crate::write::WriterState;
42
43/// Type-erased asynchronous provider write session associated with a file.
44///
45/// # Examples
46///
47/// This example uses an isolated in-memory provider fixture.
48///
49/// ```rust
50/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
51/// # use support::*;
52/// # let (filesystem, _) = async_recording_spi::async_recording_file_system(Default::default());
53/// # poll_support::ready(async {
54/// use qubit_fs::Path;
55/// use qubit_fs::write::WriteOptions;
56/// use qubit_fs::write::WriterState;
57/// use qubit_io::AsyncOutput;
58///
59/// let mut writer = filesystem.open_writer(&Path::parse("/report")?, WriteOptions::default()).await?;
60/// writer.write_fully_async(b"bytes").await?;
61/// writer.commit_async().await?;
62/// assert_eq!(WriterState::Committed, writer.state());
63/// # Ok::<(), Box<dyn std::error::Error>>(())
64/// # }).unwrap();
65/// ```
66pub struct AsyncFileWriter {
67    /// Pinned provider write session.
68    session: Pin<Box<dyn AsyncFileWriteSession>>,
69    /// Stable identity and metadata captured at open time.
70    info: OpenedFileInfo,
71    /// Current publication lifecycle state.
72    state: WriterState,
73    /// Whether this session has ever had confirmed publication evidence.
74    confirmed_publication: bool,
75    /// Current state of explicit provider cleanup.
76    cleanup_state: RecoveryCleanupState,
77    /// Atomicity required by the caller.
78    atomicity: AtomicityRequirement,
79    /// Durability required by the caller.
80    durability: DurabilityRequirement,
81    /// Provider identifier attached to facade-generated errors.
82    provider: Box<str>,
83    /// Optional inclusive byte limit for this write session.
84    write_budget: Option<ByteBudget>,
85    /// Bytes accepted by the provider session so far.
86    written_bytes: u64,
87}
88
89impl AsyncFileWriter {
90    /// Wraps an already-open asynchronous provider write session.
91    ///
92    /// # Parameters
93    /// - `session`: Runtime-neutral asynchronous write session.
94    /// - `info`: File identity and optional open-time metadata snapshot.
95    ///
96    /// # Returns
97    /// A concrete writer in [`WriterState::Open`].
98    #[inline]
99    #[must_use]
100    pub(crate) fn new(
101        info: OpenedFileInfo,
102        session: Box<dyn AsyncFileWriteSession>,
103        atomicity: AtomicityRequirement,
104        durability: DurabilityRequirement,
105        provider: &str,
106        max_write_bytes: Option<u64>,
107    ) -> Self {
108        Self {
109            session: Box::into_pin(session),
110            info,
111            state: WriterState::Open,
112            confirmed_publication: false,
113            cleanup_state: RecoveryCleanupState::Pending,
114            atomicity,
115            durability,
116            provider: provider.into(),
117            write_budget: max_write_bytes
118                .map(|maximum| FacadeCore::byte_budget(FileSystemResource::WriteBytes, maximum)),
119            written_bytes: 0,
120        }
121    }
122
123    /// Returns the fixed identity and open-time metadata snapshot.
124    ///
125    /// # Returns
126    /// Information captured when the writer was opened.
127    #[inline]
128    #[must_use]
129    pub fn info(&self) -> &OpenedFileInfo {
130        &self.info
131    }
132
133    /// Returns the current lifecycle state.
134    ///
135    /// # Returns
136    /// Current writer state.
137    #[inline]
138    #[must_use]
139    pub const fn state(&self) -> WriterState {
140        self.state
141    }
142
143    /// Returns whether this writer session has confirmed publication at any
144    /// time.
145    ///
146    /// # Returns
147    /// `true` when a commit or abort outcome confirmed publication. `false`
148    /// does not prove that publication did not occur.
149    #[inline]
150    #[must_use]
151    pub const fn has_confirmed_publication(&self) -> bool {
152        self.confirmed_publication
153    }
154
155    /// Returns the state of explicit provider cleanup for this session.
156    ///
157    /// # Returns
158    /// The latest cleanup state, independently of publication history.
159    #[inline]
160    #[must_use]
161    pub const fn cleanup_state(&self) -> RecoveryCleanupState {
162        self.cleanup_state
163    }
164
165    /// Asynchronously publishes bytes accepted by this session.
166    ///
167    /// A definite failure retains the open session for retry or abort. An
168    /// indeterminate failure retains the session and changes its observable
169    /// state to [`WriterState::Indeterminate`]. Once the returned future has
170    /// been polled, dropping it before completion also makes the writer
171    /// indeterminate because publication may already have started. Dropping an
172    /// unpolled future leaves the writer open. Only a failure in
173    /// [`WriteFailureState::RetryableNotPublished`] leaves the writer open for
174    /// another explicit commit attempt. [`WriteFailureState::NotPublished`]
175    /// allows only a valid abort; it does not make commit retryable.
176    ///
177    /// # Returns
178    /// A future resolving to the actual publication outcome.
179    ///
180    /// # Errors
181    /// The future returns [`WriteFailure`] when the provider fails publication
182    /// or violates the requested atomicity, durability, or byte-count
183    /// contract. The failure state records what is known about publication.
184    pub fn commit_async(&mut self) -> SpiFuture<'_, Result<WriteOutcome, WriteFailure>> {
185        if self.state != WriterState::Open {
186            let publication_state = if self.confirmed_publication {
187                WriteFailureState::Published
188            } else {
189                self.state.publication_failure_state()
190            };
191            let error = self.invalid_state(
192                FsOperation::CommitWriter,
193                "writer cannot be committed in its current state",
194            );
195            return Box::pin(async move { Err(WriteFailure::new(error, publication_state)) });
196        }
197        Box::pin(async move {
198            self.state = WriterState::Indeterminate;
199            let result = self.session.as_mut().commit_async().await;
200            match result {
201                Ok(outcome) => {
202                    self.confirmed_publication = true;
203                    self.state = WriterState::Committed;
204                    if self.atomicity == AtomicityRequirement::Required
205                        && outcome.atomicity() != AchievedAtomicity::Atomic
206                    {
207                        self.state = WriterState::Published;
208                        return Err(WriteFailure::new(
209                            FsError::new(
210                                FsErrorKind::ProviderContractViolation,
211                                FsOperation::CommitWriter,
212                                "provider reported non-atomic success for an atomic-required write",
213                            )
214                            .with_path(self.info.path().clone())
215                            .with_provider(&self.provider)
216                            .with_effect_state(FsEffectState::Applied),
217                            WriteFailureState::Published,
218                        ));
219                    }
220                    if self.durability == DurabilityRequirement::Required && !outcome.durable() {
221                        self.state = WriterState::Published;
222                        return Err(WriteFailure::new(
223                            FsError::new(
224                                FsErrorKind::ProviderContractViolation,
225                                FsOperation::CommitWriter,
226                                "provider reported non-durable success for a durability-required write",
227                            )
228                            .with_path(self.info.path().clone())
229                            .with_provider(&self.provider)
230                            .with_effect_state(FsEffectState::Applied),
231                            WriteFailureState::Published,
232                        ));
233                    }
234                    if let Some(bytes_written) = outcome.bytes_written()
235                        && bytes_written != self.written_bytes
236                    {
237                        self.state = WriterState::Published;
238                        return Err(WriteFailure::new(
239                            FsError::new(
240                                FsErrorKind::ProviderContractViolation,
241                                FsOperation::CommitWriter,
242                                "provider reported a byte count different from the bytes accepted by the writer",
243                            )
244                            .with_path(self.info.path().clone())
245                            .with_provider(&self.provider)
246                            .with_effect_state(FsEffectState::Applied),
247                            WriteFailureState::Published,
248                        ));
249                    }
250                    Ok(outcome)
251                }
252                Err(failure) => {
253                    if failure.state() == WriteFailureState::Published {
254                        self.confirmed_publication = true;
255                    }
256                    self.state = match failure.state() {
257                        WriteFailureState::RetryableNotPublished => WriterState::Open,
258                        WriteFailureState::NotPublished => WriterState::NotPublished,
259                        WriteFailureState::Published => WriterState::Published,
260                        WriteFailureState::Indeterminate => WriterState::Indeterminate,
261                    };
262                    let (error, state) = failure.into_parts();
263                    Err(WriteFailure::new(
264                        self.contextual_error(error, FsOperation::CommitWriter),
265                        state,
266                    ))
267                }
268            }
269        })
270    }
271
272    /// Asynchronously aborts this session and its provider staging resources.
273    ///
274    /// Once polled, cancellation before completion leaves the writer
275    /// indeterminate. A definite provider failure restores the state from
276    /// which abort was started; an indeterminate provider failure does not.
277    /// Automatic drop cancellation is disabled for an indeterminate writer.
278    ///
279    /// # Returns
280    /// A future resolving to the provider-confirmed destination publication
281    /// state after cleanup. Every `Ok` confirms cleanup;
282    /// `Indeterminate` means only that destination publication is unknown.
283    ///
284    /// # Errors
285    /// The future returns an [`FsError`] when provider cleanup fails. The error
286    /// includes the operation context available from the facade.
287    pub fn abort_async(&mut self) -> SpiFuture<'_, crate::error::FsResult<WriteAbortOutcome>> {
288        if self.cleanup_state == RecoveryCleanupState::Completed
289            || !matches!(
290                self.state,
291                WriterState::Open | WriterState::NotPublished | WriterState::Published | WriterState::Indeterminate
292            )
293        {
294            let error = self.invalid_state(
295                FsOperation::AbortWriter,
296                "writer cannot be aborted in its current state",
297            );
298            return Box::pin(async move { Err(error) });
299        }
300        Box::pin(async move {
301            let previous_state = self.state;
302            self.state = WriterState::Indeterminate;
303            let mut cleanup = RecoveryCleanupGuard::start(&mut self.cleanup_state);
304            let result = self.session.as_mut().abort_async().await;
305            cleanup.finish(result.is_ok());
306            drop(cleanup);
307            match result {
308                Ok(outcome) => {
309                    if outcome == WriteAbortOutcome::Published {
310                        self.confirmed_publication = true;
311                    }
312                    self.state = match outcome {
313                        WriteAbortOutcome::NotPublished => WriterState::Aborted,
314                        WriteAbortOutcome::Published => WriterState::Published,
315                        WriteAbortOutcome::Indeterminate => WriterState::Indeterminate,
316                    };
317                    Ok(outcome)
318                }
319                Err(error) => {
320                    if !error.has_indeterminate_effect() {
321                        self.state = previous_state;
322                    }
323                    Err(self.contextual_error(error, FsOperation::AbortWriter))
324                }
325            }
326        })
327    }
328
329    /// Returns the bytes accepted by the underlying write session.
330    #[inline]
331    #[must_use]
332    pub(crate) const fn written_bytes(&self) -> u64 {
333        self.written_bytes
334    }
335
336    /// Records that cancellation interrupted an operation using this writer.
337    #[inline]
338    pub(crate) fn mark_indeterminate(&mut self) {
339        self.state = WriterState::Indeterminate;
340    }
341
342    /// Builds a stable invalid-state error.
343    /// # Parameters
344    /// - `operation`: Filesystem operation associated with the error.
345    /// - `message`: Stable description included in the invalid-state error.
346    fn invalid_state(&self, operation: FsOperation, message: &str) -> FsError {
347        FsError::new(FsErrorKind::InvalidState, operation, message)
348            .with_path(self.info.path().clone())
349            .with_provider(&self.provider)
350    }
351
352    /// Builds a byte-transfer error after lifecycle completion.
353    fn closed_io_error(&self) -> IoError {
354        IoError::new(
355            IoErrorKind::BrokenPipe,
356            self.invalid_state(FsOperation::Write, "writer no longer accepts bytes"),
357        )
358    }
359
360    /// Checks whether a provider write can fit in the session budget.
361    /// # Parameters
362    /// - `count`: Byte count checked against or added to the session budget.
363    fn check_write_limit(&self, count: usize) -> IoResult<u64> {
364        let count = FacadeCore::quantity_from_usize(count, FsOperation::Write, self.info.path(), &self.provider)
365            .map_err(FsError::into_io_error)?;
366        if let Some(budget) = &self.write_budget
367            && let Err(error) = budget.check_available(count)
368        {
369            return Err(FacadeCore::budget_error(
370                error,
371                FsOperation::Write,
372                self.info.path(),
373                &self.provider,
374                "write session exceeds the provider byte limit",
375            )
376            .into_io_error());
377        }
378        Ok(count)
379    }
380
381    /// Records bytes accepted by the provider in the public `u64` accounting
382    /// domain.
383    ///
384    /// Returns an I/O error when the native byte count or accumulated total
385    /// cannot be represented by the filesystem API's `u64` byte counters.
386    /// # Parameters
387    /// - `count`: Byte count checked against or added to the session budget.
388    fn record_written_bytes(&mut self, count: usize) -> IoResult<()> {
389        let count = FacadeCore::quantity_from_usize(count, FsOperation::Write, self.info.path(), &self.provider)
390            .map_err(FsError::into_io_error)?;
391        if let Some(error) = self
392            .write_budget
393            .as_mut()
394            .and_then(|budget| budget.try_consume(count).err())
395        {
396            return Err(FacadeCore::budget_error(
397                error,
398                FsOperation::Write,
399                self.info.path(),
400                &self.provider,
401                "write session exceeds the provider byte limit",
402            )
403            .into_io_error());
404        }
405        self.written_bytes = self
406            .written_bytes
407            .checked_add(count)
408            .ok_or_else(|| self.byte_count_error())?;
409        Ok(())
410    }
411
412    /// Builds the error used when native byte accounting exceeds the public
413    /// filesystem API's `u64` reporting range.
414    fn byte_count_error(&self) -> IoError {
415        FsError::new(
416            FsErrorKind::ResourceLimitExceeded,
417            FsOperation::Write,
418            "write byte count exceeds the filesystem API reporting range",
419        )
420        .with_path(self.info.path().clone())
421        .with_provider(&self.provider)
422        .into_io_error()
423    }
424
425    /// Adds only missing facade context to a provider lifecycle error.
426    /// # Parameters
427    /// - `error`: Failure whose trusted filesystem context is being restored.
428    /// - `operation`: Filesystem operation associated with the error.
429    fn contextual_error(&self, error: FsError, operation: FsOperation) -> FsError {
430        error
431            .with_operation(operation)
432            .with_missing_context(self.info.path(), None, &self.provider)
433    }
434}
435
436impl AsyncOutput for AsyncFileWriter {
437    /// The byte unit accepted by this writer.
438    type Item = u8;
439
440    /// Reports whether the provider session buffers output before flushing.
441    #[inline]
442    fn is_buffered(&self) -> bool {
443        self.session.is_buffered()
444    }
445
446    /// Polls a provider write while tracking accepted bytes and uncertainty.
447    ///
448    /// # Safety
449    /// `index` and `count` must identify a valid range within `input`.
450    /// # Parameters
451    /// - `cx`: Task context used to poll the provider session.
452    /// - `input`: Input bytes containing the requested range.
453    /// - `index`: Starting offset of the requested input range.
454    /// - `count`: Maximum number of bytes requested from the provider.
455    unsafe fn poll_write_unchecked(
456        self: Pin<&mut Self>,
457        cx: &mut Context<'_>,
458        input: &[u8],
459        index: usize,
460        count: usize,
461    ) -> Poll<IoResult<usize>> {
462        let this = self.get_mut();
463        if count == 0 {
464            return Poll::Ready(Ok(0));
465        }
466        if this.state != WriterState::Open {
467            return Poll::Ready(Err(this.closed_io_error()));
468        }
469        if let Err(error) = this.check_write_limit(count) {
470            return Poll::Ready(Err(error));
471        }
472        // SAFETY: The caller guarantees the same range contract required by
473        // the wrapped asynchronous output session.
474        match unsafe { this.session.as_mut().poll_write_unchecked(cx, input, index, count) } {
475            Poll::Ready(Ok(written)) => {
476                if written > count {
477                    this.state = WriterState::Indeterminate;
478                    return Poll::Ready(Err(FsError::new(
479                        FsErrorKind::ProviderContractViolation,
480                        FsOperation::Write,
481                        "provider reported accepting more bytes than requested",
482                    )
483                    .with_effect_state(FsEffectState::Indeterminate)
484                    .with_path(this.info.path().clone())
485                    .with_provider(&this.provider)
486                    .into_io_error()));
487                }
488                if let Err(error) = this.record_written_bytes(written) {
489                    this.state = WriterState::Indeterminate;
490                    return Poll::Ready(Err(error));
491                }
492                if count > 0 && written == 0 && this.written_bytes > 0 {
493                    this.state = WriterState::Indeterminate;
494                }
495                Poll::Ready(Ok(written))
496            }
497            Poll::Ready(Err(error)) => {
498                this.state = WriterState::Indeterminate;
499                Poll::Ready(Err(error))
500            }
501            Poll::Pending => Poll::Pending,
502        }
503    }
504
505    /// Polls the provider flush and marks the writer indeterminate on failure.
506    /// # Parameters
507    /// - `cx`: Task context used to poll the provider session.
508    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
509        let this = self.get_mut();
510        if this.state != WriterState::Open {
511            return Poll::Ready(Err(this.closed_io_error()));
512        }
513        match this.session.as_mut().poll_flush(cx) {
514            Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
515            Poll::Ready(Err(error)) => {
516                this.state = WriterState::Indeterminate;
517                Poll::Ready(Err(error))
518            }
519            Poll::Pending => Poll::Pending,
520        }
521    }
522}
523
524impl Debug for AsyncFileWriter {
525    /// Formats lifecycle facts without exposing the provider session.
526    /// # Parameters
527    /// - `formatter`: Formatter receiving the diagnostic representation.
528    #[inline]
529    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
530        formatter
531            .debug_struct("AsyncFileWriter")
532            .field("info", &self.info)
533            .field("state", &self.state)
534            .finish_non_exhaustive()
535    }
536}
537
538impl Drop for AsyncFileWriter {
539    /// Requests provider cancellation when this writer still owns live work.
540    fn drop(&mut self) {
541        if self.cleanup_state != RecoveryCleanupState::Completed
542            && matches!(
543                self.state,
544                WriterState::Open | WriterState::NotPublished | WriterState::Published
545            )
546        {
547            self.session.as_mut().cancel_on_drop();
548        }
549    }
550}
551
552#[cfg(test)]
553mod tests {
554    use std::pin::Pin;
555    use std::task::Context;
556    use std::task::Poll;
557    use std::task::Waker;
558
559    use qubit_io::AsyncOutput;
560
561    use super::AsyncFileWriter;
562    use crate::error::FsResult;
563    use crate::metadata::AchievedAtomicity;
564    use crate::metadata::AtomicityRequirement;
565    use crate::metadata::DurabilityRequirement;
566    use crate::metadata::FileSystemId;
567    use crate::metadata::OpenedFileInfo;
568    use crate::metadata::PublicationMethod;
569    use crate::metadata::WriteOutcome;
570    use crate::path::Path;
571    use crate::spi::AsyncFileWriteSession;
572    use crate::spi::SpiFuture;
573    use crate::write::WriteAbortOutcome;
574    use crate::write::WriteFailure;
575
576    struct Session;
577
578    impl AsyncOutput for Session {
579        type Item = u8;
580
581        fn is_buffered(&self) -> bool {
582            false
583        }
584
585        unsafe fn poll_write_unchecked(
586            self: Pin<&mut Self>,
587            _: &mut Context<'_>,
588            _: &[u8],
589            _: usize,
590            count: usize,
591        ) -> Poll<std::io::Result<usize>> {
592            Poll::Ready(Ok(count))
593        }
594
595        fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<std::io::Result<()>> {
596            Poll::Ready(Ok(()))
597        }
598    }
599
600    impl AsyncFileWriteSession for Session {
601        fn commit_async<'a>(self: Pin<&'a mut Self>) -> SpiFuture<'a, Result<WriteOutcome, WriteFailure>> {
602            Box::pin(async {
603                Ok(WriteOutcome::new(
604                    AchievedAtomicity::Atomic,
605                    PublicationMethod::AtomicRename,
606                ))
607            })
608        }
609
610        fn abort_async<'a>(self: Pin<&'a mut Self>) -> SpiFuture<'a, FsResult<WriteAbortOutcome>> {
611            Box::pin(async { Ok(WriteAbortOutcome::NotPublished) })
612        }
613    }
614
615    #[test]
616    fn test_zero_length_write_preserves_bytes_after_nonempty_write() {
617        let info = OpenedFileInfo::new(
618            FileSystemId::new("async-writer-test").unwrap(),
619            Path::parse("/zero-write").unwrap(),
620        );
621        let mut writer = AsyncFileWriter::new(
622            info,
623            Box::new(Session),
624            AtomicityRequirement::default(),
625            DurabilityRequirement::default(),
626            "async-writer-test",
627            None,
628        );
629        let mut cx = Context::from_waker(Waker::noop());
630        assert!(matches!(
631            unsafe { Pin::new(&mut writer).poll_write_unchecked(&mut cx, b"x", 0, 1) },
632            Poll::Ready(Ok(1))
633        ));
634        assert_eq!(1, writer.written_bytes());
635
636        let written_bytes = writer.written_bytes();
637        assert!(matches!(
638            unsafe { Pin::new(&mut writer).poll_write_unchecked(&mut cx, b"", 0, 0) },
639            Poll::Ready(Ok(0))
640        ));
641        assert_eq!(written_bytes, writer.written_bytes());
642    }
643}