lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

projection.rs (44255B)


      1 //! Projection checkpoint, event-index manifest, and rebuild contracts.
      2 //!
      3 //! Storage owns durable coordination metadata. Domain reducers and projected
      4 //! row representations remain in their domain packages.
      5 
      6 pub mod batch;
      7 pub mod cache;
      8 pub mod document_query;
      9 
     10 pub use radroots_event::EventId;
     11 pub use radroots_transport::BoxFuture;
     12 use sha2::{Digest, Sha256};
     13 use std::collections::BTreeSet;
     14 
     15 use crate::{
     16     Error,
     17     event::{EventPosition, SourceGeneration},
     18 };
     19 
     20 pub const PROJECTION_ID_MAX_BYTES: usize = 128;
     21 pub const EVENT_INDEX_SHARD_ID_MAX_BYTES: usize = 128;
     22 pub const EVENT_INDEX_ARTIFACT_PATH_MAX_BYTES: usize = 512;
     23 pub const EVENT_INDEX_CURSOR_MAX_BYTES: usize = 2_048;
     24 pub const EVENT_INDEX_SHARDS_MAX: usize = 4_096;
     25 
     26 /// Stable, backend-neutral projection identity.
     27 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
     28 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
     29 pub struct ProjectionId(String);
     30 
     31 impl ProjectionId {
     32     pub fn parse(value: impl Into<String>) -> Result<Self, Error> {
     33         let value = value.into();
     34         if !valid_label(value.as_str(), PROJECTION_ID_MAX_BYTES) {
     35             return Err(Error::InvalidProjectionId);
     36         }
     37         Ok(Self(value))
     38     }
     39 
     40     pub fn as_str(&self) -> &str {
     41         self.0.as_str()
     42     }
     43 }
     44 
     45 /// Content-derived generation of a projection implementation and its inputs.
     46 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
     47 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
     48 pub struct ProjectionGeneration([u8; 32]);
     49 
     50 impl ProjectionGeneration {
     51     pub const fn new(bytes: [u8; 32]) -> Result<Self, Error> {
     52         if bytes32_are_zero(&bytes) {
     53             return Err(Error::InvalidProjectionGeneration);
     54         }
     55         Ok(Self(bytes))
     56     }
     57     pub const fn as_bytes(&self) -> &[u8; 32] {
     58         &self.0
     59     }
     60 }
     61 
     62 /// SHA-256 digest of one ordered, immutable canonical raw-event snapshot.
     63 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
     64 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
     65 pub struct RawSourceDigest([u8; 32]);
     66 
     67 impl RawSourceDigest {
     68     pub const fn new(bytes: [u8; 32]) -> Self {
     69         Self(bytes)
     70     }
     71 
     72     pub const fn as_bytes(&self) -> &[u8; 32] {
     73         &self.0
     74     }
     75 }
     76 
     77 /// Non-zero optimistic revision for projection coordination state.
     78 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
     79 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
     80 pub struct ProjectionRevision(u64);
     81 
     82 impl ProjectionRevision {
     83     pub const INITIAL: Self = Self(1);
     84     pub const fn new(value: u64) -> Result<Self, Error> {
     85         if value == 0 {
     86             return Err(Error::InvalidProjectionRevision);
     87         }
     88         Ok(Self(value))
     89     }
     90     pub const fn get(self) -> u64 {
     91         self.0
     92     }
     93     fn next(self) -> Result<Self, Error> {
     94         self.0
     95             .checked_add(1)
     96             .map(Self)
     97             .ok_or(Error::CorruptProjectionRecord)
     98     }
     99 }
    100 
    101 /// Last canonical event incorporated by a projection generation.
    102 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    103 #[derive(Clone, Debug, Eq, PartialEq)]
    104 pub struct ProjectionCheckpoint {
    105     projection_id: ProjectionId,
    106     generation: ProjectionGeneration,
    107     source_position: Option<EventPosition>,
    108     projected_rows: u64,
    109     updated_at_unix_ms: u64,
    110 }
    111 
    112 impl ProjectionCheckpoint {
    113     pub fn new(
    114         projection_id: ProjectionId,
    115         generation: ProjectionGeneration,
    116         source_position: Option<EventPosition>,
    117         projected_rows: u64,
    118         updated_at_unix_ms: u64,
    119     ) -> Result<Self, Error> {
    120         if updated_at_unix_ms == 0 {
    121             return Err(Error::InvalidProjectionTimestamp);
    122         }
    123         Ok(Self {
    124             projection_id,
    125             generation,
    126             source_position,
    127             projected_rows,
    128             updated_at_unix_ms,
    129         })
    130     }
    131     pub const fn projection_id(&self) -> &ProjectionId {
    132         &self.projection_id
    133     }
    134     pub const fn generation(&self) -> ProjectionGeneration {
    135         self.generation
    136     }
    137     pub const fn source_position(&self) -> Option<EventPosition> {
    138         self.source_position
    139     }
    140     pub const fn projected_rows(&self) -> u64 {
    141         self.projected_rows
    142     }
    143     pub const fn updated_at_unix_ms(&self) -> u64 {
    144         self.updated_at_unix_ms
    145     }
    146 
    147     pub fn advances(&self, prior: &Self) -> bool {
    148         self.projection_id == prior.projection_id
    149             && self.generation == prior.generation
    150             && self.updated_at_unix_ms >= prior.updated_at_unix_ms
    151             && self.projected_rows >= prior.projected_rows
    152             && match (self.source_position, prior.source_position) {
    153                 (Some(next), Some(previous)) => {
    154                     next.generation() == previous.generation()
    155                         && next.sequence() >= previous.sequence()
    156                 }
    157                 (Some(_), None) | (None, None) => true,
    158                 (None, Some(_)) => false,
    159             }
    160     }
    161 }
    162 
    163 /// Stable reason a projection can no longer be trusted.
    164 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    165 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    166 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    167 pub enum InvalidationReason {
    168     SourceGenerationChanged,
    169     ProjectionGenerationChanged,
    170     EventIndexManifestChanged,
    171     IntegrityFailure,
    172     OperatorRequested,
    173 }
    174 
    175 /// Durable projection invalidation evidence.
    176 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    177 #[derive(Clone, Debug, Eq, PartialEq)]
    178 pub struct ProjectionInvalidation {
    179     projection_id: ProjectionId,
    180     invalid_generation: ProjectionGeneration,
    181     replacement_generation: ProjectionGeneration,
    182     reason: InvalidationReason,
    183     invalidated_at_unix_ms: u64,
    184 }
    185 
    186 impl ProjectionInvalidation {
    187     pub fn new(
    188         projection_id: ProjectionId,
    189         invalid_generation: ProjectionGeneration,
    190         replacement_generation: ProjectionGeneration,
    191         reason: InvalidationReason,
    192         invalidated_at_unix_ms: u64,
    193     ) -> Result<Self, Error> {
    194         if invalid_generation.0 == replacement_generation.0 || invalidated_at_unix_ms == 0 {
    195             return Err(Error::InvalidProjectionInvalidation);
    196         }
    197         Ok(Self {
    198             projection_id,
    199             invalid_generation,
    200             replacement_generation,
    201             reason,
    202             invalidated_at_unix_ms,
    203         })
    204     }
    205     pub const fn projection_id(&self) -> &ProjectionId {
    206         &self.projection_id
    207     }
    208     pub const fn invalid_generation(&self) -> ProjectionGeneration {
    209         self.invalid_generation
    210     }
    211     pub const fn replacement_generation(&self) -> ProjectionGeneration {
    212         self.replacement_generation
    213     }
    214     pub const fn reason(&self) -> InvalidationReason {
    215         self.reason
    216     }
    217     pub const fn invalidated_at_unix_ms(&self) -> u64 {
    218         self.invalidated_at_unix_ms
    219     }
    220 }
    221 
    222 /// Stable identity of a projection rebuild execution.
    223 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    224 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    225 pub struct RebuildTicketId([u8; 16]);
    226 
    227 impl RebuildTicketId {
    228     pub const fn new(bytes: [u8; 16]) -> Result<Self, Error> {
    229         if bytes16_are_zero(&bytes) {
    230             return Err(Error::InvalidRebuildTicketId);
    231         }
    232         Ok(Self(bytes))
    233     }
    234     pub const fn as_bytes(&self) -> &[u8; 16] {
    235         &self.0
    236     }
    237 }
    238 
    239 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    240 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    241 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    242 pub enum RebuildStage {
    243     Requested,
    244     Running,
    245     Completed,
    246     Failed,
    247 }
    248 
    249 /// Stable, secret-safe classification retained for a failed rebuild.
    250 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    251 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    252 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    253 pub enum RebuildFailure {
    254     ReducerRejected,
    255     SourceChanged,
    256     IntegrityFailure,
    257     PromotionRejected,
    258 }
    259 
    260 /// Optimistic, monotonic projection rebuild state.
    261 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    262 #[derive(Clone, Debug, Eq, PartialEq)]
    263 pub struct RebuildTicket {
    264     ticket_id: RebuildTicketId,
    265     invalidation: ProjectionInvalidation,
    266     revision: ProjectionRevision,
    267     stage: RebuildStage,
    268     source_generation: SourceGeneration,
    269     source_high_water: Option<EventPosition>,
    270     source_digest: RawSourceDigest,
    271     checkpoint: Option<ProjectionCheckpoint>,
    272     failure: Option<RebuildFailure>,
    273     requested_at_unix_ms: u64,
    274     updated_at_unix_ms: u64,
    275 }
    276 
    277 impl RebuildTicket {
    278     pub fn requested(
    279         ticket_id: RebuildTicketId,
    280         invalidation: ProjectionInvalidation,
    281         source_generation: SourceGeneration,
    282         source_high_water: Option<EventPosition>,
    283         source_digest: RawSourceDigest,
    284     ) -> Result<Self, Error> {
    285         if source_high_water.is_some_and(|position| position.generation() != source_generation) {
    286             return Err(Error::SourceGenerationChanged);
    287         }
    288         let at = invalidation.invalidated_at_unix_ms();
    289         Ok(Self {
    290             ticket_id,
    291             invalidation,
    292             revision: ProjectionRevision::INITIAL,
    293             stage: RebuildStage::Requested,
    294             source_generation,
    295             source_high_water,
    296             source_digest,
    297             checkpoint: None,
    298             failure: None,
    299             requested_at_unix_ms: at,
    300             updated_at_unix_ms: at,
    301         })
    302     }
    303 
    304     /// Reconstructs and validates one durable rebuild ticket.
    305     #[allow(clippy::too_many_arguments)]
    306     pub fn from_durable_parts(
    307         ticket_id: RebuildTicketId,
    308         invalidation: ProjectionInvalidation,
    309         revision: ProjectionRevision,
    310         stage: RebuildStage,
    311         source_generation: SourceGeneration,
    312         source_high_water: Option<EventPosition>,
    313         source_digest: RawSourceDigest,
    314         checkpoint: Option<ProjectionCheckpoint>,
    315         failure: Option<RebuildFailure>,
    316         requested_at_unix_ms: u64,
    317         updated_at_unix_ms: u64,
    318     ) -> Result<Self, Error> {
    319         if source_high_water.is_some_and(|position| position.generation() != source_generation)
    320             || requested_at_unix_ms != invalidation.invalidated_at_unix_ms()
    321             || updated_at_unix_ms < requested_at_unix_ms
    322             || matches!(stage, RebuildStage::Requested)
    323                 && (revision != ProjectionRevision::INITIAL
    324                     || updated_at_unix_ms != requested_at_unix_ms)
    325             || !matches!(stage, RebuildStage::Requested) && revision == ProjectionRevision::INITIAL
    326             || matches!(stage, RebuildStage::Requested) && checkpoint.is_some()
    327             || matches!(stage, RebuildStage::Completed) && checkpoint.is_none()
    328             || matches!(stage, RebuildStage::Failed) != failure.is_some()
    329             || !matches!(stage, RebuildStage::Failed) && failure.is_some()
    330             || checkpoint.as_ref().is_some_and(|checkpoint| {
    331                 checkpoint.projection_id() != invalidation.projection_id()
    332                     || checkpoint.generation() != invalidation.replacement_generation()
    333                     || checkpoint
    334                         .source_position()
    335                         .is_some_and(|position| position.generation() != source_generation)
    336                     || checkpoint.updated_at_unix_ms() > updated_at_unix_ms
    337             })
    338         {
    339             return Err(Error::CorruptProjectionRecord);
    340         }
    341         Ok(Self {
    342             ticket_id,
    343             invalidation,
    344             revision,
    345             stage,
    346             source_generation,
    347             source_high_water,
    348             source_digest,
    349             checkpoint,
    350             failure,
    351             requested_at_unix_ms,
    352             updated_at_unix_ms,
    353         })
    354     }
    355     pub const fn ticket_id(&self) -> RebuildTicketId {
    356         self.ticket_id
    357     }
    358     pub const fn invalidation(&self) -> &ProjectionInvalidation {
    359         &self.invalidation
    360     }
    361     pub const fn revision(&self) -> ProjectionRevision {
    362         self.revision
    363     }
    364     pub const fn stage(&self) -> RebuildStage {
    365         self.stage
    366     }
    367     pub const fn source_generation(&self) -> SourceGeneration {
    368         self.source_generation
    369     }
    370     pub const fn source_high_water(&self) -> Option<EventPosition> {
    371         self.source_high_water
    372     }
    373     pub const fn source_digest(&self) -> RawSourceDigest {
    374         self.source_digest
    375     }
    376     pub const fn checkpoint(&self) -> Option<&ProjectionCheckpoint> {
    377         self.checkpoint.as_ref()
    378     }
    379     pub const fn requested_at_unix_ms(&self) -> u64 {
    380         self.requested_at_unix_ms
    381     }
    382     pub const fn updated_at_unix_ms(&self) -> u64 {
    383         self.updated_at_unix_ms
    384     }
    385     pub const fn failure(&self) -> Option<RebuildFailure> {
    386         self.failure
    387     }
    388 
    389     pub fn transition(&self, transition: RebuildTransition) -> Result<Self, Error> {
    390         if transition.ticket_id != self.ticket_id || transition.expected_revision != self.revision {
    391             return Err(Error::ProjectionRevisionConflict);
    392         }
    393         if transition.at_unix_ms < self.updated_at_unix_ms {
    394             return Err(Error::InvalidProjectionTimestamp);
    395         }
    396         let (stage, checkpoint, failure) = match (&self.stage, transition.kind) {
    397             (RebuildStage::Requested, RebuildTransitionKind::Start) => {
    398                 (RebuildStage::Running, None, None)
    399             }
    400             (RebuildStage::Running, RebuildTransitionKind::Checkpoint(checkpoint)) => {
    401                 self.validate_checkpoint(&checkpoint)?;
    402                 if self
    403                     .checkpoint
    404                     .as_ref()
    405                     .is_some_and(|prior| !checkpoint.advances(prior))
    406                 {
    407                     return Err(Error::ProjectionCheckpointRegression);
    408                 }
    409                 (RebuildStage::Running, Some(checkpoint), None)
    410             }
    411             (RebuildStage::Running, RebuildTransitionKind::Complete(checkpoint)) => {
    412                 self.validate_checkpoint(&checkpoint)?;
    413                 if self
    414                     .checkpoint
    415                     .as_ref()
    416                     .is_some_and(|prior| !checkpoint.advances(prior))
    417                 {
    418                     return Err(Error::ProjectionCheckpointRegression);
    419                 }
    420                 (RebuildStage::Completed, Some(checkpoint), None)
    421             }
    422             (
    423                 RebuildStage::Requested | RebuildStage::Running,
    424                 RebuildTransitionKind::Fail(failure),
    425             ) => (RebuildStage::Failed, self.checkpoint.clone(), Some(failure)),
    426             (RebuildStage::Completed | RebuildStage::Failed, _) => {
    427                 return Err(Error::RebuildTicketTerminal);
    428             }
    429             _ => return Err(Error::InvalidRebuildTransition),
    430         };
    431         Ok(Self {
    432             ticket_id: self.ticket_id,
    433             invalidation: self.invalidation.clone(),
    434             revision: self.revision.next()?,
    435             stage,
    436             source_generation: self.source_generation,
    437             source_high_water: self.source_high_water,
    438             source_digest: self.source_digest,
    439             checkpoint,
    440             failure,
    441             requested_at_unix_ms: self.requested_at_unix_ms,
    442             updated_at_unix_ms: transition.at_unix_ms,
    443         })
    444     }
    445 
    446     fn validate_checkpoint(&self, checkpoint: &ProjectionCheckpoint) -> Result<(), Error> {
    447         if checkpoint.projection_id() != self.invalidation.projection_id()
    448             || checkpoint.generation() != self.invalidation.replacement_generation()
    449             || checkpoint
    450                 .source_position()
    451                 .is_some_and(|position| position.generation() != self.source_generation)
    452         {
    453             return Err(Error::ProjectionCheckpointMismatch);
    454         }
    455         Ok(())
    456     }
    457 }
    458 
    459 #[derive(Clone, Debug, Eq, PartialEq)]
    460 pub struct RebuildTransition {
    461     ticket_id: RebuildTicketId,
    462     expected_revision: ProjectionRevision,
    463     at_unix_ms: u64,
    464     kind: RebuildTransitionKind,
    465 }
    466 
    467 #[derive(Clone, Debug, Eq, PartialEq)]
    468 enum RebuildTransitionKind {
    469     Start,
    470     Checkpoint(ProjectionCheckpoint),
    471     Complete(ProjectionCheckpoint),
    472     Fail(RebuildFailure),
    473 }
    474 
    475 impl RebuildTransition {
    476     pub const fn start(
    477         ticket_id: RebuildTicketId,
    478         expected_revision: ProjectionRevision,
    479         at_unix_ms: u64,
    480     ) -> Self {
    481         Self {
    482             ticket_id,
    483             expected_revision,
    484             at_unix_ms,
    485             kind: RebuildTransitionKind::Start,
    486         }
    487     }
    488     pub const fn checkpoint(
    489         ticket_id: RebuildTicketId,
    490         expected_revision: ProjectionRevision,
    491         at_unix_ms: u64,
    492         checkpoint: ProjectionCheckpoint,
    493     ) -> Self {
    494         Self {
    495             ticket_id,
    496             expected_revision,
    497             at_unix_ms,
    498             kind: RebuildTransitionKind::Checkpoint(checkpoint),
    499         }
    500     }
    501     pub const fn complete(
    502         ticket_id: RebuildTicketId,
    503         expected_revision: ProjectionRevision,
    504         at_unix_ms: u64,
    505         checkpoint: ProjectionCheckpoint,
    506     ) -> Self {
    507         Self {
    508             ticket_id,
    509             expected_revision,
    510             at_unix_ms,
    511             kind: RebuildTransitionKind::Complete(checkpoint),
    512         }
    513     }
    514     pub const fn fail(
    515         ticket_id: RebuildTicketId,
    516         expected_revision: ProjectionRevision,
    517         at_unix_ms: u64,
    518         failure: RebuildFailure,
    519     ) -> Self {
    520         Self {
    521             ticket_id,
    522             expected_revision,
    523             at_unix_ms,
    524             kind: RebuildTransitionKind::Fail(failure),
    525         }
    526     }
    527     pub const fn ticket_id(&self) -> RebuildTicketId {
    528         self.ticket_id
    529     }
    530 }
    531 
    532 /// SHA-256 digest of an immutable event-index shard artifact.
    533 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    534 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    535 pub struct ArtifactDigest([u8; 32]);
    536 
    537 impl ArtifactDigest {
    538     pub const fn new(bytes: [u8; 32]) -> Self {
    539         Self(bytes)
    540     }
    541     pub const fn as_bytes(&self) -> &[u8; 32] {
    542         &self.0
    543     }
    544 }
    545 
    546 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    547 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    548 pub struct EventIndexShardId(String);
    549 
    550 impl EventIndexShardId {
    551     pub fn parse(value: impl Into<String>) -> Result<Self, Error> {
    552         let value = value.into();
    553         if !valid_label(value.as_str(), EVENT_INDEX_SHARD_ID_MAX_BYTES) {
    554             return Err(Error::InvalidEventIndexShardId);
    555         }
    556         Ok(Self(value))
    557     }
    558     pub fn as_str(&self) -> &str {
    559         self.0.as_str()
    560     }
    561 }
    562 
    563 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    564 #[derive(Clone, Debug, Eq, PartialEq)]
    565 pub struct EventIdRange {
    566     first: EventId,
    567     last: EventId,
    568 }
    569 
    570 impl EventIdRange {
    571     pub fn new(first: EventId, last: EventId) -> Result<Self, Error> {
    572         if first > last {
    573             return Err(Error::InvalidEventIndexRange);
    574         }
    575         Ok(Self { first, last })
    576     }
    577     pub const fn first(&self) -> &EventId {
    578         &self.first
    579     }
    580     pub const fn last(&self) -> &EventId {
    581         &self.last
    582     }
    583 }
    584 
    585 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    586 #[derive(Clone, Debug, Eq, PartialEq)]
    587 pub struct EventIndexShard {
    588     shard_id: EventIndexShardId,
    589     artifact_path: String,
    590     event_count: u32,
    591     event_ids: EventIdRange,
    592     first_published_at_unix_s: u64,
    593     last_published_at_unix_s: u64,
    594     sha256: ArtifactDigest,
    595 }
    596 
    597 impl EventIndexShard {
    598     #[allow(clippy::too_many_arguments)]
    599     pub fn new(
    600         shard_id: EventIndexShardId,
    601         artifact_path: impl Into<String>,
    602         event_count: u32,
    603         event_ids: EventIdRange,
    604         first_published_at_unix_s: u64,
    605         last_published_at_unix_s: u64,
    606         sha256: ArtifactDigest,
    607     ) -> Result<Self, Error> {
    608         let artifact_path = artifact_path.into();
    609         if !valid_artifact_path(artifact_path.as_str()) {
    610             return Err(Error::InvalidEventIndexArtifactPath);
    611         }
    612         if event_count == 0 {
    613             return Err(Error::InvalidEventIndexShardCount);
    614         }
    615         if first_published_at_unix_s == 0 || last_published_at_unix_s < first_published_at_unix_s {
    616             return Err(Error::InvalidEventIndexTimestamp);
    617         }
    618         Ok(Self {
    619             shard_id,
    620             artifact_path,
    621             event_count,
    622             event_ids,
    623             first_published_at_unix_s,
    624             last_published_at_unix_s,
    625             sha256,
    626         })
    627     }
    628     pub const fn shard_id(&self) -> &EventIndexShardId {
    629         &self.shard_id
    630     }
    631     pub fn artifact_path(&self) -> &str {
    632         self.artifact_path.as_str()
    633     }
    634     pub const fn event_count(&self) -> u32 {
    635         self.event_count
    636     }
    637     pub const fn event_ids(&self) -> &EventIdRange {
    638         &self.event_ids
    639     }
    640     pub const fn first_published_at_unix_s(&self) -> u64 {
    641         self.first_published_at_unix_s
    642     }
    643     pub const fn last_published_at_unix_s(&self) -> u64 {
    644         self.last_published_at_unix_s
    645     }
    646     pub const fn sha256(&self) -> ArtifactDigest {
    647         self.sha256
    648     }
    649 }
    650 
    651 /// Validated, immutable event-index artifact inventory.
    652 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    653 #[derive(Clone, Debug, Eq, PartialEq)]
    654 pub struct EventIndexManifest {
    655     generation: ProjectionGeneration,
    656     total_events: u64,
    657     target_shard_size: u32,
    658     first_published_at_unix_s: u64,
    659     last_published_at_unix_s: u64,
    660     shards: Vec<EventIndexShard>,
    661 }
    662 
    663 impl EventIndexManifest {
    664     pub fn new(
    665         generation: ProjectionGeneration,
    666         total_events: u64,
    667         target_shard_size: u32,
    668         first_published_at_unix_s: u64,
    669         last_published_at_unix_s: u64,
    670         shards: Vec<EventIndexShard>,
    671     ) -> Result<Self, Error> {
    672         if shards.is_empty() || shards.len() > EVENT_INDEX_SHARDS_MAX {
    673             return Err(Error::InvalidEventIndexShardCount);
    674         }
    675         if target_shard_size == 0 || total_events == 0 {
    676             return Err(Error::InvalidEventIndexManifest);
    677         }
    678         let sum = shards.iter().try_fold(0_u64, |sum, shard| {
    679             if shard.event_count() > target_shard_size {
    680                 return Err(Error::InvalidEventIndexManifest);
    681             }
    682             sum.checked_add(u64::from(shard.event_count()))
    683                 .ok_or(Error::InvalidEventIndexManifest)
    684         })?;
    685         if sum != total_events
    686             || first_published_at_unix_s != shards[0].first_published_at_unix_s()
    687             || last_published_at_unix_s != shards[shards.len() - 1].last_published_at_unix_s()
    688         {
    689             return Err(Error::InvalidEventIndexManifest);
    690         }
    691         let mut shard_ids = BTreeSet::new();
    692         let mut artifact_paths = BTreeSet::new();
    693         if shards.iter().any(|shard| {
    694             !shard_ids.insert(shard.shard_id()) || !artifact_paths.insert(shard.artifact_path())
    695         }) {
    696             return Err(Error::InvalidEventIndexManifest);
    697         }
    698         for pair in shards.windows(2) {
    699             if pair[0].shard_id() >= pair[1].shard_id()
    700                 || pair[0].event_ids().last() >= pair[1].event_ids().first()
    701                 || pair[0].last_published_at_unix_s() > pair[1].first_published_at_unix_s()
    702             {
    703                 return Err(Error::InvalidEventIndexManifest);
    704             }
    705         }
    706         Ok(Self {
    707             generation,
    708             total_events,
    709             target_shard_size,
    710             first_published_at_unix_s,
    711             last_published_at_unix_s,
    712             shards,
    713         })
    714     }
    715     pub const fn generation(&self) -> ProjectionGeneration {
    716         self.generation
    717     }
    718     pub const fn total_events(&self) -> u64 {
    719         self.total_events
    720     }
    721     pub const fn target_shard_size(&self) -> u32 {
    722         self.target_shard_size
    723     }
    724     pub const fn first_published_at_unix_s(&self) -> u64 {
    725         self.first_published_at_unix_s
    726     }
    727     pub const fn last_published_at_unix_s(&self) -> u64 {
    728         self.last_published_at_unix_s
    729     }
    730     pub fn shards(&self) -> &[EventIndexShard] {
    731         self.shards.as_slice()
    732     }
    733 }
    734 
    735 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    736 #[derive(Clone, Debug, Eq, PartialEq)]
    737 pub struct EventIndexShardCheckpoint {
    738     shard_id: EventIndexShardId,
    739     last_created_at_unix_s: u64,
    740     last_event_id: Option<EventId>,
    741     cursor: Option<String>,
    742 }
    743 
    744 impl EventIndexShardCheckpoint {
    745     pub fn new(
    746         shard_id: EventIndexShardId,
    747         last_created_at_unix_s: u64,
    748         last_event_id: Option<EventId>,
    749         cursor: Option<String>,
    750     ) -> Result<Self, Error> {
    751         if last_created_at_unix_s == 0 {
    752             return Err(Error::InvalidEventIndexTimestamp);
    753         }
    754         if let Some(value) = cursor.as_deref()
    755             && (value.is_empty()
    756                 || value.len() > EVENT_INDEX_CURSOR_MAX_BYTES
    757                 || value != value.trim()
    758                 || value.chars().any(char::is_control))
    759         {
    760             return Err(Error::InvalidEventIndexCursor);
    761         }
    762         Ok(Self {
    763             shard_id,
    764             last_created_at_unix_s,
    765             last_event_id,
    766             cursor,
    767         })
    768     }
    769     pub const fn shard_id(&self) -> &EventIndexShardId {
    770         &self.shard_id
    771     }
    772     pub const fn last_created_at_unix_s(&self) -> u64 {
    773         self.last_created_at_unix_s
    774     }
    775     pub const fn last_event_id(&self) -> Option<&EventId> {
    776         self.last_event_id.as_ref()
    777     }
    778     pub fn cursor(&self) -> Option<&str> {
    779         self.cursor.as_deref()
    780     }
    781 }
    782 
    783 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    784 #[derive(Clone, Debug, Eq, PartialEq)]
    785 pub struct EventIndexCheckpoint {
    786     generation: ProjectionGeneration,
    787     generated_at_unix_ms: u64,
    788     shards: Vec<EventIndexShardCheckpoint>,
    789 }
    790 
    791 impl EventIndexCheckpoint {
    792     pub fn new(
    793         generation: ProjectionGeneration,
    794         generated_at_unix_ms: u64,
    795         mut shards: Vec<EventIndexShardCheckpoint>,
    796     ) -> Result<Self, Error> {
    797         if generated_at_unix_ms == 0 || shards.len() > EVENT_INDEX_SHARDS_MAX {
    798             return Err(Error::InvalidEventIndexCheckpoint);
    799         }
    800         shards.sort_by(|left, right| left.shard_id().cmp(right.shard_id()));
    801         if shards
    802             .windows(2)
    803             .any(|pair| pair[0].shard_id() == pair[1].shard_id())
    804         {
    805             return Err(Error::DuplicateEventIndexShard);
    806         }
    807         Ok(Self {
    808             generation,
    809             generated_at_unix_ms,
    810             shards,
    811         })
    812     }
    813     pub const fn generation(&self) -> ProjectionGeneration {
    814         self.generation
    815     }
    816     pub const fn generated_at_unix_ms(&self) -> u64 {
    817         self.generated_at_unix_ms
    818     }
    819     pub fn shards(&self) -> &[EventIndexShardCheckpoint] {
    820         self.shards.as_slice()
    821     }
    822     pub fn shard(&self, id: &EventIndexShardId) -> Option<&EventIndexShardCheckpoint> {
    823         self.shards
    824             .binary_search_by(|candidate| candidate.shard_id().cmp(id))
    825             .ok()
    826             .map(|index| &self.shards[index])
    827     }
    828 }
    829 
    830 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    831 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    832 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    833 pub enum ProjectionHealth {
    834     Ready,
    835     Invalidated,
    836     Rebuilding,
    837     Failed,
    838 }
    839 
    840 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    841 #[derive(Clone, Debug, Eq, PartialEq)]
    842 pub struct ProjectionStatus {
    843     projection_id: ProjectionId,
    844     generation: ProjectionGeneration,
    845     health: ProjectionHealth,
    846     checkpoint: Option<ProjectionCheckpoint>,
    847     active_rebuild: Option<RebuildTicketId>,
    848 }
    849 
    850 /// Maximum UTF-8 bytes in one materialized projection document key.
    851 pub const PROJECTION_DOCUMENT_KEY_MAX_BYTES: usize = 512;
    852 /// Maximum bytes in one materialized projection document value.
    853 pub const PROJECTION_DOCUMENT_VALUE_MAX_BYTES: usize = 16 * 1024 * 1024;
    854 
    855 /// One backend-neutral, opaque materialized projection document.
    856 ///
    857 /// Projection owners define the value encoding. Storage verifies its digest
    858 /// and treats the bytes as opaque so product-specific DTOs do not leak into
    859 /// the generic persistence boundary.
    860 #[derive(Clone, Debug, Eq, PartialEq)]
    861 pub struct ProjectionDocument {
    862     key: String,
    863     value: Vec<u8>,
    864     value_sha256: [u8; 32],
    865 }
    866 
    867 impl ProjectionDocument {
    868     pub fn new(key: String, value: Vec<u8>) -> Result<Self, Error> {
    869         if !valid_document_key(&key)
    870             || value.is_empty()
    871             || value.len() > PROJECTION_DOCUMENT_VALUE_MAX_BYTES
    872         {
    873             return Err(Error::InvalidProjectionDocument);
    874         }
    875         let value_sha256 = Sha256::digest(&value).into();
    876         Ok(Self {
    877             key,
    878             value,
    879             value_sha256,
    880         })
    881     }
    882 
    883     pub fn from_stored_parts(
    884         key: String,
    885         value: Vec<u8>,
    886         value_sha256: [u8; 32],
    887     ) -> Result<Self, Error> {
    888         let document = Self::new(key, value)?;
    889         if document.value_sha256 != value_sha256 {
    890             return Err(Error::CorruptProjectionDocument);
    891         }
    892         Ok(document)
    893     }
    894 
    895     pub fn key(&self) -> &str {
    896         &self.key
    897     }
    898 
    899     pub fn value(&self) -> &[u8] {
    900         &self.value
    901     }
    902 
    903     pub const fn value_sha256(&self) -> &[u8; 32] {
    904         &self.value_sha256
    905     }
    906 }
    907 
    908 /// One immutable, durable frozen-query snapshot.
    909 #[derive(Clone, Debug, Eq, PartialEq)]
    910 pub struct ProjectionSnapshot {
    911     projection_id: ProjectionId,
    912     snapshot_id: [u8; 32],
    913     generation: ProjectionGeneration,
    914     created_at_unix_ms: u64,
    915     value: Vec<u8>,
    916     value_sha256: [u8; 32],
    917 }
    918 
    919 impl ProjectionSnapshot {
    920     pub fn new(
    921         projection_id: ProjectionId,
    922         snapshot_id: [u8; 32],
    923         generation: ProjectionGeneration,
    924         created_at_unix_ms: u64,
    925         value: Vec<u8>,
    926     ) -> Result<Self, Error> {
    927         if snapshot_id.iter().all(|byte| *byte == 0)
    928             || created_at_unix_ms == 0
    929             || value.is_empty()
    930             || value.len() > PROJECTION_DOCUMENT_VALUE_MAX_BYTES
    931         {
    932             return Err(Error::InvalidProjectionSnapshot);
    933         }
    934         let value_sha256 = Sha256::digest(&value).into();
    935         Ok(Self {
    936             projection_id,
    937             snapshot_id,
    938             generation,
    939             created_at_unix_ms,
    940             value,
    941             value_sha256,
    942         })
    943     }
    944 
    945     pub fn from_stored_parts(
    946         projection_id: ProjectionId,
    947         snapshot_id: [u8; 32],
    948         generation: ProjectionGeneration,
    949         created_at_unix_ms: u64,
    950         value: Vec<u8>,
    951         value_sha256: [u8; 32],
    952     ) -> Result<Self, Error> {
    953         let snapshot = Self::new(
    954             projection_id,
    955             snapshot_id,
    956             generation,
    957             created_at_unix_ms,
    958             value,
    959         )?;
    960         if snapshot.value_sha256 != value_sha256 {
    961             return Err(Error::CorruptProjectionDocument);
    962         }
    963         Ok(snapshot)
    964     }
    965 
    966     pub const fn projection_id(&self) -> &ProjectionId {
    967         &self.projection_id
    968     }
    969 
    970     pub const fn snapshot_id(&self) -> &[u8; 32] {
    971         &self.snapshot_id
    972     }
    973 
    974     pub const fn generation(&self) -> ProjectionGeneration {
    975         self.generation
    976     }
    977 
    978     pub const fn created_at_unix_ms(&self) -> u64 {
    979         self.created_at_unix_ms
    980     }
    981 
    982     pub fn value(&self) -> &[u8] {
    983         &self.value
    984     }
    985 
    986     pub const fn value_sha256(&self) -> &[u8; 32] {
    987         &self.value_sha256
    988     }
    989 }
    990 
    991 impl ProjectionStatus {
    992     pub fn new(
    993         projection_id: ProjectionId,
    994         generation: ProjectionGeneration,
    995         health: ProjectionHealth,
    996         checkpoint: Option<ProjectionCheckpoint>,
    997         active_rebuild: Option<RebuildTicketId>,
    998     ) -> Result<Self, Error> {
    999         if checkpoint.as_ref().is_some_and(|value| {
   1000             value.projection_id() != &projection_id || value.generation() != generation
   1001         }) || (health == ProjectionHealth::Rebuilding) != active_rebuild.is_some()
   1002         {
   1003             return Err(Error::CorruptProjectionRecord);
   1004         }
   1005         Ok(Self {
   1006             projection_id,
   1007             generation,
   1008             health,
   1009             checkpoint,
   1010             active_rebuild,
   1011         })
   1012     }
   1013     pub const fn projection_id(&self) -> &ProjectionId {
   1014         &self.projection_id
   1015     }
   1016     pub const fn generation(&self) -> ProjectionGeneration {
   1017         self.generation
   1018     }
   1019     pub const fn health(&self) -> ProjectionHealth {
   1020         self.health
   1021     }
   1022     pub const fn checkpoint(&self) -> Option<&ProjectionCheckpoint> {
   1023         self.checkpoint.as_ref()
   1024     }
   1025     pub const fn active_rebuild(&self) -> Option<RebuildTicketId> {
   1026         self.active_rebuild
   1027     }
   1028 }
   1029 
   1030 /// Backend-neutral projection coordination SPI.
   1031 pub trait ProjectionStore: radroots_transport::host::HostBound {
   1032     /// Registers one exact derived-cache identity under an immutable store budget.
   1033     /// Configured identities cannot create new legacy whole-view snapshots.
   1034     fn configure_projection_cache(
   1035         &self,
   1036         _id: ProjectionId,
   1037         _limits: cache::ProjectionCacheLimits,
   1038     ) -> BoxFuture<'_, Result<cache::ProjectionCacheUsage, Error>> {
   1039         Box::pin(async { Err(Error::BackendUnavailable) })
   1040     }
   1041     /// Retires an exact obsolete generation without touching canonical or authored data.
   1042     /// An unconfigured legacy checkpoint must be explicitly invalidated without an
   1043     /// active rebuild; retirement retains its refusal status and bytes, and grants
   1044     /// no collection authority. Source and expected-active fences still apply.
   1045     fn retire_projection_generation(
   1046         &self,
   1047         _scope: cache::ProjectionCacheScope,
   1048     ) -> BoxFuture<'_, Result<cache::ProjectionCacheUsage, Error>> {
   1049         Box::pin(async { Err(Error::BackendUnavailable) })
   1050     }
   1051     /// Collects at most64 exact-generation derived rows under a source/active fence.
   1052     fn collect_projection_cache(
   1053         &self,
   1054         _scope: cache::ProjectionCacheScope,
   1055     ) -> BoxFuture<'_, Result<cache::ProjectionCacheCollection, Error>> {
   1056         Box::pin(async { Err(Error::BackendUnavailable) })
   1057     }
   1058     /// Collects at most64 derived rows from one indexed retired generation.
   1059     /// The registered owner, current source and active identity are fenced under
   1060     /// the same provider transaction or lock; `more` includes other retired work.
   1061     fn collect_retired_projection_cache(
   1062         &self,
   1063         _id: ProjectionId,
   1064         _source: crate::event::EventSourceToken,
   1065         _expected_active: Option<ProjectionGeneration>,
   1066     ) -> BoxFuture<'_, Result<cache::ProjectionCacheCollection, Error>> {
   1067         Box::pin(async { Err(Error::BackendUnavailable) })
   1068     }
   1069     /// Retires only obsolete snapshots, preserving documents and other owner state.
   1070     /// A current target must be explicitly Invalidated without a rebuild; live
   1071     /// staging is refused. Exact registered-owner/source/active fences apply.
   1072     fn collect_obsolete_projection_snapshots(
   1073         &self,
   1074         _scope: cache::ProjectionCacheScope,
   1075     ) -> BoxFuture<'_, Result<cache::ProjectionCacheCollection, Error>> {
   1076         Box::pin(async { Err(Error::BackendUnavailable) })
   1077     }
   1078     /// Atomically stages a bounded batch under a durable source and generation fence.
   1079     fn put_projection_batch(
   1080         &self,
   1081         _batch: batch::ProjectionDocumentBatch,
   1082     ) -> BoxFuture<'_, Result<(), Error>> {
   1083         Box::pin(async { Err(Error::BackendUnavailable) })
   1084     }
   1085     /// Writes the final bounded batch and publishes its complete generation atomically.
   1086     fn promote_projection_batch(
   1087         &self,
   1088         _batch: batch::ProjectionDocumentBatch,
   1089         _checkpoint: ProjectionCheckpoint,
   1090     ) -> BoxFuture<'_, Result<ProjectionStatus, Error>> {
   1091         Box::pin(async { Err(Error::BackendUnavailable) })
   1092     }
   1093     /// Reads an exact active generation under one canonical source fence.
   1094     fn query_projection_documents_at(
   1095         &self,
   1096         _query: document_query::ProjectionDocumentQuery,
   1097         _source: crate::event::EventSourceToken,
   1098         _active: ProjectionGeneration,
   1099     ) -> BoxFuture<'_, Result<document_query::ProjectionDocumentPage, Error>> {
   1100         Box::pin(async { Err(Error::BackendUnavailable) })
   1101     }
   1102     fn status(
   1103         &self,
   1104         projection_id: ProjectionId,
   1105     ) -> BoxFuture<'_, Result<Option<ProjectionStatus>, Error>>;
   1106     fn checkpoint(
   1107         &self,
   1108         checkpoint: ProjectionCheckpoint,
   1109     ) -> BoxFuture<'_, Result<ProjectionStatus, Error>>;
   1110     fn invalidate(
   1111         &self,
   1112         invalidation: ProjectionInvalidation,
   1113     ) -> BoxFuture<'_, Result<ProjectionStatus, Error>>;
   1114     /// Returns the latest durable invalidation selecting a replacement generation.
   1115     fn invalidation(
   1116         &self,
   1117         projection_id: ProjectionId,
   1118         replacement_generation: ProjectionGeneration,
   1119     ) -> BoxFuture<'_, Result<Option<ProjectionInvalidation>, Error>>;
   1120     fn request_rebuild(&self, ticket: RebuildTicket)
   1121     -> BoxFuture<'_, Result<RebuildTicket, Error>>;
   1122     /// Returns one durable rebuild execution by identity.
   1123     fn rebuild(
   1124         &self,
   1125         ticket_id: RebuildTicketId,
   1126     ) -> BoxFuture<'_, Result<Option<RebuildTicket>, Error>>;
   1127     fn transition_rebuild(
   1128         &self,
   1129         transition: RebuildTransition,
   1130     ) -> BoxFuture<'_, Result<RebuildTicket, Error>>;
   1131     fn event_index_manifest(
   1132         &self,
   1133         generation: ProjectionGeneration,
   1134     ) -> BoxFuture<'_, Result<Option<EventIndexManifest>, Error>>;
   1135     fn put_event_index_manifest(
   1136         &self,
   1137         manifest: EventIndexManifest,
   1138     ) -> BoxFuture<'_, Result<(), Error>>;
   1139     fn event_index_checkpoint(
   1140         &self,
   1141         generation: ProjectionGeneration,
   1142     ) -> BoxFuture<'_, Result<Option<EventIndexCheckpoint>, Error>>;
   1143     fn put_event_index_checkpoint(
   1144         &self,
   1145         checkpoint: EventIndexCheckpoint,
   1146     ) -> BoxFuture<'_, Result<(), Error>>;
   1147     /// Replaces one named materialized document for a projection generation.
   1148     fn put_projection_document(
   1149         &self,
   1150         projection_id: ProjectionId,
   1151         generation: ProjectionGeneration,
   1152         document: ProjectionDocument,
   1153     ) -> BoxFuture<'_, Result<(), Error>>;
   1154     /// Loads one named materialized document for an exact generation.
   1155     fn projection_document(
   1156         &self,
   1157         projection_id: ProjectionId,
   1158         generation: ProjectionGeneration,
   1159         key: String,
   1160     ) -> BoxFuture<'_, Result<Option<ProjectionDocument>, Error>>;
   1161     /// Inventories are live bounded scans. Unsupported backends fail explicitly.
   1162     fn query_projection_documents(
   1163         &self,
   1164         _query: document_query::ProjectionDocumentQuery,
   1165     ) -> BoxFuture<'_, Result<document_query::ProjectionDocumentPage, Error>> {
   1166         Box::pin(async { Err(Error::BackendUnavailable) })
   1167     }
   1168     /// Persists one immutable frozen-query snapshot idempotently.
   1169     fn put_projection_snapshot(
   1170         &self,
   1171         snapshot: ProjectionSnapshot,
   1172     ) -> BoxFuture<'_, Result<(), Error>>;
   1173     /// Loads one immutable frozen-query snapshot by exact identity.
   1174     fn projection_snapshot(
   1175         &self,
   1176         projection_id: ProjectionId,
   1177         snapshot_id: [u8; 32],
   1178     ) -> BoxFuture<'_, Result<Option<ProjectionSnapshot>, Error>>;
   1179 }
   1180 
   1181 fn valid_label(value: &str, max: usize) -> bool {
   1182     !value.is_empty()
   1183         && value.len() <= max
   1184         && value == value.trim()
   1185         && value.bytes().all(|byte| {
   1186             byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-' | b'.')
   1187         })
   1188 }
   1189 
   1190 pub(crate) fn valid_document_key(value: &str) -> bool {
   1191     !value.is_empty()
   1192         && value.len() <= PROJECTION_DOCUMENT_KEY_MAX_BYTES
   1193         && value == value.trim()
   1194         && !value.chars().any(char::is_control)
   1195 }
   1196 
   1197 fn valid_artifact_path(value: &str) -> bool {
   1198     !value.is_empty()
   1199         && value.len() <= EVENT_INDEX_ARTIFACT_PATH_MAX_BYTES
   1200         && value == value.trim()
   1201         && !value.starts_with('/')
   1202         && !value.contains('\\')
   1203         && value.split('/').all(|part| {
   1204             !part.is_empty() && part != "." && part != ".." && !part.chars().any(char::is_control)
   1205         })
   1206 }
   1207 
   1208 const fn bytes16_are_zero(bytes: &[u8; 16]) -> bool {
   1209     let mut index = 0;
   1210     while index < bytes.len() {
   1211         if bytes[index] != 0 {
   1212             return false;
   1213         }
   1214         index += 1;
   1215     }
   1216     true
   1217 }
   1218 
   1219 const fn bytes32_are_zero(bytes: &[u8; 32]) -> bool {
   1220     let mut index = 0;
   1221     while index < bytes.len() {
   1222         if bytes[index] != 0 {
   1223             return false;
   1224         }
   1225         index += 1;
   1226     }
   1227     true
   1228 }
   1229 
   1230 #[cfg(test)]
   1231 mod materialized_tests {
   1232     use super::*;
   1233 
   1234     #[test]
   1235     fn materialized_document_and_snapshot_bounds_and_digests_fail_closed() {
   1236         assert_eq!(
   1237             ProjectionDocument::new(String::new(), vec![1]),
   1238             Err(Error::InvalidProjectionDocument)
   1239         );
   1240         assert_eq!(
   1241             ProjectionDocument::new("key".into(), Vec::new()),
   1242             Err(Error::InvalidProjectionDocument)
   1243         );
   1244         assert_eq!(
   1245             ProjectionDocument::new("k".repeat(PROJECTION_DOCUMENT_KEY_MAX_BYTES + 1), vec![1],),
   1246             Err(Error::InvalidProjectionDocument)
   1247         );
   1248         assert_eq!(
   1249             ProjectionDocument::new(" key".into(), vec![1]),
   1250             Err(Error::InvalidProjectionDocument)
   1251         );
   1252         assert_eq!(
   1253             ProjectionDocument::new("key\npart".into(), vec![1]),
   1254             Err(Error::InvalidProjectionDocument)
   1255         );
   1256         assert_eq!(
   1257             ProjectionDocument::new(
   1258                 "key".into(),
   1259                 vec![0; PROJECTION_DOCUMENT_VALUE_MAX_BYTES + 1],
   1260             ),
   1261             Err(Error::InvalidProjectionDocument)
   1262         );
   1263         let document = ProjectionDocument::new("key".into(), vec![1, 2]).unwrap();
   1264         assert_eq!(document.key(), "key");
   1265         assert_eq!(document.value(), [1, 2]);
   1266         assert_eq!(document.value_sha256().len(), 32);
   1267         assert_eq!(
   1268             ProjectionDocument::from_stored_parts("key".into(), vec![1, 2], [9; 32]),
   1269             Err(Error::CorruptProjectionDocument)
   1270         );
   1271 
   1272         let projection_id = ProjectionId::parse("today").unwrap();
   1273         let generation = ProjectionGeneration::new([1; 32]).unwrap();
   1274         assert_eq!(
   1275             ProjectionSnapshot::new(projection_id.clone(), [0; 32], generation, 1, vec![1]),
   1276             Err(Error::InvalidProjectionSnapshot)
   1277         );
   1278         assert_eq!(
   1279             ProjectionSnapshot::new(projection_id.clone(), [2; 32], generation, 0, vec![1]),
   1280             Err(Error::InvalidProjectionSnapshot)
   1281         );
   1282         assert_eq!(
   1283             ProjectionSnapshot::new(projection_id.clone(), [2; 32], generation, 1, Vec::new()),
   1284             Err(Error::InvalidProjectionSnapshot)
   1285         );
   1286         assert_eq!(
   1287             ProjectionSnapshot::new(
   1288                 projection_id.clone(),
   1289                 [2; 32],
   1290                 generation,
   1291                 1,
   1292                 vec![0; PROJECTION_DOCUMENT_VALUE_MAX_BYTES + 1],
   1293             ),
   1294             Err(Error::InvalidProjectionSnapshot)
   1295         );
   1296         let snapshot =
   1297             ProjectionSnapshot::new(projection_id.clone(), [2; 32], generation, 1, vec![1])
   1298                 .unwrap();
   1299         assert_eq!(snapshot.projection_id(), &projection_id);
   1300         assert_eq!(snapshot.snapshot_id(), &[2; 32]);
   1301         assert_eq!(snapshot.generation(), generation);
   1302         assert_eq!(snapshot.created_at_unix_ms(), 1);
   1303         assert_eq!(snapshot.value(), [1]);
   1304         assert_eq!(snapshot.value_sha256().len(), 32);
   1305         assert_eq!(
   1306             ProjectionSnapshot::from_stored_parts(
   1307                 projection_id,
   1308                 [2; 32],
   1309                 generation,
   1310                 1,
   1311                 vec![1],
   1312                 [9; 32],
   1313             ),
   1314             Err(Error::CorruptProjectionDocument)
   1315         );
   1316     }
   1317 }