qubit-fs 0.3.3

Provider-neutral synchronous and asynchronous filesystem abstraction for Rust
Documentation
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Copy operation outcome.

use crate::copy::CopyConflictPolicy;
use crate::copy::CopyFailureState;
use crate::copy::CopyMethod;
use crate::copy::CopyMode;
use crate::copy::CopyOptions;
use crate::copy::CopyStats;
use crate::copy::MetadataPreservePolicy;
use crate::copy::ServerSidePreference;
use crate::metadata::AchievedAtomicity;
use crate::metadata::NonSensitiveMetadata;
use crate::metadata::ResourceVersion;
use crate::metadata::UserMetadata;

/// Outcome returned by copy operations.
///
/// Facades validate the reported statistics shape before checking requested
/// guarantees. When a guarantee is violated, coherent statistics still
/// determine whether the destination is unchanged, published, or partial.
///
/// # Examples
///
/// ```rust
/// use qubit_fs::copy::{CopyMethod, CopyOutcome, CopyStats};
/// use qubit_fs::metadata::AchievedAtomicity;
///
/// let outcome = CopyOutcome::new(
///     CopyStats { files: 1, ..CopyStats::default() },
///     CopyMethod::Native,
///     AchievedAtomicity::NonAtomic,
/// );
/// assert_eq!(CopyMethod::Native, outcome.method());
/// assert!(!outcome.used_fallback());
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct CopyOutcome {
    /// Aggregate counts and bytes reported for the completed copy.
    stats: CopyStats,
    /// Actual transfer method used by the provider or facade.
    method: CopyMethod,
    /// Atomicity achieved while publishing the destination.
    atomicity: AchievedAtomicity,
    /// Whether requested durability was confirmed.
    durable: bool,
    /// Metadata preservation level actually achieved.
    metadata: MetadataPreservePolicy,
    /// Optional version assigned to the destination.
    target_version: Option<ResourceVersion>,
    /// Whether the facade completed the copy after provider decline.
    used_fallback: bool,
    /// Provider diagnostics whose keys passed sensitivity checks.
    diagnostics: NonSensitiveMetadata,
}

impl CopyOutcome {
    /// Creates a copy outcome.
    ///
    /// # Parameters
    /// - `stats`: Copy statistics.
    /// - `method`: Method used to complete the copy.
    /// - `atomicity`: Atomicity achieved while publishing the destination.
    ///
    /// # Returns
    /// New copy outcome without diagnostics.
    #[inline]
    #[must_use]
    pub fn new(stats: CopyStats, method: CopyMethod, atomicity: AchievedAtomicity) -> Self {
        Self {
            stats,
            method,
            atomicity,
            durable: false,
            metadata: MetadataPreservePolicy::None,
            target_version: None,
            used_fallback: false,
            diagnostics: NonSensitiveMetadata::new(),
        }
    }

    /// Marks this result as the facade's streamed fallback.
    ///
    /// # Parameters
    /// - `stats`: Counts and bytes accumulated by the fallback copy.
    /// - `atomicity`: Atomicity achieved while publishing the destination.
    /// - `durable`: Whether durability synchronization was confirmed.
    ///
    /// # Returns
    /// An outcome marked as fallback with no provider diagnostics or target
    /// version.
    #[must_use]
    pub(crate) fn streamed_fallback(stats: CopyStats, atomicity: AchievedAtomicity, durable: bool) -> Self {
        Self {
            stats,
            method: CopyMethod::Streamed,
            atomicity,
            durable,
            metadata: MetadataPreservePolicy::None,
            target_version: None,
            used_fallback: true,
            diagnostics: NonSensitiveMetadata::new(),
        }
    }

    /// Returns the completed copy statistics.
    ///
    /// # Returns
    /// A borrow of the aggregate counts and bytes reported by the operation.
    #[inline]
    #[must_use]
    pub const fn stats(&self) -> &CopyStats {
        &self.stats
    }

    /// Returns the actual method used by the completed operation.
    ///
    /// # Returns
    /// The method the provider or facade used to transfer the resources.
    #[inline]
    #[must_use]
    pub const fn method(&self) -> CopyMethod {
        self.method
    }

    /// Returns the atomicity actually achieved while publishing the target.
    ///
    /// # Returns
    /// The achieved atomicity, which may be weaker than the requested level.
    #[inline]
    #[must_use]
    pub const fn atomicity(&self) -> AchievedAtomicity {
        self.atomicity
    }

