Skip to main content

postproject_core/
revision.rs

1//! Durable semantic revision values for production-local change feeds.
2
3use std::{collections::BTreeSet, fmt, str::FromStr, time::Duration};
4
5use crate::{
6    ActivityId, ActivityKind, ActivityRole, AssetId, Error, ErrorKind, ExternalIdentifier, JobId,
7    LocatorId, MediaRootId, MetadataProperty, ObjectRef, RepresentationId, ResourceId, Result,
8    RevisionId, Timestamp, ToolIdentity, TransactionId,
9};
10
11/// Maximum UTF-8 byte length of a revision message.
12pub const MAX_REVISION_MESSAGE_BYTES: usize = 4_096;
13/// Maximum revisions returned by one change-feed page.
14pub const MAX_REVISION_PAGE_SIZE: u32 = 1_000;
15/// Longest caller-supplied timeout accepted by one revision wait.
16pub const MAX_REVISION_WAIT: Duration = Duration::from_secs(60);
17
18/// Identity of the integrating application or process that committed a revision.
19#[derive(Clone, Debug, Eq, PartialEq)]
20pub struct OriginIdentity(ToolIdentity);
21
22impl OriginIdentity {
23    /// Creates a bounded origin identity with an optional version and URI.
24    ///
25    /// # Errors
26    ///
27    /// Returns [`ErrorKind::InvalidArgument`] under the same conditions as
28    /// [`ToolIdentity::new`].
29    pub fn new(
30        name: impl Into<String>,
31        version: Option<String>,
32        uri: Option<String>,
33    ) -> Result<Self> {
34        ToolIdentity::new(name, version, uri).map(Self)
35    }
36
37    /// Returns the integrating application or process name.
38    #[must_use]
39    pub fn name(&self) -> &str {
40        self.0.name()
41    }
42
43    /// Returns the optional exact application version or build.
44    #[must_use]
45    pub fn version(&self) -> Option<&str> {
46        self.0.version()
47    }
48
49    /// Returns the optional canonical application or vendor URI.
50    #[must_use]
51    pub fn uri(&self) -> Option<&str> {
52        self.0.uri()
53    }
54}
55
56/// One committed production mutation transaction in local sequence order.
57#[derive(Clone, Debug, Eq, PartialEq)]
58pub struct Revision {
59    id: RevisionId,
60    sequence: u64,
61    transaction_id: TransactionId,
62    committed_at: Timestamp,
63    origin: Option<OriginIdentity>,
64    message: Option<String>,
65}
66
67/// Optional origin and message applied to one transaction's revision.
68#[derive(Clone, Debug, Default, Eq, PartialEq)]
69pub struct RevisionContext {
70    origin: Option<OriginIdentity>,
71    message: Option<String>,
72}
73
74impl RevisionContext {
75    /// Creates validated context for a future committed revision.
76    ///
77    /// # Errors
78    ///
79    /// Returns [`ErrorKind::InvalidArgument`] for an empty, oversized, or
80    /// NUL-containing message.
81    pub fn new(origin: Option<OriginIdentity>, message: Option<String>) -> Result<Self> {
82        validate_revision_message(message.as_deref())?;
83        Ok(Self { origin, message })
84    }
85
86    /// Returns the optional integrating application/process identity.
87    #[must_use]
88    pub const fn origin(&self) -> Option<&OriginIdentity> {
89        self.origin.as_ref()
90    }
91
92    /// Returns the optional human-facing revision message.
93    #[must_use]
94    pub fn message(&self) -> Option<&str> {
95        self.message.as_deref()
96    }
97}
98
99/// One semantic mutation recorded in a durable revision.
100#[derive(Clone, Debug, Eq, PartialEq)]
101#[non_exhaustive]
102pub enum RevisionEventKind {
103    /// A logical asset and its import aggregate were created.
104    AssetImported {
105        /// Imported logical asset.
106        asset_id: AssetId,
107    },
108    /// A representation was attached to an asset.
109    RepresentationAdded {
110        /// Owning logical asset.
111        asset_id: AssetId,
112        /// Added representation.
113        representation_id: RepresentationId,
114    },
115    /// A storage resource was created.
116    ResourceAdded {
117        /// Added resource.
118        resource_id: ResourceId,
119    },
120    /// A resource was attached to a representation's content structure.
121    RepresentationResourceAdded {
122        /// Owning representation.
123        representation_id: RepresentationId,
124        /// Attached resource.
125        resource_id: ResourceId,
126        /// Stable structural position within the representation.
127        position: u32,
128    },
129    /// A resource locator was added or explicitly confirmed.
130    LocatorAdded {
131        /// Located resource.
132        resource_id: ResourceId,
133        /// Added locator.
134        locator_id: LocatorId,
135    },
136    /// A superseded resource locator was retired.
137    LocatorRetired {
138        /// Resource that owned the retired locator.
139        resource_id: ResourceId,
140        /// Retired locator.
141        locator_id: LocatorId,
142    },
143    /// A resolver media root was added.
144    MediaRootAdded {
145        /// Added media root.
146        media_root_id: MediaRootId,
147    },
148    /// A resolver media root was enabled or disabled.
149    MediaRootEnabledChanged {
150        /// Updated media root.
151        media_root_id: MediaRootId,
152        /// New resolver participation state.
153        enabled: bool,
154    },
155    /// A resolver media root was removed.
156    MediaRootRemoved {
157        /// Removed media root.
158        media_root_id: MediaRootId,
159    },
160    /// An exact external identifier attachment was added.
161    ExternalIdentifierAdded {
162        /// Object receiving the identifier.
163        target: ObjectRef,
164        /// Added external identifier.
165        identifier: ExternalIdentifier,
166    },
167    /// An exact external identifier attachment was removed.
168    ExternalIdentifierRemoved {
169        /// Object losing the identifier.
170        target: ObjectRef,
171        /// Removed external identifier.
172        identifier: ExternalIdentifier,
173    },
174    /// One metadata property's values were appended or replaced.
175    MetadataAddedOrReplaced {
176        /// Object whose metadata changed.
177        target: ObjectRef,
178        /// Property that consumers should re-query.
179        property: MetadataProperty,
180    },
181    /// One metadata property was removed.
182    MetadataRemoved {
183        /// Object whose metadata changed.
184        target: ObjectRef,
185        /// Removed property.
186        property: MetadataProperty,
187    },
188    /// A production activity was created.
189    ActivityCreated {
190        /// Added activity.
191        activity_id: ActivityId,
192        /// Extensible activity kind.
193        kind: ActivityKind,
194    },
195    /// A production activity input edge was added.
196    ActivityInputAdded {
197        /// Owning activity.
198        activity_id: ActivityId,
199        /// Consumed representation.
200        representation_id: RepresentationId,
201        /// Optional semantic edge role.
202        role: Option<ActivityRole>,
203    },
204    /// A production activity output edge was added.
205    ActivityOutputAdded {
206        /// Owning activity.
207        activity_id: ActivityId,
208        /// Produced representation.
209        representation_id: RepresentationId,
210        /// Optional semantic edge role.
211        role: Option<ActivityRole>,
212    },
213    /// A resource fingerprint domain received a new current observation.
214    ResourceFingerprintObserved {
215        /// Re-observed storage resource.
216        resource_id: ResourceId,
217        /// Fingerprint algorithm identifier.
218        algorithm: String,
219        /// Fingerprint algorithm format version.
220        version: u16,
221    },
222    /// A resource's size or modification time received a new observation.
223    ResourceFileFactsObserved {
224        /// Re-observed storage resource.
225        resource_id: ResourceId,
226    },
227    /// A representation fingerprint domain received a new current observation.
228    RepresentationFingerprintObserved {
229        /// Re-observed representation.
230        representation_id: RepresentationId,
231        /// Fingerprint algorithm identifier.
232        algorithm: String,
233        /// Fingerprint algorithm format version.
234        version: u16,
235    },
236    /// A representation's complete dependency observation was replaced.
237    DependencySetRecorded {
238        /// Representation whose authored dependency set changed.
239        representation_id: RepresentationId,
240    },
241    /// A durable work request was created.
242    JobRequested {
243        /// Requested job.
244        job_id: JobId,
245    },
246    /// A worker claimed a requested or expired job.
247    JobClaimed {
248        /// Claimed job.
249        job_id: JobId,
250    },
251    /// The current worker extended a job lease.
252    JobClaimRenewed {
253        /// Renewed job.
254        job_id: JobId,
255    },
256    /// The current worker released a job claim.
257    JobClaimReleased {
258        /// Released job.
259        job_id: JobId,
260    },
261    /// A job completed with its durable activity and output.
262    JobSucceeded {
263        /// Completed job.
264        job_id: JobId,
265    },
266    /// A job ended with a diagnostic and no output.
267    JobFailed {
268        /// Failed job.
269        job_id: JobId,
270    },
271    /// A requested or claimed job was cancelled.
272    JobCancelled {
273        /// Cancelled job.
274        job_id: JobId,
275    },
276}
277
278/// Payload-free discriminant of a [`RevisionEventKind`].
279///
280/// Event types select revisions for a filtered change-feed page. Their stable
281/// names are the `snake_case` form of the event kind.
282#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
283#[non_exhaustive]
284pub enum RevisionEventType {
285    /// A logical asset and its import aggregate were created.
286    AssetImported,
287    /// A representation was attached to an asset.
288    RepresentationAdded,
289    /// A storage resource was created.
290    ResourceAdded,
291    /// A resource was attached to a representation's content structure.
292    RepresentationResourceAdded,
293    /// A resource locator was added or explicitly confirmed.
294    LocatorAdded,
295    /// A superseded resource locator was retired.
296    LocatorRetired,
297    /// A resolver media root was added.
298    MediaRootAdded,
299    /// A resolver media root was enabled or disabled.
300    MediaRootEnabledChanged,
301    /// A resolver media root was removed.
302    MediaRootRemoved,
303    /// An exact external identifier attachment was added.
304    ExternalIdentifierAdded,
305    /// An exact external identifier attachment was removed.
306    ExternalIdentifierRemoved,
307    /// One metadata property's values were appended or replaced.
308    MetadataAddedOrReplaced,
309    /// One metadata property was removed.
310    MetadataRemoved,
311    /// A production activity was created.
312    ActivityCreated,
313    /// A production activity input edge was added.
314    ActivityInputAdded,
315    /// A production activity output edge was added.
316    ActivityOutputAdded,
317    /// A resource fingerprint domain received a new current observation.
318    ResourceFingerprintObserved,
319    /// A resource's size or modification time received a new observation.
320    ResourceFileFactsObserved,
321    /// A representation fingerprint domain received a new current observation.
322    RepresentationFingerprintObserved,
323    /// A representation's complete dependency observation was replaced.
324    DependencySetRecorded,
325    /// A durable work request was created.
326    JobRequested,
327    /// A worker claimed a requested or expired job.
328    JobClaimed,
329    /// The current worker extended a job lease.
330    JobClaimRenewed,
331    /// The current worker released a job claim.
332    JobClaimReleased,
333    /// A job completed with its durable activity and output.
334    JobSucceeded,
335    /// A job ended with a diagnostic and no output.
336    JobFailed,
337    /// A requested or claimed job was cancelled.
338    JobCancelled,
339}
340
341impl RevisionEventType {
342    /// Every event type in catalog order.
343    pub const ALL: &'static [Self] = &[
344        Self::AssetImported,
345        Self::RepresentationAdded,
346        Self::ResourceAdded,
347        Self::RepresentationResourceAdded,
348        Self::LocatorAdded,
349        Self::LocatorRetired,
350        Self::MediaRootAdded,
351        Self::MediaRootEnabledChanged,
352        Self::MediaRootRemoved,
353        Self::ExternalIdentifierAdded,
354        Self::ExternalIdentifierRemoved,
355        Self::MetadataAddedOrReplaced,
356        Self::MetadataRemoved,
357        Self::ActivityCreated,
358        Self::ActivityInputAdded,
359        Self::ActivityOutputAdded,
360        Self::ResourceFingerprintObserved,
361        Self::ResourceFileFactsObserved,
362        Self::RepresentationFingerprintObserved,
363        Self::DependencySetRecorded,
364        Self::JobRequested,
365        Self::JobClaimed,
366        Self::JobClaimRenewed,
367        Self::JobClaimReleased,
368        Self::JobSucceeded,
369        Self::JobFailed,
370        Self::JobCancelled,
371    ];
372
373    /// Returns the stable `snake_case` event type name.
374    #[must_use]
375    pub const fn as_str(self) -> &'static str {
376        match self {
377            Self::AssetImported => "asset_imported",
378            Self::RepresentationAdded => "representation_added",
379            Self::ResourceAdded => "resource_added",
380            Self::RepresentationResourceAdded => "representation_resource_added",
381            Self::LocatorAdded => "locator_added",
382            Self::LocatorRetired => "locator_retired",
383            Self::MediaRootAdded => "media_root_added",
384            Self::MediaRootEnabledChanged => "media_root_enabled_changed",
385            Self::MediaRootRemoved => "media_root_removed",
386            Self::ExternalIdentifierAdded => "external_identifier_added",
387            Self::ExternalIdentifierRemoved => "external_identifier_removed",
388            Self::MetadataAddedOrReplaced => "metadata_added_or_replaced",
389            Self::MetadataRemoved => "metadata_removed",
390            Self::ActivityCreated => "activity_created",
391            Self::ActivityInputAdded => "activity_input_added",
392            Self::ActivityOutputAdded => "activity_output_added",
393            Self::ResourceFingerprintObserved => "resource_fingerprint_observed",
394            Self::ResourceFileFactsObserved => "resource_file_facts_observed",
395            Self::RepresentationFingerprintObserved => "representation_fingerprint_observed",
396            Self::DependencySetRecorded => "dependency_set_recorded",
397            Self::JobRequested => "job_requested",
398            Self::JobClaimed => "job_claimed",
399            Self::JobClaimRenewed => "job_claim_renewed",
400            Self::JobClaimReleased => "job_claim_released",
401            Self::JobSucceeded => "job_succeeded",
402            Self::JobFailed => "job_failed",
403            Self::JobCancelled => "job_cancelled",
404        }
405    }
406
407    /// Returns the explicit optimistic-concurrency policy for this event type.
408    #[must_use]
409    pub const fn concurrency_classification(self) -> crate::ConcurrencyClassification {
410        use crate::ConcurrencyClassification::{
411            Conflict, ExistingGuard, Merge, OperationDependent,
412        };
413        match self {
414            Self::AssetImported
415            | Self::RepresentationAdded
416            | Self::ResourceAdded
417            | Self::RepresentationResourceAdded
418            | Self::ActivityCreated
419            | Self::ActivityInputAdded
420            | Self::ActivityOutputAdded
421            | Self::JobRequested => Merge,
422            Self::LocatorAdded
423            | Self::LocatorRetired
424            | Self::MediaRootEnabledChanged
425            | Self::MediaRootRemoved
426            | Self::ExternalIdentifierAdded
427            | Self::ExternalIdentifierRemoved
428            | Self::MetadataRemoved
429            | Self::ResourceFingerprintObserved
430            | Self::ResourceFileFactsObserved
431            | Self::RepresentationFingerprintObserved
432            | Self::DependencySetRecorded => Conflict,
433            Self::MediaRootAdded
434            | Self::JobClaimed
435            | Self::JobClaimRenewed
436            | Self::JobClaimReleased
437            | Self::JobSucceeded
438            | Self::JobFailed
439            | Self::JobCancelled => ExistingGuard,
440            Self::MetadataAddedOrReplaced => OperationDependent,
441        }
442    }
443}
444
445impl fmt::Display for RevisionEventType {
446    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
447        formatter.write_str(self.as_str())
448    }
449}
450
451impl FromStr for RevisionEventType {
452    type Err = Error;
453
454    fn from_str(value: &str) -> Result<Self> {
455        Self::ALL
456            .iter()
457            .copied()
458            .find(|event_type| event_type.as_str() == value)
459            .ok_or_else(|| {
460                Error::new(
461                    ErrorKind::InvalidArgument,
462                    format!("unknown revision event type: {value}"),
463                )
464            })
465    }
466}
467
468impl RevisionEventKind {
469    /// Returns the payload-free type of this event.
470    #[must_use]
471    pub const fn event_type(&self) -> RevisionEventType {
472        match self {
473            Self::AssetImported { .. } => RevisionEventType::AssetImported,
474            Self::RepresentationAdded { .. } => RevisionEventType::RepresentationAdded,
475            Self::ResourceAdded { .. } => RevisionEventType::ResourceAdded,
476            Self::RepresentationResourceAdded { .. } => {
477                RevisionEventType::RepresentationResourceAdded
478            }
479            Self::LocatorAdded { .. } => RevisionEventType::LocatorAdded,
480            Self::LocatorRetired { .. } => RevisionEventType::LocatorRetired,
481            Self::MediaRootAdded { .. } => RevisionEventType::MediaRootAdded,
482            Self::MediaRootEnabledChanged { .. } => RevisionEventType::MediaRootEnabledChanged,
483            Self::MediaRootRemoved { .. } => RevisionEventType::MediaRootRemoved,
484            Self::ExternalIdentifierAdded { .. } => RevisionEventType::ExternalIdentifierAdded,
485            Self::ExternalIdentifierRemoved { .. } => RevisionEventType::ExternalIdentifierRemoved,
486            Self::MetadataAddedOrReplaced { .. } => RevisionEventType::MetadataAddedOrReplaced,
487            Self::MetadataRemoved { .. } => RevisionEventType::MetadataRemoved,
488            Self::ActivityCreated { .. } => RevisionEventType::ActivityCreated,
489            Self::ActivityInputAdded { .. } => RevisionEventType::ActivityInputAdded,
490            Self::ActivityOutputAdded { .. } => RevisionEventType::ActivityOutputAdded,
491            Self::ResourceFingerprintObserved { .. } => {
492                RevisionEventType::ResourceFingerprintObserved
493            }
494            Self::ResourceFileFactsObserved { .. } => RevisionEventType::ResourceFileFactsObserved,
495            Self::RepresentationFingerprintObserved { .. } => {
496                RevisionEventType::RepresentationFingerprintObserved
497            }
498            Self::DependencySetRecorded { .. } => RevisionEventType::DependencySetRecorded,
499            Self::JobRequested { .. } => RevisionEventType::JobRequested,
500            Self::JobClaimed { .. } => RevisionEventType::JobClaimed,
501            Self::JobClaimRenewed { .. } => RevisionEventType::JobClaimRenewed,
502            Self::JobClaimReleased { .. } => RevisionEventType::JobClaimReleased,
503            Self::JobSucceeded { .. } => RevisionEventType::JobSucceeded,
504            Self::JobFailed { .. } => RevisionEventType::JobFailed,
505            Self::JobCancelled { .. } => RevisionEventType::JobCancelled,
506        }
507    }
508}
509
510/// Non-empty set of event types that selects revisions for a filtered page.
511#[derive(Clone, Debug, Eq, PartialEq)]
512pub struct RevisionEventFilter {
513    types: BTreeSet<RevisionEventType>,
514}
515
516impl RevisionEventFilter {
517    /// Creates a filter matching revisions with at least one event of `types`.
518    ///
519    /// Duplicate types are ignored.
520    ///
521    /// # Errors
522    ///
523    /// Returns [`ErrorKind::InvalidArgument`] when `types` is empty.
524    pub fn new(types: impl IntoIterator<Item = RevisionEventType>) -> Result<Self> {
525        let types: BTreeSet<_> = types.into_iter().collect();
526        if types.is_empty() {
527            return Err(Error::new(
528                ErrorKind::InvalidArgument,
529                "revision event filter must name at least one event type",
530            ));
531        }
532        Ok(Self { types })
533    }
534
535    /// Returns the selected event types in catalog order.
536    #[must_use = "event types are only visited when the iterator is consumed"]
537    pub fn types(&self) -> impl ExactSizeIterator<Item = RevisionEventType> + '_ {
538        self.types.iter().copied()
539    }
540
541    /// Reports whether an event of `event_type` selects its revision.
542    #[must_use]
543    pub fn matches(&self, event_type: RevisionEventType) -> bool {
544        self.types.contains(&event_type)
545    }
546}
547
548/// One page of revisions that contain at least one event of a filter's types.
549///
550/// Every matching revision with a sequence greater than the requested sequence
551/// and at most [`Self::through_sequence`] is in the page. The through sequence
552/// is the cursor for the next filtered page.
553#[derive(Clone, Debug, Eq, PartialEq)]
554pub struct FilteredRevisionPage {
555    revisions: Vec<Revision>,
556    through_sequence: u64,
557}
558
559impl FilteredRevisionPage {
560    /// Creates a page from ascending matching revisions and its covered range end.
561    ///
562    /// # Errors
563    ///
564    /// Returns [`ErrorKind::InvalidArgument`] when revisions are not strictly
565    /// ascending or one lies beyond `through_sequence`.
566    pub fn new(revisions: Vec<Revision>, through_sequence: u64) -> Result<Self> {
567        let ascending = revisions
568            .windows(2)
569            .all(|pair| pair[0].sequence() < pair[1].sequence());
570        if !ascending
571            || revisions
572                .last()
573                .is_some_and(|revision| revision.sequence() > through_sequence)
574        {
575            return Err(Error::new(
576                ErrorKind::InvalidArgument,
577                "filtered revisions must ascend and end at or before the through sequence",
578            ));
579        }
580        Ok(Self {
581            revisions,
582            through_sequence,
583        })
584    }
585
586    /// Returns the matching revisions in ascending sequence order.
587    #[must_use]
588    pub fn revisions(&self) -> &[Revision] {
589        &self.revisions
590    }
591
592    /// Consumes the page and returns its matching revisions.
593    #[must_use]
594    pub fn into_revisions(self) -> Vec<Revision> {
595        self.revisions
596    }
597
598    /// Returns the last sequence this page accounts for; the next cursor.
599    #[must_use]
600    pub const fn through_sequence(&self) -> u64 {
601        self.through_sequence
602    }
603}
604
605/// Outcome of one bounded wait for revisions after a sequence.
606#[derive(Clone, Debug, Eq, PartialEq)]
607#[non_exhaustive]
608pub enum RevisionWaitOutcome {
609    /// A non-empty ascending page of revisions after the requested sequence.
610    Revisions(Vec<Revision>),
611    /// No revision after the requested sequence appeared within the timeout.
612    TimedOut,
613    /// The production the waiter belongs to was closed. Terminal.
614    Closed,
615    /// The waiter was cancelled. Terminal.
616    Cancelled,
617}
618
619/// Bounded blocking wait for revisions committed after a sequence.
620///
621/// Implementations observe commits from the same process and from other
622/// processes sharing the production. Closed and cancelled outcomes are
623/// terminal for the waiter.
624pub trait RevisionWaiter {
625    /// Waits until at least one revision after `after_sequence` exists, then
626    /// returns up to `limit` of them in ascending order.
627    ///
628    /// A zero `timeout` checks once without blocking.
629    ///
630    /// # Errors
631    ///
632    /// Returns [`ErrorKind::InvalidArgument`] when `limit` is zero or exceeds
633    /// [`MAX_REVISION_PAGE_SIZE`], or when `timeout` exceeds
634    /// [`MAX_REVISION_WAIT`]; storage errors are returned unchanged.
635    fn wait_for_revisions(
636        &mut self,
637        after_sequence: u64,
638        limit: u32,
639        timeout: Duration,
640    ) -> Result<RevisionWaitOutcome>;
641}
642
643/// Validates the page limit and timeout of one revision wait.
644///
645/// # Errors
646///
647/// Returns [`ErrorKind::InvalidArgument`] for a zero or excessive limit or an
648/// excessive timeout.
649pub fn validate_revision_wait(limit: u32, timeout: Duration) -> Result<()> {
650    if limit == 0 || limit > MAX_REVISION_PAGE_SIZE {
651        return Err(Error::new(
652            ErrorKind::InvalidArgument,
653            format!("revision page limit must be 1-{MAX_REVISION_PAGE_SIZE}"),
654        ));
655    }
656    if timeout > MAX_REVISION_WAIT {
657        return Err(Error::new(
658            ErrorKind::InvalidArgument,
659            format!(
660                "revision wait timeout must not exceed {} ms",
661                MAX_REVISION_WAIT.as_millis()
662            ),
663        ));
664    }
665    Ok(())
666}
667
668/// One deterministically ordered semantic event within a revision.
669#[derive(Clone, Debug, Eq, PartialEq)]
670pub struct RevisionEvent {
671    revision_id: RevisionId,
672    position: u32,
673    kind: RevisionEventKind,
674}
675
676impl RevisionEvent {
677    /// Creates an event at its stable zero-based revision position.
678    #[must_use]
679    pub const fn new(revision_id: RevisionId, position: u32, kind: RevisionEventKind) -> Self {
680        Self {
681            revision_id,
682            position,
683            kind,
684        }
685    }
686
687    /// Returns the revision that owns the event.
688    #[must_use]
689    pub const fn revision_id(&self) -> RevisionId {
690        self.revision_id
691    }
692
693    /// Returns the zero-based stable position within the revision.
694    #[must_use]
695    pub const fn position(&self) -> u32 {
696        self.position
697    }
698
699    /// Returns the semantic mutation payload.
700    #[must_use]
701    pub const fn kind(&self) -> &RevisionEventKind {
702        &self.kind
703    }
704}
705
706impl Revision {
707    /// Creates a complete durable revision value.
708    ///
709    /// # Errors
710    ///
711    /// Returns [`ErrorKind::InvalidArgument`] for sequence zero or an empty,
712    /// oversized, or NUL-containing message.
713    pub fn new(
714        id: RevisionId,
715        sequence: u64,
716        transaction_id: TransactionId,
717        committed_at: Timestamp,
718        origin: Option<OriginIdentity>,
719        message: Option<String>,
720    ) -> Result<Self> {
721        if sequence == 0 {
722            return Err(Error::new(
723                ErrorKind::InvalidArgument,
724                "revision sequence must be greater than zero",
725            ));
726        }
727        validate_revision_message(message.as_deref())?;
728        Ok(Self {
729            id,
730            sequence,
731            transaction_id,
732            committed_at,
733            origin,
734            message,
735        })
736    }
737
738    /// Returns the stable revision identity.
739    #[must_use]
740    pub const fn id(&self) -> RevisionId {
741        self.id
742    }
743
744    /// Returns the monotonically increasing production-local sequence.
745    #[must_use]
746    pub const fn sequence(&self) -> u64 {
747        self.sequence
748    }
749
750    /// Returns the transaction that produced this revision.
751    #[must_use]
752    pub const fn transaction_id(&self) -> TransactionId {
753        self.transaction_id
754    }
755
756    /// Returns the durable commit timestamp.
757    #[must_use]
758    pub const fn committed_at(&self) -> Timestamp {
759        self.committed_at
760    }
761
762    /// Returns the optional integrating application/process identity.
763    #[must_use]
764    pub const fn origin(&self) -> Option<&OriginIdentity> {
765        self.origin.as_ref()
766    }
767
768    /// Returns the optional human-facing commit message.
769    #[must_use]
770    pub fn message(&self) -> Option<&str> {
771        self.message.as_deref()
772    }
773}
774
775fn validate_revision_message(message: Option<&str>) -> Result<()> {
776    if message.is_some_and(|message| {
777        message.is_empty() || message.len() > MAX_REVISION_MESSAGE_BYTES || message.contains('\0')
778    }) {
779        return Err(Error::new(
780            ErrorKind::InvalidArgument,
781            format!(
782                "revision message must contain 1-{MAX_REVISION_MESSAGE_BYTES} UTF-8 bytes without NUL"
783            ),
784        ));
785    }
786    Ok(())
787}
788
789#[cfg(test)]
790mod tests {
791    use super::*;
792
793    #[test]
794    fn revision_preserves_transaction_context() {
795        let origin = OriginIdentity::new(
796            "Editorial host",
797            Some("2.4.1".to_owned()),
798            Some("https://example.com/editor".to_owned()),
799        )
800        .expect("valid origin");
801        let revision = Revision::new(
802            RevisionId::new(),
803            7,
804            TransactionId::new(),
805            Timestamp::from_unix_micros(42),
806            Some(origin),
807            Some("Import camera original".to_owned()),
808        )
809        .expect("valid revision");
810
811        assert_eq!(revision.sequence(), 7);
812        assert_eq!(revision.committed_at().as_unix_micros(), 42);
813        assert_eq!(revision.origin().unwrap().name(), "Editorial host");
814        assert_eq!(revision.message(), Some("Import camera original"));
815    }
816
817    #[test]
818    fn revision_rejects_ambiguous_context() {
819        let create = |sequence, message| {
820            Revision::new(
821                RevisionId::new(),
822                sequence,
823                TransactionId::new(),
824                Timestamp::from_unix_micros(0),
825                None,
826                message,
827            )
828        };
829
830        assert!(create(0, None).is_err());
831        assert!(create(1, Some(String::new())).is_err());
832        assert!(create(1, Some("bad\0message".to_owned())).is_err());
833        assert!(create(1, Some("x".repeat(MAX_REVISION_MESSAGE_BYTES + 1))).is_err());
834    }
835
836    #[test]
837    fn events_identify_semantic_targets_in_stable_order() {
838        let revision_id = RevisionId::new();
839        let asset_id = AssetId::new();
840        let representation_id = RepresentationId::new();
841        let events = [
842            RevisionEvent::new(
843                revision_id,
844                0,
845                RevisionEventKind::AssetImported { asset_id },
846            ),
847            RevisionEvent::new(
848                revision_id,
849                1,
850                RevisionEventKind::RepresentationAdded {
851                    asset_id,
852                    representation_id,
853                },
854            ),
855        ];
856
857        assert_eq!(events[0].revision_id(), revision_id);
858        assert_eq!(events[1].position(), 1);
859        assert!(matches!(
860            events[1].kind(),
861            RevisionEventKind::RepresentationAdded {
862                representation_id: id,
863                ..
864            } if *id == representation_id
865        ));
866    }
867
868    #[test]
869    fn event_types_round_trip_their_stable_names() {
870        for event_type in RevisionEventType::ALL {
871            assert_eq!(
872                event_type.as_str().parse::<RevisionEventType>().unwrap(),
873                *event_type
874            );
875        }
876        assert_eq!(RevisionEventType::ALL.len(), 27);
877        assert!("row_updated".parse::<RevisionEventType>().is_err());
878        assert_eq!(
879            RevisionEventKind::JobSucceeded {
880                job_id: JobId::new()
881            }
882            .event_type(),
883            RevisionEventType::JobSucceeded
884        );
885    }
886
887    #[test]
888    fn every_event_type_has_an_explicit_concurrency_classification() {
889        use crate::ConcurrencyClassification::{
890            Conflict, ExistingGuard, Merge, OperationDependent,
891        };
892
893        let classifications: Vec<_> = RevisionEventType::ALL
894            .iter()
895            .map(|event| event.concurrency_classification())
896            .collect();
897        assert_eq!(classifications.len(), 27);
898        assert!(classifications.contains(&Merge));
899        assert!(classifications.contains(&Conflict));
900        assert_eq!(
901            RevisionEventType::ResourceFileFactsObserved.concurrency_classification(),
902            Conflict
903        );
904        assert!(classifications.contains(&ExistingGuard));
905        assert!(classifications.contains(&OperationDependent));
906    }
907
908    #[test]
909    fn filters_and_filtered_pages_reject_ambiguous_values() {
910        assert!(RevisionEventFilter::new([]).is_err());
911        let filter = RevisionEventFilter::new([
912            RevisionEventType::JobFailed,
913            RevisionEventType::AssetImported,
914            RevisionEventType::JobFailed,
915        ])
916        .unwrap();
917        assert_eq!(
918            filter.types().collect::<Vec<_>>(),
919            [
920                RevisionEventType::AssetImported,
921                RevisionEventType::JobFailed
922            ]
923        );
924        assert!(filter.matches(RevisionEventType::JobFailed));
925        assert!(!filter.matches(RevisionEventType::JobClaimed));
926
927        let revision = |sequence| {
928            Revision::new(
929                RevisionId::new(),
930                sequence,
931                TransactionId::new(),
932                Timestamp::from_unix_micros(0),
933                None,
934                None,
935            )
936            .unwrap()
937        };
938        assert!(FilteredRevisionPage::new(vec![revision(2), revision(4)], 9).is_ok());
939        assert!(FilteredRevisionPage::new(vec![revision(4), revision(2)], 9).is_err());
940        assert!(FilteredRevisionPage::new(vec![revision(4)], 3).is_err());
941        assert_eq!(
942            FilteredRevisionPage::new(Vec::new(), 7)
943                .unwrap()
944                .through_sequence(),
945            7
946        );
947    }
948
949    #[test]
950    fn revision_waits_are_bounded() {
951        assert!(validate_revision_wait(1, Duration::ZERO).is_ok());
952        assert!(validate_revision_wait(MAX_REVISION_PAGE_SIZE, MAX_REVISION_WAIT).is_ok());
953        assert!(validate_revision_wait(0, Duration::ZERO).is_err());
954        assert!(validate_revision_wait(MAX_REVISION_PAGE_SIZE + 1, Duration::ZERO).is_err());
955        assert!(validate_revision_wait(1, MAX_REVISION_WAIT + Duration::from_millis(1)).is_err());
956    }
957}