nizaam-core 1.0.1

Domain-agnostic Rust infrastructure core for building secure, observable, reliable, and extensible Nizaam engines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Storage abstraction for artifact versions and their lifecycle metadata.
//!
//! `ArtifactStore` owns storage mechanics, not artifact domain semantics.
//! The in-memory implementation exists for Core tests and deterministic
//! behavior. Persistent or remote storage implementations can be supplied
//! by infrastructure layers.

use std::collections::BTreeMap;
use std::sync::{Arc, RwLock};

use crate::artifact::integrity::IntegrityProof;
use crate::artifact::lifecycle::{LifecycleState, transition};
use crate::artifact::version::{
    ArtifactVersion, ArtifactVersionRecord, ArtifactVersionRestoreError,
};
use crate::identity::ArtifactId;

/// Errors produced by artifact storage operations.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StoreError {
    /// The artifact version already exists.
    AlreadyExists,

    /// The requested artifact version does not exist.
    NotFound,

    /// The supplied alias is empty or whitespace-only.
    InvalidAlias,

    /// The supplied version is empty or whitespace-only.
    InvalidVersion,

    /// The requested lifecycle transition is not allowed.
    InvalidLifecycleTransition {
        from: LifecycleState,
        to: LifecycleState,
    },

    /// Publishing must use the dedicated publication operation.
    PublicationRequired,

    /// The artifact content reference is invalid.
    InvalidContentReference,

    /// The persisted artifact version could not be trusted and restored.
    RestorationFailed,

    /// The supplied integrity proof does not match the recorded content.
    IntegrityFailure,

    /// Internal synchronization state could not be acquired.
    LockPoisoned,
}

impl std::fmt::Display for StoreError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::AlreadyExists => write!(formatter, "artifact version already exists"),
            Self::NotFound => write!(formatter, "artifact version not found"),
            Self::InvalidAlias => write!(formatter, "artifact alias is invalid"),
            Self::InvalidVersion => write!(formatter, "artifact version is invalid"),
            Self::InvalidLifecycleTransition { from, to } => write!(
                formatter,
                "invalid artifact lifecycle transition from {:?} to {:?}",
                from, to
            ),
            Self::PublicationRequired => write!(
                formatter,
                "artifact publication requires the dedicated publication operation"
            ),
            Self::InvalidContentReference => {
                write!(formatter, "artifact content reference is invalid")
            }
            Self::RestorationFailed => write!(formatter, "artifact version restoration failed"),
            Self::IntegrityFailure => {
                write!(formatter, "artifact content integrity verification failed")
            }
            Self::LockPoisoned => write!(formatter, "artifact store lock is poisoned"),
        }
    }
}

impl std::error::Error for StoreError {}

fn map_restoration_error(error: ArtifactVersionRestoreError) -> StoreError {
    match error {
        ArtifactVersionRestoreError::InvalidContentReference => StoreError::InvalidContentReference,
        ArtifactVersionRestoreError::InvalidVersion
        | ArtifactVersionRestoreError::InvalidLifecycleTransition { .. } => {
            StoreError::RestorationFailed
        }
    }
}

/// Storage abstraction for artifact versions.
pub trait ArtifactStore: Send + Sync {
    /// Stores a new artifact version.
    fn store(&self, version: ArtifactVersion) -> Result<(), StoreError>;

    /// Retrieves one exact version.
    fn get(
        &self,
        artifact_id: &ArtifactId,
        version: &str,
    ) -> Result<Option<ArtifactVersion>, StoreError>;

    /// Lists all versions belonging to an artifact.
    ///
    /// No ordering semantics are implied.
    fn list_versions(&self, artifact_id: &ArtifactId) -> Result<Vec<ArtifactVersion>, StoreError>;

    /// Atomically applies a valid lifecycle transition and returns the
    /// resulting version.
    ///
    /// The `Validated → Published` transition is reserved for
    /// [`ArtifactStore::publish_validated`].
    fn transition_lifecycle(
        &self,
        artifact_id: &ArtifactId,
        version: &str,
        target: LifecycleState,
    ) -> Result<ArtifactVersion, StoreError>;

    /// Atomically publishes a version only when its stored state is
    /// `Validated`.
    ///
    /// This compare-and-transition primitive is the only store operation that
    /// can enter `Published`, preventing callers from bypassing publication
    /// prerequisites through a generic lifecycle update.
    fn publish_validated(
        &self,
        artifact_id: &ArtifactId,
        version: &str,
        proof: &IntegrityProof,
    ) -> Result<ArtifactVersion, StoreError>;

