Skip to main content

coven_sync/
pending.rs

1//! Current unmet conditions shared by calls, persistence and the application query.
2
3use super::pending_encoding as encoding;
4use crate::{OperationId, OperationKind, Refusal};
5use coven_database::PendingValue;
6use coven_format::{admin::SnapshotId, path::ObjectPath};
7use coven_foundation::id_source::{DeviceId, FileId, KeyId, MemberId, ObjectId};
8use coven_merge::{Audience, Slot, WriteId};
9use coven_storage::{CloudProvider, RetainedAccess, StorageFailure};
10use serde::{Deserialize, Serialize};
11
12pub use coven_format::RequiredUpdate;
13
14/// The staging device cannot supply the file's original bytes.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
16pub enum FileSourceFailure {
17    /// The original file is absent.
18    Missing,
19    /// The original changed after it was staged.
20    Changed,
21    /// The original fails its retained content checks.
22    Integrity,
23}
24
25/// A member of the store that holds a key a stopped device waits for: a copy
26/// of the key is sealed to the member's current sealing key, so every device of
27/// the member with that pair opens it, and a device of the member that reads the
28/// key's audience sends the copy on its next pass (§12.1).
29#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
30pub struct KeyHolder {
31    /// The member.
32    pub member: MemberId,
33    /// The member reads the key's audience now, so its devices send the copy;
34    /// otherwise it holds the key from before it left the audience, and a
35    /// member of the audience has to add it back first.
36    pub reads_audience: bool,
37    /// The member's active devices, as the applied history names them.
38    pub devices: Vec<HolderDevice>,
39}
40
41/// An active device of a `KeyHolder`.
42#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
43pub struct HolderDevice {
44    /// The device.
45    pub id: DeviceId,
46    /// The name it was added under.
47    pub name: String,
48}
49
50/// One local first unmet condition, identified by its subject (§19.1, E5).
51#[derive(Clone, Debug, Serialize, Deserialize)]
52pub struct PendingRecord {
53    /// The work that cannot advance.
54    pub subject: PendingSubject,
55    /// The first condition in its processing order.
56    pub reason: PendingReason,
57    /// The text of the error behind `reason`: the provider, disk or
58    /// database failure, naming every cause below it. `coven_pending.cause`
59    /// keeps it beside the record, written in the same step. Only the run
60    /// that met the error writes one: opening clears every cause, and a
61    /// record whose last failure went back to an app call has none. It
62    /// names the failure and is no part of the record's identity: equality
63    /// ignores it, and `record` leaves it out.
64    #[serde(skip)]
65    pub cause: Option<String>,
66}
67
68impl PartialEq for PendingRecord {
69    fn eq(&self, other: &Self) -> bool {
70        self.subject == other.subject && self.reason == other.reason
71    }
72}
73impl Eq for PendingRecord {}
74
75/// The subject and its reason, then the error behind it when the record
76/// keeps one, such as `Operation { .. }: Storage { .. }: S3: Network: …`.
77impl std::fmt::Display for PendingRecord {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        write!(f, "{:?}: {:?}", self.subject, self.reason)?;
80        match &self.cause {
81            Some(cause) => write!(f, ": {cause}"),
82            None => Ok(()),
83        }
84    }
85}
86
87/// Stable identities of work, independent of attempts and wall-clock time.
88#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
89pub enum PendingSubject {
90    /// A numbered write.
91    Write(#[serde(with = "encoding::write")] WriteId),
92    /// A position in the store sequence.
93    Slot(#[serde(with = "coven_database::slot_json")] Slot),
94    /// A sealed key addressed to a member.
95    KeyCopy {
96        /// The key's audience.
97        #[serde(with = "crate::pending_encoding::audience")]
98        audience: Audience,
99        /// The key identity.
100        key: KeyId,
101        /// The recipient.
102        member: MemberId,
103        /// The recipient's exact sealing credential (D9, Key copies).
104        #[serde(with = "encoding::sealing")]
105        sealing: coven_crypto::SealingKey,
106    },
107    /// A numbered snapshot.
108    Snapshot(#[serde(with = "crate::pending_encoding::snapshot_id")] SnapshotId),
109    /// This device's upload of a stored object, and its reads of its staged
110    /// original while the upload waits.
111    Upload {
112        /// This device, which uploads it.
113        device: DeviceId,
114        /// The stored object's id.
115        object: ObjectId,
116    },
117    /// This device's downloads of a stored object, for an app's pins: a
118    /// read's failure goes to its caller and leaves no record (§17.7).
119    Download {
120        /// The device that uploaded it.
121        device: DeviceId,
122        /// The stored object's id.
123        object: ObjectId,
124    },
125    /// A file a switch to the cloud asked this device to keep whole, which
126    /// coven downloads itself: its pin is work coven drives, not an app
127    /// call's (§17.8).
128    Keep {
129        /// The file.
130        file: FileId,
131    },
132    /// A move of this device's files to the cloud: the files one write
133    /// staged for the cloud, or the files the app moved (§17.3).
134    Move {
135        /// The move's identity on this device.
136        id: coven_database::MoveId,
137    },
138    /// An unfinished journal row.
139    Operation {
140        /// The never reused local identity.
141        id: OperationId,
142        /// The work's purpose.
143        kind: OperationKind,
144    },
145    /// A physical object waiting for safe deletion.
146    Retention {
147        /// The storage path.
148        path: ObjectPath,
149    },
150    /// An audience that requires dependent work.
151    Audience(#[serde(with = "crate::pending_encoding::audience")] Audience),
152    /// The local storage connection.
153    Connection,
154}
155
156/// A fact required before processing can continue.
157#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
158pub enum Prerequisite {
159    /// A completed read and apply through the current sequence end, which a
160    /// file read or a member-key replacement waits for. A slot never blocks
161    /// on it.
162    SequenceCatchUp,
163    /// This audience must reload: a slot holds a raise or reset of it, and no
164    /// snapshot announced after it is named yet.
165    Reload(#[serde(with = "crate::pending_encoding::audience")] Audience),
166    /// A slot's reload met a newer floor, which retention moved past the slots
167    /// it needed; the next pass retries it from the new floor.
168    Floor,
169}
170
171/// A local invariant or resource failure; immediate calls retain the native cause.
172#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
173pub enum LocalFailure {
174    /// Database state or persistence failed.
175    Database,
176    /// Local file access failed because the disk is full or its quota is
177    /// spent.
178    DiskFull,
179    /// Local file access failed because the operating system refused this
180    /// process the file or folder, or the volume is read-only.
181    DiskDenied,
182    /// Local file access failed for a reason that is neither: the file is
183    /// gone, the device failed, or the cause names no operating system
184    /// error.
185    DiskOther,
186    /// Key custody failed.
187    KeyCustody,
188    /// Cryptographic work failed.
189    Crypto,
190    /// Operation state failed.
191    Operation,
192    /// The work's runtime is shutting down and dropped it: the process is
193    /// ending, and the next one runs the work again (E15).
194    Shutdown,
195    /// Coven's own code broke its rule or panicked: a bug. The work retries
196    /// under backoff, as a database failure does, and fails again until the
197    /// bug is fixed (E15).
198    Bug,
199}
200
201impl LocalFailure {
202    /// The disk failure `error` is, read from the operating system error
203    /// first in its chain of causes: a full disk or spent quota, a refusal
204    /// of access or a read-only volume, or anything else.
205    pub(crate) fn of_disk(error: &(dyn std::error::Error + 'static)) -> Self {
206        let mut current = Some(error);
207        while let Some(cause) = current {
208            if let Some(os) = cause.downcast_ref::<std::io::Error>() {
209                return match os.kind() {
210                    std::io::ErrorKind::StorageFull | std::io::ErrorKind::QuotaExceeded => {
211                        Self::DiskFull
212                    }
213                    std::io::ErrorKind::PermissionDenied
214                    | std::io::ErrorKind::ReadOnlyFilesystem => Self::DiskDenied,
215                    _ => Self::DiskOther,
216                };
217            }
218            current = cause.source();
219        }
220        Self::DiskOther
221    }
222}
223
224/// The provider's intended sharing change.
225#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
226pub enum ProviderAccessAction {
227    /// Share the location.
228    Grant,
229    /// Take sharing back.
230    Revoke,
231}
232
233/// Why a file can't be read (§17.6).
234#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
235pub enum FileMissingReason {
236    /// Storage confirms nothing at the path a file's record names: the
237    /// provider lost it. Nothing brings it back on its own; the app can stage
238    /// it again.
239    Lost,
240    /// A file this device uploads, on it only until then, whose source
241    /// failed: its original is missing, or coven's copy fails its check; its
242    /// upload retries (§17.3, §17.9). A changed original fails its move.
243    Source(FileSourceFailure),
244}
245
246/// A typed current condition, never an error's display string.
247#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
248pub enum PendingReason {
249    /// The named object has not arrived.
250    Missing {
251        /// The storage path.
252        path: ObjectPath,
253    },
254    /// An earlier prerequisite remains unmet.
255    Waits(Prerequisite),
256    /// No usable copy of a required key has arrived.
257    KeyUnavailable {
258        /// The key's audience.
259        #[serde(with = "crate::pending_encoding::audience")]
260        audience: Audience,
261        /// The missing key.
262        key: KeyId,
263        /// The members that hold the key, as the history this device applied
264        /// names them, when the record was made with that history at hand: a
265        /// stuck slot's, and the first queued write's. `Some` and empty means
266        /// no member can ever send a copy (§12.1), which only Failed says.
267        /// `None` is a record made without the history (the start of a
268        /// connection, an operation's failure): it names no state.
269        holders: Option<Vec<KeyHolder>>,
270    },
271    /// Processing requires a supported schema or format.
272    UpdateRequired(RequiredUpdate),
273    /// No storage is connected.
274    NoStorage,
275    /// A classified provider failure.
276    Storage {
277        /// The provider.
278        provider: CloudProvider,
279        /// The classification, without a process-local cause.
280        failure: StorageFailure,
281        /// Whether the provider answered the failed request, even with an
282        /// error. `Network` alone cannot say: a server's error response is
283        /// an answer, a lookup or connection failure is not (E5).
284        answered: bool,
285    },
286    /// Complete immutable bytes failed a check.
287    Refused(Refusal),
288    /// Writes consumed after a permanent lower-slot cut-off.
289    WritesRefused {
290        /// The removal or replacement slot.
291        #[serde(with = "coven_database::slot_json")]
292        cutoff: Slot,
293        /// The event that excluded the original author.
294        cause: coven_database::WriteCutoff,
295    },
296    /// A provider has accepted work that is still waiting.
297    ProviderPending {
298        /// The intended change.
299        action: ProviderAccessAction,
300        /// The provider account.
301        account: String,
302    },
303    /// Another member or invite still needs this account.
304    AccountInUse {
305        /// The shared account.
306        account: String,
307    },
308    /// Revocation retained grants requiring owner action.
309    AccessRemains {
310        /// The account whose access remains.
311        account: String,
312        /// The retained grants.
313        shares: Vec<RetainedAccess>,
314    },
315    /// The uploading device cannot supply this file.
316    FileUnavailable(FileMissingReason),
317    /// A user's original a move uploads is missing, and the move waits for
318    /// it, or changed, and the move failed (§17.3).
319    Original {
320        /// The original's recorded path.
321        #[serde(with = "crate::pending_encoding::path")]
322        path: std::path::PathBuf,
323        /// Missing or changed.
324        failure: FileSourceFailure,
325    },
326    /// A local failure prevented progress.
327    Failed(LocalFailure),
328    /// The action was refused; an enclosing cleanup may still be owed (§11.3).
329    Rejected(crate::OperationRejection),
330    /// Both the initiating failure and the failure preventing undo (§11.3).
331    Cleanup {
332        /// The failure that made cleanup necessary.
333        operation: Box<PendingReason>,
334        /// The current condition preventing cleanup.
335        cleanup: Box<PendingReason>,
336    },
337    /// Work awaits the app’s next action, such as approval or resuming a transfer.
338    Paused,
339    /// This installation is not in the store (§13.2, §14.1).
340    Removed(coven_database::Removal),
341    /// Sending needs this stable member's current credentials, which this
342    /// installation does not hold (§14.1).
343    MemberKeysReplaced {
344        /// The member whose held keys were replaced.
345        member: MemberId,
346    },
347}
348
349/// What can permit another attempt; no attempt count determines it.
350#[derive(Clone, Copy, Debug, PartialEq, Eq)]
351pub enum Retry {
352    /// Retry when the prerequisite or retry deadline changes.
353    Automatic,
354    /// Retry only under software that may decide otherwise: a refusal under
355    /// another build of coven, a required update once it is installed.
356    AfterUpdate,
357    /// A person must act.
358    AppAction,
359    /// A permanent cut-off or removal never retries.
360    Never,
361}
362impl PendingRecord {
363    /// The record of `subject`'s first unmet condition, with no cause.
364    pub fn new(subject: PendingSubject, reason: PendingReason) -> Self {
365        Self { subject, reason, cause: None }
366    }
367
368    /// Retry according to the cause and the owner of the unfinished work.
369    pub fn retry(&self) -> Retry {
370        match (&self.subject, self.reason.retry_cause()) {
371            (
372                PendingSubject::Upload { .. },
373                PendingReason::FileUnavailable(FileMissingReason::Source(_)),
374            ) => Retry::Automatic,
375            // Only a pin's failed download is recorded, and its call
376            // returns the failure: the app's next pin or read tries again,
377            // and nothing else does.
378            (PendingSubject::Download { .. }, reason) => match reason.clears() {
379                Some(Clears::Never) => Retry::Never,
380                Some(Clears::ByItself | Clears::ByPerson) => Retry::AppAction,
381                None => match reason.retry() {
382                    Retry::Automatic => Retry::AppAction,
383                    retry => retry,
384                },
385            },
386            (subject, reason)
387                if matches!(
388                    subject,
389                    PendingSubject::Upload { .. } | PendingSubject::Keep { .. }
390                ) || matches!(subject, PendingSubject::Operation { kind, .. } if kind.coven_owned()) =>
391            {
392                match reason.clears() {
393                    Some(Clears::ByItself) => Retry::Automatic,
394                    Some(Clears::ByPerson) => Retry::AppAction,
395                    Some(Clears::Never) => Retry::Never,
396                    None => reason.retry(),
397                }
398            }
399            // An operation the app started returned this failure to the
400            // app's call, and the app calls again. Nobody calls again for
401            // work coven drives itself, such as the pass: a local failure
402            // that clears by itself retries under the shared backoff.
403            (subject, reason @ PendingReason::Failed(_))
404                if !matches!(subject, PendingSubject::Operation { .. })
405                    && reason.clears() == Some(Clears::ByItself) =>
406            {
407                Retry::Automatic
408            }
409            (_, reason) => reason.retry(),
410        }
411    }
412}
413
414/// How a failure clears (E5). Every failure is classified here, once.
415#[derive(Clone, Copy, Debug, PartialEq, Eq)]
416pub(crate) enum Clears {
417    /// It can clear on its own: retry under the shared backoff.
418    ByItself,
419    /// Only a person's action clears it, such as signing in again.
420    ByPerson,
421    /// Nothing clears it: the provider or this installation refuses outright.
422    Never,
423}
424
425/// A failure that received no usable provider response: the device is
426/// offline (E5), and only a change in its network can end the wait early
427/// (§6.7). A server's error response is an answer, so it is not offline.
428pub(crate) fn offline(failure: StorageFailure, answered: bool) -> bool {
429    failure == StorageFailure::Network && !answered
430}
431
432/// Storage failures that subjects other than files and coven's own
433/// operations retry automatically (E5).
434pub(crate) fn automatic_storage(failure: StorageFailure) -> bool {
435    matches!(
436        failure,
437        StorageFailure::Network
438            | StorageFailure::Corrupted
439            | StorageFailure::Conflict
440            | StorageFailure::RateLimited
441            | StorageFailure::NotFound
442            | StorageFailure::SessionExpired
443    )
444}
445
446/// How a provider failure clears. Every variant is matched by name, so a
447/// new one is classified here.
448#[deny(clippy::wildcard_enum_match_arm)]
449pub(crate) fn storage_clears(failure: StorageFailure) -> Clears {
450    use StorageFailure::*;
451    match failure {
452        Network | Corrupted | Conflict | RateLimited | NotFound | SessionExpired
453        | CatchUpRequired | QuotaExceeded | File | Bug => Clears::ByItself,
454        Authentication
455        | PermissionDenied
456        | AccessNotRegistered { .. }
457        | AccessNotGranted { .. }
458        | ContainerNotFound
459        | RegionMismatch
460        | ClockSkew
461        | InvalidConfiguration
462        | NotStoreOwner
463        | AccountIdUnavailable
464        | SharingRefused(_)
465        | ProviderUnavailable
466        | MemberKeysMissing => Clears::ByPerson,
467        DropboxAppFolderNotShareable
468        | AlreadyExists
469        | StoreExists
470        | OwnLocationRequired
471        | Refused
472        | Protocol
473        | InvalidPath
474        | InvalidRange
475        | InviteeIsStoreOwner
476        | InvitationMismatch
477        | SessionMismatch
478        | InvalidPart
479        | SingleRequestTooLarge { .. }
480        | CopyTooLarge { .. }
481        | Encoding => Clears::Never,
482    }
483}
484
485impl PendingReason {
486    /// Cleanup retries its own unmet condition, retaining the initiating cause.
487    pub(crate) fn retry_cause(&self) -> &Self {
488        match self {
489            Self::Cleanup { cleanup, .. } => cleanup.retry_cause(),
490            reason => reason,
491        }
492    }
493
494    /// How the failure this reason reports clears; `None` for a wait or a
495    /// verdict, which are not failures.
496    #[deny(clippy::wildcard_enum_match_arm)]
497    pub(crate) fn clears(&self) -> Option<Clears> {
498        match self.retry_cause() {
499            Self::Failed(
500                LocalFailure::Database
501                | LocalFailure::DiskFull
502                | LocalFailure::DiskDenied
503                | LocalFailure::DiskOther
504                | LocalFailure::KeyCustody
505                | LocalFailure::Shutdown
506                | LocalFailure::Bug,
507            ) => Some(Clears::ByItself),
508            Self::Failed(LocalFailure::Crypto | LocalFailure::Operation) => Some(Clears::Never),
509            Self::Storage { failure, .. } => Some(storage_clears(*failure)),
510            Self::Missing { .. }
511            | Self::Waits(_)
512            | Self::KeyUnavailable { .. }
513            | Self::UpdateRequired(_)
514            | Self::NoStorage
515            | Self::Refused(_)
516            | Self::WritesRefused { .. }
517            | Self::ProviderPending { .. }
518            | Self::AccountInUse { .. }
519            | Self::AccessRemains { .. }
520            | Self::FileUnavailable(_)
521            | Self::Original { .. }
522            | Self::Rejected(_)
523            | Self::Cleanup { .. }
524            | Self::Paused
525            | Self::Removed(_)
526            | Self::MemberKeysReplaced { .. } => None,
527        }
528    }
529
530    /// Whether this reason waits for a condition to change, as opposed to
531    /// reporting a failure or a verdict. A wait is ordinary progress, and
532    /// is logged at debug where a failure is logged at warn.
533    pub(crate) fn waits(&self) -> bool {
534        match self {
535            Self::Missing { .. }
536            | Self::Waits(_)
537            | Self::KeyUnavailable { .. }
538            | Self::NoStorage
539            | Self::ProviderPending { .. }
540            | Self::AccountInUse { .. }
541            | Self::Paused => true,
542            Self::Original { failure, .. } => *failure == FileSourceFailure::Missing,
543            Self::UpdateRequired(_)
544            | Self::Storage { .. }
545            | Self::Refused(_)
546            | Self::WritesRefused { .. }
547            | Self::AccessRemains { .. }
548            | Self::FileUnavailable(_)
549            | Self::Failed(_)
550            | Self::Rejected(_)
551            | Self::Removed(_)
552            | Self::MemberKeysReplaced { .. } => false,
553            Self::Cleanup { operation, cleanup } => operation.waits() && cleanup.waits(),
554        }
555    }
556
557    /// Whether this reason records an attempt that received no usable
558    /// provider response, which the connection reports as `Offline` (E5).
559    pub(crate) fn offline(&self) -> bool {
560        matches!(self, Self::Storage { failure, answered, .. } if offline(*failure, *answered))
561    }
562
563    #[deny(clippy::wildcard_enum_match_arm)]
564    fn retry(&self) -> Retry {
565        match self {
566            Self::Missing { .. }
567            | Self::Waits(_)
568            | Self::KeyUnavailable { .. }
569            | Self::ProviderPending { .. }
570            | Self::AccountInUse { .. } => Retry::Automatic,
571            // A missing original's move retries as its upload does, until
572            // the original is back; a changed one failed the move, which
573            // stays recorded until the app cancels it (§17.3).
574            Self::Original { failure: FileSourceFailure::Missing, .. } => Retry::Automatic,
575            Self::Original {
576                failure: FileSourceFailure::Changed | FileSourceFailure::Integrity,
577                ..
578            } => Retry::AppAction,
579            Self::Storage { failure, .. } if automatic_storage(*failure) => Retry::Automatic,
580            Self::Refused(_) | Self::UpdateRequired(_) => Retry::AfterUpdate,
581            Self::Rejected(_)
582            | Self::WritesRefused { .. }
583            | Self::Removed(_)
584            | Self::MemberKeysReplaced { .. } => Retry::Never,
585            Self::NoStorage
586            | Self::Storage { .. }
587            | Self::AccessRemains { .. }
588            | Self::FileUnavailable(_)
589            | Self::Failed(_)
590            | Self::Cleanup { .. }
591            | Self::Paused => Retry::AppAction,
592        }
593    }
594}
595
596/// A record as coven's `coven_uploads` view and `coven_pending` table hold it
597/// (api.md E4), without its cause: `coven_pending.cause` holds that.
598impl coven_database::types::FromSql for PendingRecord {
599    fn column_result(
600        value: coven_database::types::ValueRef<'_>,
601    ) -> coven_database::types::FromSqlResult<Self> {
602        serde_json::from_slice(value.as_blob()?)
603            .map_err(|error| coven_database::types::FromSqlError::Other(Box::new(error)))
604    }
605}
606
607impl PendingValue for PendingRecord {
608    fn provider_access(id: OperationId, account: String, grant: bool) -> Self {
609        Self::new(
610            PendingSubject::Operation { id, kind: OperationKind::RevokeAccess },
611            PendingReason::ProviderPending {
612                action: if grant {
613                    ProviderAccessAction::Grant
614                } else {
615                    ProviderAccessAction::Revoke
616                },
617                account,
618            },
619        )
620    }
621    fn reload(audience: Audience) -> Self {
622        Self::new(
623            PendingSubject::Audience(audience.clone()),
624            PendingReason::Waits(Prerequisite::Reload(audience)),
625        )
626    }
627    fn writes_refused(slot: Slot, cutoff: Slot, cause: coven_database::WriteCutoff) -> Self {
628        Self::new(PendingSubject::Slot(slot), PendingReason::WritesRefused { cutoff, cause })
629    }
630    type Subject = PendingSubject;
631    fn subject(&self) -> &PendingSubject {
632        &self.subject
633    }
634    fn operation(&self) -> Option<OperationId> {
635        match self.subject {
636            PendingSubject::Operation { id, .. } => Some(id),
637            _ => None,
638        }
639    }
640    fn move_of(&self) -> Option<coven_database::MoveId> {
641        match self.subject {
642            PendingSubject::Move { id } => Some(id),
643            _ => None,
644        }
645    }
646    fn pin_of(&self) -> Option<FileId> {
647        match self.subject {
648            PendingSubject::Keep { file } => Some(file),
649            _ => None,
650        }
651    }
652    fn object(&self) -> Option<(coven_database::FileWork, DeviceId, ObjectId)> {
653        match self.subject {
654            PendingSubject::Upload { device, object } => {
655                Some((coven_database::FileWork::Upload, device, object))
656            }
657            PendingSubject::Download { device, object } => {
658                Some((coven_database::FileWork::Download, device, object))
659            }
660            _ => None,
661        }
662    }
663    fn slot(&self) -> Option<Slot> {
664        match self.subject {
665            PendingSubject::Slot(slot) => Some(slot),
666            _ => None,
667        }
668    }
669    fn ends_when_covered(&self) -> bool {
670        !matches!(
671            self.reason.retry_cause(),
672            PendingReason::Refused(_) | PendingReason::WritesRefused { .. }
673        )
674    }
675    /// Drawn at random each time this crate compiles. Every refusal is made
676    /// here, from checks in this crate and in the crates it depends on, so a
677    /// change to any of that code, or to a dependency, compiles this crate
678    /// again and draws another. A version number would not do: development
679    /// never moves it, so a refusal a since-fixed bug made would never be
680    /// rechecked.
681    // crates/coven-sync/build.rs fails the build when CONST_RANDOM_SEED fixes this draw.
682    const BUILD: u128 = const_random::const_random!(u128);
683    /// A refusal is a verdict on bytes that never change, judged against
684    /// what never changes either: only another build can judge it
685    /// differently, and each other build checks it once (§19.1).
686    fn can_retry(&self, recorded_build: u128, schema_version: u32) -> bool {
687        match self.reason.retry_cause() {
688            PendingReason::Refused(_) => recorded_build != Self::BUILD,
689            PendingReason::UpdateRequired(RequiredUpdate::AppSchema { version }) => {
690                schema_version >= *version
691            }
692            PendingReason::UpdateRequired(RequiredUpdate::CovenFormat { version }) => {
693                coven_format::FORMAT_VERSION >= *version
694            }
695            _ => self.retry() == Retry::Automatic,
696        }
697    }
698    fn cause(&self) -> Option<&str> {
699        self.cause.as_deref()
700    }
701    fn with_cause(self, cause: Option<String>) -> Self {
702        Self { cause, ..self }
703    }
704}
705
706#[cfg(test)]
707#[path = "pending_tests.rs"]
708mod tests;