    /// Returns whether provider-confirmed durability synchronization completed.
    ///
    /// # Returns
    /// `true` only when the provider confirmed the requested synchronization.
    #[inline]
    #[must_use]
    pub const fn durable(&self) -> bool {
        self.durable
    }

    /// Returns the metadata preservation category the provider reports as
    /// achieved.
    ///
    /// This is the provider's completion declaration under the documented
    /// policy; the facade checks that the reported category matches the
    /// request, but does not read the destination to verify individual fields.
    ///
    /// # Returns
    /// The metadata preservation policy the provider reports as achieved.
    #[inline]
    #[must_use]
    pub const fn metadata(&self) -> MetadataPreservePolicy {
        self.metadata
    }

    /// Returns the target version reported by the provider or fallback writer.
    ///
    /// # Returns
    /// `Some` with the destination version when reported, or `None` otherwise.
    #[inline]
    pub const fn target_version(&self) -> Option<&ResourceVersion> {
        self.target_version.as_ref()
    }

    /// Returns whether the facade streamed after the provider declined its fast
    /// path.
    ///
    /// # Returns
    /// `true` when the facade completed this operation using streamed fallback.
    #[inline]
    #[must_use]
    pub const fn used_fallback(&self) -> bool {
        self.used_fallback
    }

    /// Returns provider diagnostics whose keys passed sensitivity checks.
    ///
    /// Values are retained unchanged. Providers must sanitize diagnostic
    /// values before storing them; explicitly reading a value does not make it
    /// safe to log.
    ///
    /// # Returns
    /// A borrow of diagnostics whose keys passed sensitivity checks.
    #[inline]
    #[must_use]
    pub const fn diagnostics(&self) -> &NonSensitiveMetadata {
        &self.diagnostics
    }

    /// Replaces provider diagnostics whose keys are checked when added.
    ///
    /// Values are stored unchanged. Providers must sanitize diagnostic values
    /// before storing them.
    ///
    /// # Parameters
    /// - `diagnostics`: Provider metadata to add after sanitizing its values.
    ///
    /// # Returns
    /// This outcome with diagnostics whose keys passed sensitivity checks.
    #[inline]
    #[must_use]
    pub fn with_diagnostics(mut self, diagnostics: UserMetadata) -> Self {
        self.diagnostics = NonSensitiveMetadata::from(diagnostics);
        self
    }

    /// Replaces the provider-reported durability completion fact.
    ///
    /// # Parameters
    /// - `durable`: Whether the provider confirmed durability synchronization.
    ///
    /// # Returns
    /// This outcome with the provider's durability fact recorded.
    #[inline]
    #[must_use]
    pub fn with_durable(mut self, durable: bool) -> Self {
        self.durable = durable;
        self
    }

    /// Records the metadata preservation policy the provider declares as
    /// achieved.
    ///
    /// The facade checks this category against the request. It does not verify
    /// individual destination fields, so provider documentation defines the
    /// fields covered by this declaration.
    ///
    /// # Parameters
    /// - `metadata`: The preservation policy the provider reports as achieved.
    ///
    /// # Returns
    /// This outcome with the provider-reported metadata policy recorded.
    #[inline]
    #[must_use]
    pub fn with_metadata(mut self, metadata: MetadataPreservePolicy) -> Self {
        self.metadata = metadata;
        self
    }

    /// Records the destination version reported after publication.
    ///
    /// # Parameters
    /// - `target_version`: Version reported for the published destination.
    ///
    /// # Returns
    /// This outcome with the destination version recorded.
    #[inline]
    #[must_use]
    pub fn with_target_version(mut self, target_version: ResourceVersion) -> Self {
        self.target_version = Some(target_version);
        self
    }