    /// Associates an alias with one exact version.
    fn set_alias(
        &self,
        artifact_id: &ArtifactId,
        alias: &str,
        version: &str,
    ) -> Result<(), StoreError>;

    /// Resolves an alias to its exact version identifier.
    fn resolve_alias(
        &self,
        artifact_id: &ArtifactId,
        alias: &str,
    ) -> Result<Option<String>, StoreError>;

    /// Removes an alias without removing the underlying version.
    fn remove_alias(&self, artifact_id: &ArtifactId, alias: &str) -> Result<bool, StoreError>;
}

/// Deterministic in-memory artifact store.
#[derive(Clone, Default)]
pub struct InMemoryArtifactStore {
    versions: Arc<RwLock<BTreeMap<(String, String), ArtifactVersionRecord>>>,
    aliases: Arc<RwLock<BTreeMap<(String, String), String>>>,
}

impl InMemoryArtifactStore {
    /// Creates an empty in-memory artifact store.
    pub fn new() -> Self {
        Self::default()
    }
}

impl ArtifactStore for InMemoryArtifactStore {
    fn store(&self, version: ArtifactVersion) -> Result<(), StoreError> {
        if version.version().trim().is_empty() {
            return Err(StoreError::InvalidVersion);
        }

        if !version.content().is_valid() {
            return Err(StoreError::InvalidContentReference);
        }

        let key = (
            version.artifact_id().as_str().to_string(),
            version.version().to_string(),
        );

        let mut versions = self
            .versions
            .write()
            .map_err(|_| StoreError::LockPoisoned)?;

        if versions.contains_key(&key) {
            return Err(StoreError::AlreadyExists);
        }

        versions.insert(key, (&version).into());
        Ok(())
    }

    fn get(
        &self,
        artifact_id: &ArtifactId,
        version: &str,
    ) -> Result<Option<ArtifactVersion>, StoreError> {
        if version.trim().is_empty() {
            return Err(StoreError::InvalidVersion);
        }

        let versions = self.versions.read().map_err(|_| StoreError::LockPoisoned)?;

        versions
            .get(&(artifact_id.as_str().to_string(), version.to_string()))
            .cloned()
            .map(ArtifactVersion::restore)
            .transpose()
            .map_err(map_restoration_error)
    }

    fn list_versions(&self, artifact_id: &ArtifactId) -> Result<Vec<ArtifactVersion>, StoreError> {
        let versions = self.versions.read().map_err(|_| StoreError::LockPoisoned)?;

        versions
            .iter()
            .filter(|((stored_artifact_id, _), _)| stored_artifact_id == artifact_id.as_str())
            .map(|(_, record)| {
                ArtifactVersion::restore(record.clone()).map_err(map_restoration_error)
            })
            .collect()
    }

    fn transition_lifecycle(
        &self,
        artifact_id: &ArtifactId,
        version: &str,
        target: LifecycleState,
    ) -> Result<ArtifactVersion, StoreError> {
        if version.trim().is_empty() {
            return Err(StoreError::InvalidVersion);
        }

        let key = (artifact_id.as_str().to_string(), version.to_string());
        let mut versions = self
            .versions
            .write()
            .map_err(|_| StoreError::LockPoisoned)?;

        let current_record = versions.get(&key).ok_or(StoreError::NotFound)?;
        let current =
            ArtifactVersion::restore(current_record.clone()).map_err(map_restoration_error)?;

        if *current.lifecycle() == LifecycleState::Validated && target == LifecycleState::Published
        {
            return Err(StoreError::PublicationRequired);
        }

        let next_state = transition(*current.lifecycle(), target).map_err(|error| {
            StoreError::InvalidLifecycleTransition {
                from: error.from(),
                to: error.to(),
            }
        })?;

        let mut updated = current;
        updated.set_lifecycle(next_state);
        versions.insert(key, (&updated).into());

        Ok(updated)
    }

    fn publish_validated(
        &self,
        artifact_id: &ArtifactId,
        version: &str,
        proof: &IntegrityProof,
    ) -> Result<ArtifactVersion, StoreError> {
        if version.trim().is_empty() {
            return Err(StoreError::InvalidVersion);
        }

        let key = (artifact_id.as_str().to_string(), version.to_string());
        let mut versions = self
            .versions
            .write()
            .map_err(|_| StoreError::LockPoisoned)?;

        let current_record = versions.get(&key).ok_or(StoreError::NotFound)?;
        let current =
            ArtifactVersion::restore(current_record.clone()).map_err(map_restoration_error)?;

        if *current.lifecycle() != LifecycleState::Validated {
            return Err(StoreError::InvalidLifecycleTransition {
                from: *current.lifecycle(),
                to: LifecycleState::Published,
            });
        }

        if !current.content().is_valid() {
            return Err(StoreError::InvalidContentReference);
        }

        if !proof.matches(current.digest(), current.size()) {
            return Err(StoreError::IntegrityFailure);
        }

        let next_state =
            transition(LifecycleState::Validated, LifecycleState::Published).map_err(|error| {
                StoreError::InvalidLifecycleTransition {
                    from: error.from(),
                    to: error.to(),
                }
            })?;

        let mut updated = current;
        updated.set_lifecycle(next_state);
        versions.insert(key, (&updated).into());

        Ok(updated)
    }

