Skip to main content

qubit_fs/write/
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 synchronous 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;
16
17use qubit_io::Output;
18
19use crate::error::FsEffectState;
20use crate::error::FsError;
21use crate::error::FsErrorKind;
22use crate::error::FsOperation;
23use crate::error::FsResult;
24use crate::error::RecoveryCleanupState;
25use crate::facade::facade_core::FacadeCore;
26use crate::facade::internal::ByteBudget;
27use crate::facade::internal::FileSystemResource;
28use crate::facade::internal::RecoveryCleanupGuard;
29use crate::metadata::AchievedAtomicity;
30use crate::metadata::AtomicityRequirement;
31use crate::metadata::DurabilityRequirement;
32use crate::metadata::OpenedFileInfo;
33use crate::metadata::WriteOutcome;
34use crate::spi::FileWriterSpi;
35use crate::write::WriteAbortOutcome;
36use crate::write::WriteFailure;
37use crate::write::WriteFailureState;
38use crate::write::WriterState;
39
40/// Type-erased provider write session explicitly associated with a file.
41///
42/// # Examples
43///
44/// This example uses an isolated in-memory provider fixture.
45///
46/// ```rust
47/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
48/// # let filesystem = support::rustdoc_provider::filesystem();
49/// use qubit_fs::Path;
50/// use qubit_fs::write::WriteOptions;
51/// use qubit_fs::write::WriterState;
52/// use qubit_io::Output;
53///
54/// let mut writer = filesystem.open_writer(&Path::parse("/new-report")?, WriteOptions::default())?;
55/// writer.write_fully(b"report")?;
56/// let outcome = writer.commit()?;
57/// assert_eq!(Some(6), outcome.bytes_written());
58/// assert_eq!(WriterState::Committed, writer.state());
59/// # Ok::<(), Box<dyn std::error::Error>>(())
60/// ```
61pub struct FileWriter {
62    /// Provider write session.
63    session: Box<dyn FileWriterSpi>,
64    /// Stable identity and metadata captured at open time.
65    info: OpenedFileInfo,
66    /// Current publication lifecycle state.
67    state: WriterState,
68    /// Whether this session has ever had confirmed publication evidence.
69    confirmed_publication: bool,
70    /// Current state of explicit provider cleanup.
71    cleanup_state: RecoveryCleanupState,
72    /// Atomicity required by the caller.
73    atomicity: AtomicityRequirement,
74    /// Durability required by the caller.
75    durability: DurabilityRequirement,
76    /// Provider identifier attached to facade-generated errors.
77    provider: Box<str>,
78    /// Optional inclusive byte limit for this write session.
79    write_budget: Option<ByteBudget>,
80    /// Bytes accepted by the provider session so far.
81    written_bytes: u64,
82}
83
84impl FileWriter {
85    /// Wraps an already-open provider write session.
86    ///
87    /// # Parameters
88    ///
89    /// - `info`: File identity and optional open-time metadata snapshot.
90    /// - `session`: Provider session accepting file bytes.
91    /// - `atomicity`: Caller-required atomicity checked against publication
92    ///   outcomes.
93    /// - `durability`: Caller-required durability checked against publication
94    ///   outcomes.
95    /// - `provider`: Provider identifier attached to facade-generated errors.
96    /// - `max_write_bytes`: Inclusive limit on cumulative bytes accepted by
97    ///   this session. `None` imposes no finite byte limit here; `Some(0)`
98    ///   permits only zero-byte writes. This is not a process-memory limit.
99    ///
100    /// # Returns
101    /// A concrete writer in [`WriterState::Open`].
102    #[inline]
103    #[must_use]
104    pub(crate) fn new(
105        info: OpenedFileInfo,
106        session: Box<dyn FileWriterSpi>,
107        atomicity: AtomicityRequirement,
108        durability: DurabilityRequirement,
109        provider: &str,
110        max_write_bytes: Option<u64>,
111    ) -> Self {
112        Self {
113            session,
114            info,
115            state: WriterState::Open,
116            confirmed_publication: false,
117            cleanup_state: RecoveryCleanupState::Pending,
118            atomicity,
119            durability,
120            provider: provider.into(),
121            write_budget: max_write_bytes
122                .map(|maximum| FacadeCore::byte_budget(FileSystemResource::WriteBytes, maximum)),
123            written_bytes: 0,
124        }
125    }
126
127    /// Returns the fixed identity and open-time metadata snapshot.
128    ///
129    /// # Returns
130    /// Information captured when the writer was opened.
131    #[inline]
132    #[must_use]
133    pub fn info(&self) -> &OpenedFileInfo {
134        &self.info
135    }
136
137    /// Returns the current lifecycle state.
138    ///
139    /// # Returns
140    /// Current writer state.
141    #[inline]
142    #[must_use]
143    pub const fn state(&self) -> WriterState {
144        self.state
145    }
146
147    /// Returns whether this writer session has confirmed publication at any
148    /// time.
149    ///
150    /// # Returns
151    /// `true` when a commit or abort outcome confirmed publication. `false`
152    /// does not prove that publication did not occur.
153    #[inline]
154    #[must_use]
155    pub const fn has_confirmed_publication(&self) -> bool {
156        self.confirmed_publication
157    }
158
159    /// Returns the state of explicit provider cleanup for this session.
160    ///
161    /// # Returns
162    /// The latest cleanup state, independently of publication history.
163    #[inline]
164    #[must_use]
165    pub const fn cleanup_state(&self) -> RecoveryCleanupState {
166        self.cleanup_state
167    }
168
169    /// Publishes bytes accepted by this session.
170    ///
171    /// This method borrows rather than consumes the writer. The provider's
172    /// typed failure determines whether retry remains safe or only explicit
173    /// cleanup is available.
174    ///
175    /// # Returns
176    /// Actual publication method and atomicity on success.
177    ///
178    /// # Errors
179    /// Returns [`FsErrorKind::InvalidState`] after commit or abort, or the
180    /// provider publication error.
181    pub fn commit(&mut self) -> Result<WriteOutcome, WriteFailure> {
182        if self.state != WriterState::Open {
183            let publication_state = if self.confirmed_publication {
184                WriteFailureState::Published
185            } else {
186                self.state.publication_failure_state()
187            };
188            return Err(WriteFailure::new(
189                self.invalid_state(
190                    FsOperation::CommitWriter,
191                    "writer cannot be committed in its current state",
192                ),
193                publication_state,
194            ));
195        }
196        let outcome = self.session.commit();
197        match outcome {
198            Ok(outcome) => {
199                self.confirmed_publication = true;
200                self.state = WriterState::Committed;
201                if self.atomicity == AtomicityRequirement::Required && outcome.atomicity() != AchievedAtomicity::Atomic
202                {
203                    self.state = WriterState::Published;
204                    return Err(WriteFailure::new(
205                        FsError::new(
206                            FsErrorKind::ProviderContractViolation,
207                            FsOperation::CommitWriter,
208                            "provider reported non-atomic success for an atomic-required write",
209                        )
210                        .with_path(self.info.path().clone())
211                        .with_provider(&self.provider)
212                        .with_effect_state(FsEffectState::Applied),
213                        WriteFailureState::Published,
214                    ));
215                }
216                if self.durability == DurabilityRequirement::Required && !outcome.durable() {
217                    self.state = WriterState::Published;
218                    return Err(WriteFailure::new(
219                        FsError::new(
220                            FsErrorKind::ProviderContractViolation,
221                            FsOperation::CommitWriter,
222                            "provider reported non-durable success for a durability-required write",
223                        )
224                        .with_path(self.info.path().clone())
225                        .with_provider(&self.provider)
226                        .with_effect_state(FsEffectState::Applied),
227                        WriteFailureState::Published,
228                    ));
229                }
230                if let Some(bytes_written) = outcome.bytes_written()
231                    && bytes_written != self.written_bytes
232                {
233                    self.state = WriterState::Published;
234                    return Err(WriteFailure::new(
235                        FsError::new(
236                            FsErrorKind::ProviderContractViolation,
237                            FsOperation::CommitWriter,
238                            "provider reported a byte count different from the bytes accepted by the writer",
239                        )
240                        .with_path(self.info.path().clone())
241                        .with_provider(&self.provider)
242                        .with_effect_state(FsEffectState::Applied),
243                        WriteFailureState::Published,
244                    ));
245                }
246                Ok(outcome)
247            }
248            Err(failure) => {
249                self.state = match failure.state() {
250                    WriteFailureState::RetryableNotPublished => WriterState::Open,
251                    WriteFailureState::NotPublished => WriterState::NotPublished,
252                    WriteFailureState::Published => WriterState::Published,
253                    WriteFailureState::Indeterminate => WriterState::Indeterminate,
254                };
255                if failure.state() == WriteFailureState::Published {
256                    self.confirmed_publication = true;
257                }
258                let (error, state) = failure.into_parts();
259                Err(WriteFailure::new(
260                    self.contextual_error(error, FsOperation::CommitWriter),
261                    state,
262                ))
263            }
264        }
265    }
266
267    /// Aborts this writer and releases provider staging resources.
268    ///
269    /// Abort is allowed while open and after every failed commit. Successful
270    /// cleanup does not imply that an already-published target was rolled back.
271    /// Every `Ok` outcome confirms cleanup; `Indeterminate` means only that the
272    /// destination publication state remains unknown.
273    /// An indeterminate abort disables automatic drop cleanup so the caller can
274    /// inspect provider state before choosing a recovery action.
275    ///
276    /// # Returns
277    /// Provider-confirmed destination publication state after cleanup.
278    ///
279    /// # Errors
280    /// Returns [`FsErrorKind::InvalidState`] after commit or a previous abort,
281    /// or returns the provider cleanup error while retaining the session.
282    pub fn abort(&mut self) -> FsResult<WriteAbortOutcome> {
283        if self.cleanup_state == RecoveryCleanupState::Completed
284            || !matches!(
285                self.state,
286                WriterState::Open | WriterState::NotPublished | WriterState::Published | WriterState::Indeterminate
287            )
288        {
289            return Err(self.invalid_state(
290                FsOperation::AbortWriter,
291                "writer cannot be aborted in its current state",
292            ));
293        }
294        let mut cleanup = RecoveryCleanupGuard::start(&mut self.cleanup_state);
295        let result = self.session.abort();
296        cleanup.finish(result.is_ok());
297        drop(cleanup);
298        match result {
299            Ok(outcome) => {
300                if outcome == WriteAbortOutcome::Published {
301                    self.confirmed_publication = true;
302                }
303                self.state = match outcome {
304                    WriteAbortOutcome::NotPublished => WriterState::Aborted,
305                    WriteAbortOutcome::Published => WriterState::Published,
306                    WriteAbortOutcome::Indeterminate => WriterState::Indeterminate,
307                };
308                Ok(outcome)
309            }
310            Err(error) => {
311                if error.has_indeterminate_effect() {
312                    self.state = WriterState::Indeterminate;
313                }
314                Err(self.contextual_error(error, FsOperation::AbortWriter))
315            }
316        }
317    }
318
319    /// Returns the bytes accepted by the underlying write session.
320    #[inline]
321    #[must_use]
322    pub(crate) const fn written_bytes(&self) -> u64 {
323        self.written_bytes
324    }
325
326    /// Builds a stable invalid-state error for this writer.
327    /// # Parameters
328    /// - `operation`: Filesystem operation associated with the error.
329    /// - `message`: Stable description included in the invalid-state error.
330    fn invalid_state(&self, operation: FsOperation, message: &str) -> FsError {
331        FsError::new(FsErrorKind::InvalidState, operation, message)
332            .with_path(self.info.path().clone())
333            .with_provider(&self.provider)
334    }
335
336    /// Builds a stream error for byte transfer after lifecycle completion.
337    fn closed_io_error(&self) -> IoError {
338        IoError::new(
339            IoErrorKind::BrokenPipe,
340            self.invalid_state(FsOperation::Write, "writer no longer accepts bytes"),
341        )
342    }
343
344    /// Checks whether a provider write can fit in the session budget.
345    /// # Parameters
346    /// - `count`: Byte count checked against or added to the session budget.
347    fn check_write_limit(&self, count: usize) -> IoResult<u64> {
348        let count = FacadeCore::quantity_from_usize(count, FsOperation::Write, self.info.path(), &self.provider)
349            .map_err(FsError::into_io_error)?;
350        if let Some(budget) = &self.write_budget
351            && let Err(error) = budget.check_available(count)
352        {
353            return Err(FacadeCore::budget_error(
354                error,
355                FsOperation::Write,
356                self.info.path(),
357                &self.provider,
358                "write session exceeds the provider byte limit",
359            )
360            .into_io_error());
361        }
362        Ok(count)
363    }
364
365    /// Records bytes accepted by the provider in the public `u64` accounting
366    /// domain.
367    ///
368    /// Returns an I/O error when the native byte count or accumulated total
369    /// cannot be represented by the filesystem API's `u64` byte counters.
370    /// # Parameters
371    /// - `count`: Byte count checked against or added to the session budget.
372    fn record_written_bytes(&mut self, count: usize) -> IoResult<()> {
373        let count = FacadeCore::quantity_from_usize(count, FsOperation::Write, self.info.path(), &self.provider)
374            .map_err(FsError::into_io_error)?;
375        if let Some(error) = self
376            .write_budget
377            .as_mut()
378            .and_then(|budget| budget.try_consume(count).err())
379        {
380            return Err(FacadeCore::budget_error(
381                error,
382                FsOperation::Write,
383                self.info.path(),
384                &self.provider,
385                "write session exceeds the provider byte limit",
386            )
387            .into_io_error());
388        }
389        self.written_bytes = self
390            .written_bytes
391            .checked_add(count)
392            .ok_or_else(|| self.byte_count_error())?;
393        Ok(())
394    }
395
396    /// Builds the error used when native byte accounting exceeds the public
397    /// filesystem API's `u64` reporting range.
398    fn byte_count_error(&self) -> IoError {
399        FsError::new(
400            FsErrorKind::ResourceLimitExceeded,
401            FsOperation::Write,
402            "write byte count exceeds the filesystem API reporting range",
403        )
404        .with_path(self.info.path().clone())
405        .with_provider(&self.provider)
406        .into_io_error()
407    }
408
409    /// Adds only missing facade context to a provider lifecycle error.
410    /// # Parameters
411    /// - `error`: Failure whose trusted filesystem context is being restored.
412    /// - `operation`: Filesystem operation associated with the error.
413    fn contextual_error(&self, error: FsError, operation: FsOperation) -> FsError {
414        error
415            .with_operation(operation)
416            .with_missing_context(self.info.path(), None, &self.provider)
417    }
418}
419
420impl Output for FileWriter {
421    /// The byte unit accepted by this writer.
422    type Item = u8;
423
424    /// Reports whether the provider session buffers output before flushing.
425    #[inline]
426    fn is_buffered(&self) -> bool {
427        self.session.is_buffered()
428    }
429
430    /// Writes a range and records provider progress or uncertainty.
431    ///
432    /// # Safety
433    /// `index` and `count` must identify a valid range within `input`.
434    /// # Parameters
435    /// - `input`: Input bytes containing the requested range.
436    /// - `index`: Starting offset of the requested input range.
437    /// - `count`: Maximum number of bytes requested from the provider.
438    unsafe fn write_unchecked(&mut self, input: &[u8], index: usize, count: usize) -> IoResult<usize> {
439        if self.state != WriterState::Open {
440            return Err(self.closed_io_error());
441        }
442        self.check_write_limit(count)?;
443        // SAFETY: The caller guarantees the same range contract required by
444        // the wrapped output session.
445        match unsafe { self.session.write_unchecked(input, index, count) } {
446            Ok(value) => {
447                if value > count {
448                    self.state = WriterState::Indeterminate;
449                    return Err(FsError::new(
450                        FsErrorKind::ProviderContractViolation,
451                        FsOperation::Write,
452                        "provider reported accepting more bytes than requested",
453                    )
454                    .with_effect_state(FsEffectState::Indeterminate)
455                    .with_path(self.info.path().clone())
456                    .with_provider(&self.provider)
457                    .into_io_error());
458                }
459                if let Err(error) = self.record_written_bytes(value) {
460                    self.state = WriterState::Indeterminate;
461                    return Err(error);
462                }
463                if count > 0 && value == 0 && self.written_bytes > 0 {
464                    self.state = WriterState::Indeterminate;
465                }
466                Ok(value)
467            }
468            Err(error) => {
469                if error.kind() == IoErrorKind::Interrupted {
470                    let typed_error = error.get_ref().and_then(|source| source.downcast_ref::<FsError>());
471                    let has_unchanged_fact = typed_error.is_some_and(|typed_error| {
472                        typed_error.kind() == FsErrorKind::Interrupted
473                            && typed_error.effect_state() == Some(FsEffectState::Unchanged)
474                    });
475                    if typed_error.is_none() || has_unchanged_fact {
476                        return Err(error);
477                    }
478                    self.state = WriterState::Indeterminate;
479                    let source = error
480                        .into_inner()
481                        .expect("typed Interrupted error must retain its source");
482                    Err(IoError::other(source))
483                } else {
484                    self.state = WriterState::Indeterminate;
485                    Err(error)
486                }
487            }
488        }
489    }
490
491    /// Flushes the provider session and marks it indeterminate on failure.
492    fn flush(&mut self) -> IoResult<()> {
493        if self.state != WriterState::Open {
494            return Err(self.closed_io_error());
495        }
496        match self.session.flush() {
497            Ok(()) => Ok(()),
498            Err(error) => {
499                self.state = WriterState::Indeterminate;
500                Err(error)
501            }
502        }
503    }
504}
505
506impl Debug for FileWriter {
507    /// Formats lifecycle facts without exposing the provider session.
508    /// # Parameters
509    /// - `formatter`: Formatter receiving the diagnostic representation.
510    #[inline]
511    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
512        formatter
513            .debug_struct("FileWriter")
514            .field("info", &self.info)
515            .field("state", &self.state)
516            .finish_non_exhaustive()
517    }
518}
519
520impl Drop for FileWriter {
521    /// Aborts provider work when this writer still owns a live session.
522    fn drop(&mut self) {
523        if self.cleanup_state != RecoveryCleanupState::Completed
524            && matches!(
525                self.state,
526                WriterState::Open | WriterState::NotPublished | WriterState::Published
527            )
528        {
529            let _ = self.session.abort();
530        }
531    }
532}