    /// Returns the first provider-completed outcome fact that contradicts the
    /// resolved copy request.
    ///
    /// # Parameters
    /// - `options`: The resolved request whose constraints the outcome must
    ///   meet.
    ///
    /// # Returns
    /// The first violated contract, or `None` when all checked constraints
    /// hold.
    pub(crate) fn contract_violation(&self, options: &CopyOptions) -> Option<&'static str> {
        if self.statistics_shape_violation(options.mode()).is_some() {
            return Some("provider reported structurally inconsistent copy statistics");
        }
        if self.used_fallback || self.method == CopyMethod::Streamed {
            return Some("provider returned a facade streamed-fallback outcome as native success");
        }
        if options.atomicity() == crate::metadata::AtomicityRequirement::Required
            && self.atomicity != AchievedAtomicity::Atomic
        {
            return Some("provider reported non-atomic success for an atomic-required copy");
        }
        if options.durability() == crate::metadata::DurabilityRequirement::Required && !self.durable {
            return Some("provider reported non-durable success for a durability-required copy");
        }
        if options.server_side() == ServerSidePreference::Require && self.method != CopyMethod::ServerSide {
            return Some("provider reported a non-server-side success for a server-side-required copy");
        }
        if options.server_side() == ServerSidePreference::Disable && self.method == CopyMethod::ServerSide {
            return Some("provider reported a server-side success for a server-side-disabled copy");
        }
        if self.metadata != options.preserve_metadata() {
            return Some("provider reported metadata preservation different from the copy request");
        }
        if !options.continue_on_error() && self.stats.failed != 0 {
            return Some("provider reported failed copy entries without continue-on-error");
        }
        if options.conflict() != CopyConflictPolicy::Skip && self.stats.skipped != 0 {
            return Some("provider reported skipped copy entries without a skip conflict policy");
        }
        if options.conflict() != CopyConflictPolicy::Overwrite && self.stats.overwritten != 0 {
            return Some("provider reported overwritten copy entries without an overwrite conflict policy");
        }
        if options.max_bytes().is_some_and(|maximum| self.stats.bytes > maximum) {
            return Some("provider reported copy bytes beyond the requested limit");
        }
        let Some(entries) = self.entry_count() else {
            return Some("provider reported copy entries beyond the requested limit");
        };
        if options
            .max_entries()
            .and_then(|maximum| u64::try_from(maximum).ok())
            .is_some_and(|maximum| {
                entries > maximum
                    || self.stats.skipped > maximum
                    || entries
                        .checked_add(self.stats.skipped)
                        .is_none_or(|processed_lower_bound| processed_lower_bound > maximum)
                    || self.stats.failed > maximum
            })
        {
            return Some("provider reported copy entries beyond the requested limit");
        }
        None
    }

    /// Infers destination publication facts for a rejected completed outcome.
    ///
    /// Statistics must form a coherent shape for the requested mode before
    /// they can establish publication. A request guarantee violation alone
    /// does not invalidate otherwise coherent statistics.
    ///
    /// # Parameters
    ///
    /// - `options`: Copy route, conflict, consistency, and metadata guarantees
    ///   requested by the caller.
    pub(crate) fn violation_failure_state(&self, options: &CopyOptions) -> CopyFailureState {
        if self.statistics_shape_violation(options.mode()).is_some() {
            return CopyFailureState::Indeterminate;
        }
        crate::copy::internal::from_completed_stats(&self.stats)
    }

    /// Returns the checked total of completed file and directory entries.
    ///
    /// Returns `None` if the provider-reported counters overflow.
    fn entry_count(&self) -> Option<u64> {
        // These counters describe completed resources; skipped and failed
        // entries are separate outcomes and cannot justify an overwrite.
        self.stats
            .files
            .checked_add(self.stats.directories)
            .and_then(|value| value.checked_add(self.stats.symlinks))
            .and_then(|value| value.checked_add(self.stats.objects))
            .and_then(|value| value.checked_add(self.stats.prefixes))
    }

    /// Checks whether the reported statistics match the requested copy mode.
    ///
    /// Returns a diagnostic when counters are inconsistent or overflow.
    ///
    /// # Parameters
    ///
    /// - `mode`: Copy mode whose counter requirements are checked.
    fn statistics_shape_violation(&self, mode: CopyMode) -> Option<&'static str> {
        let Some(entries) = self.entry_count() else {
            return Some("provider reported copy entry counters that overflow");
        };
        if self.stats.overwritten > entries {
            return Some("provider reported more overwritten entries than completed resources");
        }
        if entries == 0 && self.stats.failed == 0 && self.stats.bytes != 0 {
            return Some("provider reported copied bytes without completed or failed resources");
        }
        if mode != CopyMode::File {
            return None;
        }
        let valid_skipped_file = self.stats.skipped == 1
            && entries == 0
            && self.stats.bytes == 0
            && self.stats.overwritten == 0
            && self.stats.failed == 0;
        let valid_copied_file = entries == 1
            && self.stats.directories == 0
            && self.stats.prefixes == 0
            && self.stats.skipped == 0
            && self.stats.failed == 0;
        if valid_copied_file || valid_skipped_file {
            None
        } else {
            Some("provider reported a file-mode copy without exactly one resource")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::CopyOutcome;
    use crate::copy::CopyFailureState;
    use crate::copy::CopyMethod;
    use crate::copy::CopyOptions;
    use crate::copy::CopyStats;
    use crate::metadata::AchievedAtomicity;
    use crate::metadata::AtomicityRequirement;

    #[test]
    fn test_contract_violation_rejects_exceeded_copy_limits() {
        let bytes_exceeded = CopyOutcome::new(
            CopyStats {
                bytes: 11,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::Atomic,
        );
        assert!(
            bytes_exceeded
                .contract_violation(&CopyOptions::default().with_max_bytes(Some(10)))
                .is_some()
        );

        let entries_exceeded = CopyOutcome::new(
            CopyStats {
                files: 2,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::Atomic,
        );
        assert!(
            entries_exceeded
                .contract_violation(&CopyOptions::tree().with_max_entries(Some(1)))
                .is_some()
        );
    }

    #[test]
    fn test_violation_failure_state_uses_coherent_statistics() {
        let skipped = CopyOutcome::new(
            CopyStats {
                skipped: 1,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::NonAtomic,
        );
        let file_skip = CopyOptions::file()
            .with_conflict(crate::copy::CopyConflictPolicy::Skip)
            .with_atomicity(AtomicityRequirement::Required);
        assert_eq!(
            Some("provider reported non-atomic success for an atomic-required copy"),
            skipped.contract_violation(&file_skip)
        );
        assert_eq!(CopyFailureState::Unchanged, skipped.violation_failure_state(&file_skip));

        let copied_empty_file = CopyOutcome::new(
            CopyStats {
                files: 1,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::NonAtomic,
        );
        assert_eq!(
            CopyFailureState::Published,
            copied_empty_file.violation_failure_state(&file_skip)
        );

        let failed_only = CopyOutcome::new(
            CopyStats {
                failed: 1,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::Atomic,
        );
        assert_eq!(
            CopyFailureState::Indeterminate,
            failed_only.violation_failure_state(&CopyOptions::default())
        );

        let partial_tree = CopyOutcome::new(
            CopyStats {
                files: 1,
                failed: 1,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::NonAtomic,
        );
        assert_eq!(
            CopyFailureState::PartiallyPublished,
            partial_tree.violation_failure_state(&CopyOptions::tree().with_atomicity(AtomicityRequirement::Required)),
        );

        let inconsistent = CopyOutcome::new(
            CopyStats {
                files: 1,
                skipped: 1,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::Atomic,
        );
        assert_eq!(
            CopyFailureState::Indeterminate,
            inconsistent
                .violation_failure_state(&CopyOptions::file().with_conflict(crate::copy::CopyConflictPolicy::Skip)),
        );

        let too_many_overwrites = CopyOutcome::new(
            CopyStats {
                files: 1,
                overwritten: 2,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::Atomic,
        );
        assert!(too_many_overwrites.contract_violation(&CopyOptions::file()).is_some());
        assert_eq!(
            CopyFailureState::Indeterminate,
            too_many_overwrites.violation_failure_state(&CopyOptions::file())
        );

        let overflow = CopyOutcome::new(
            CopyStats {
                files: u64::MAX,
                objects: 1,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            AchievedAtomicity::Atomic,
        );
        assert_eq!(
            CopyFailureState::Indeterminate,
            overflow.violation_failure_state(&CopyOptions::default())
        );
    }

    #[test]
    fn test_all_modes_reject_overwritten_counts_above_completed_entries() {
        let outcome = CopyOutcome::new(
            CopyStats {
                files: 1,
                overwritten: 2,
                ..CopyStats::default()
            },
            CopyMethod::Native,
            crate::metadata::AchievedAtomicity::Atomic,
        );

        for options in [CopyOptions::default(), CopyOptions::tree()] {
            assert!(outcome.contract_violation(&options).is_some());
            assert_eq!(
                CopyFailureState::Indeterminate,
                outcome.violation_failure_state(&options)
            );
        }
    }
}