    fn set_alias(
        &self,
        artifact_id: &ArtifactId,
        alias: &str,
        version: &str,
    ) -> Result<(), StoreError> {
        if alias.trim().is_empty() {
            return Err(StoreError::InvalidAlias);
        }

        if version.trim().is_empty() {
            return Err(StoreError::InvalidVersion);
        }

        let version_key = (artifact_id.as_str().to_string(), version.to_string());

        {
            let versions = self.versions.read().map_err(|_| StoreError::LockPoisoned)?;

            if !versions.contains_key(&version_key) {
                return Err(StoreError::NotFound);
            }
        }

        let alias_key = (artifact_id.as_str().to_string(), alias.to_string());

        let mut aliases = self.aliases.write().map_err(|_| StoreError::LockPoisoned)?;

        aliases.insert(alias_key, version.to_string());

        Ok(())
    }

    fn resolve_alias(
        &self,
        artifact_id: &ArtifactId,
        alias: &str,
    ) -> Result<Option<String>, StoreError> {
        if alias.trim().is_empty() {
            return Err(StoreError::InvalidAlias);
        }

        let aliases = self.aliases.read().map_err(|_| StoreError::LockPoisoned)?;

        Ok(aliases
            .get(&(artifact_id.as_str().to_string(), alias.to_string()))
            .cloned())
    }

    fn remove_alias(&self, artifact_id: &ArtifactId, alias: &str) -> Result<bool, StoreError> {
        if alias.trim().is_empty() {
            return Err(StoreError::InvalidAlias);
        }

        let mut aliases = self.aliases.write().map_err(|_| StoreError::LockPoisoned)?;

        Ok(aliases
            .remove(&(artifact_id.as_str().to_string(), alias.to_string()))
            .is_some())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::artifact::content::ContentReference;
    use crate::artifact::integrity::{ContentDigest, IntegrityProof};

    fn artifact_id() -> ArtifactId {
        ArtifactId::new("test-artifact").unwrap()
    }

    fn version(version: &str) -> ArtifactVersion {
        ArtifactVersion::new(
            artifact_id(),
            version,
            ContentReference::new("provider", "location"),
            ContentDigest::new(b"content"),
            7,
        )
    }

    #[test]
    fn stores_and_retrieves_version() {
        let store = InMemoryArtifactStore::new();
        let item = version("v1");

        store.store(item.clone()).unwrap();

        assert_eq!(store.get(&artifact_id(), "v1").unwrap(), Some(item));
    }

    #[test]
    fn duplicate_version_is_rejected() {
        let store = InMemoryArtifactStore::new();

        store.store(version("v1")).unwrap();

        assert_eq!(store.store(version("v1")), Err(StoreError::AlreadyExists));
    }

    #[test]
    fn lists_versions_without_implying_version_order() {
        let store = InMemoryArtifactStore::new();

        store.store(version("v2")).unwrap();
        store.store(version("v10")).unwrap();

        let versions = store.list_versions(&artifact_id()).unwrap();

        assert_eq!(versions.len(), 2);
        assert!(versions.iter().any(|item| item.version() == "v2"));
        assert!(versions.iter().any(|item| item.version() == "v10"));
    }

    #[test]
    fn lifecycle_transition_cannot_bypass_publication() {
        let store = InMemoryArtifactStore::new();

        let mut item = version("v1");
        item.set_lifecycle(LifecycleState::Validated);
        store.store(item).unwrap();

        assert_eq!(
            store.transition_lifecycle(&artifact_id(), "v1", LifecycleState::Published),
            Err(StoreError::PublicationRequired)
        );
    }

    #[test]
    fn publish_validated_atomically_updates_existing_version() {
        let store = InMemoryArtifactStore::new();

        let mut item = version("v1");
        item.set_lifecycle(LifecycleState::Validated);
        store.store(item).unwrap();

        let content = b"content";
        let proof = IntegrityProof::verify(content, &ContentDigest::new(content)).unwrap();
        let updated = store
            .publish_validated(&artifact_id(), "v1", &proof)
            .unwrap();

        assert_eq!(updated.lifecycle(), &LifecycleState::Published);

        let stored = store.get(&artifact_id(), "v1").unwrap().unwrap();
        assert_eq!(stored.lifecycle(), &LifecycleState::Published);
    }

    #[test]
    fn publish_validated_rejects_an_integrity_mismatch() {
        let store = InMemoryArtifactStore::new();

        let mut item = version("v1");
        item.set_lifecycle(LifecycleState::Validated);
        store.store(item).unwrap();

        let proof = IntegrityProof::verify(
            b"tampered content",
            &ContentDigest::new(b"tampered content"),
        )
        .unwrap();

        assert_eq!(
            store.publish_validated(&artifact_id(), "v1", &proof),
            Err(StoreError::IntegrityFailure)
        );
        assert_eq!(
            store
                .get(&artifact_id(), "v1")
                .unwrap()
                .unwrap()
                .lifecycle(),
            &LifecycleState::Validated
        );
    }

    #[test]
    fn invalid_lifecycle_transition_is_rejected() {
        let store = InMemoryArtifactStore::new();

        store.store(version("v1")).unwrap();

        let result = store.transition_lifecycle(&artifact_id(), "v1", LifecycleState::Published);

        assert!(matches!(
            result,
            Err(StoreError::InvalidLifecycleTransition {
                from: LifecycleState::Created,
                to: LifecycleState::Published
            })
        ));
    }

    #[test]
    fn publish_validated_rejects_a_stale_state() {
        let store = InMemoryArtifactStore::new();

        let mut item = version("v1");
        item.set_lifecycle(LifecycleState::Validated);
        store.store(item).unwrap();

        let content = b"content";
        let proof = IntegrityProof::verify(content, &ContentDigest::new(content)).unwrap();

        store
            .publish_validated(&artifact_id(), "v1", &proof)
            .unwrap();

        assert_eq!(
            store.publish_validated(&artifact_id(), "v1", &proof),
            Err(StoreError::InvalidLifecycleTransition {
                from: LifecycleState::Published,
                to: LifecycleState::Published,
            })
        );
    }

    #[test]
    fn missing_version_cannot_transition() {
        let store = InMemoryArtifactStore::new();

        assert_eq!(
            store.transition_lifecycle(&artifact_id(), "missing", LifecycleState::Published),
            Err(StoreError::NotFound)
        );
    }

    #[test]
    fn aliases_resolve_to_exact_versions() {
        let store = InMemoryArtifactStore::new();

        store.store(version("v1")).unwrap();
        store.set_alias(&artifact_id(), "latest", "v1").unwrap();

        assert_eq!(
            store.resolve_alias(&artifact_id(), "latest").unwrap(),
            Some("v1".to_string())
        );
    }

    #[test]
    fn aliases_can_be_updated_without_replacing_versions() {
        let store = InMemoryArtifactStore::new();

        store.store(version("v1")).unwrap();
        store.store(version("v2")).unwrap();

        store.set_alias(&artifact_id(), "latest", "v1").unwrap();
        store.set_alias(&artifact_id(), "latest", "v2").unwrap();

        assert_eq!(
            store.resolve_alias(&artifact_id(), "latest").unwrap(),
            Some("v2".to_string())
        );

        assert!(store.get(&artifact_id(), "v1").unwrap().is_some());
        assert!(store.get(&artifact_id(), "v2").unwrap().is_some());
    }

    #[test]
    fn removing_alias_does_not_remove_version() {
        let store = InMemoryArtifactStore::new();

        store.store(version("v1")).unwrap();
        store.set_alias(&artifact_id(), "latest", "v1").unwrap();

        assert!(store.remove_alias(&artifact_id(), "latest").unwrap());

        assert_eq!(store.resolve_alias(&artifact_id(), "latest").unwrap(), None);

        assert!(store.get(&artifact_id(), "v1").unwrap().is_some());
    }

    #[test]
    fn invalid_version_is_rejected() {
        let store = InMemoryArtifactStore::new();

        assert_eq!(store.store(version("   ")), Err(StoreError::InvalidVersion));
    }

    #[test]
    fn invalid_alias_is_rejected() {
        let store = InMemoryArtifactStore::new();

        assert_eq!(
            store.set_alias(&artifact_id(), "   ", "v1"),
            Err(StoreError::InvalidAlias)
        );
    }

    #[test]
    fn alias_requires_existing_target_version() {
        let store = InMemoryArtifactStore::new();

        assert_eq!(
            store.set_alias(&artifact_id(), "latest", "missing"),
            Err(StoreError::NotFound)
        );
    }
}