use std::path::Path;
use muniment::{Backend, MemoryBackend, RedbBackend};
use proofs::Digest;
use crate::constitution::ConstitutionRules;
use super::MootId;
use super::governance::{MootGovernance, MootGovernanceError, MootGovernanceSnapshot};
use super::retention::{AvailabilityPolicy, ErasurePolicy, MootRetentionPolicy, PolicyRevision};
use super::roster::MootRoster;
use super::store::{MootStore, MootStoreError};
use super::wire::MootEvent;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootRetentionSettings {
pub revision: PolicyRevision,
pub availability: AvailabilityPolicy,
pub erasure: ErasurePolicy,
}
impl MootRetentionSettings {
fn resolve(
&self,
checkpoint_authority: super::GovernedCheckpointAuthority,
) -> MootRetentionPolicy {
MootRetentionPolicy {
revision: self.revision.clone(),
checkpoint_authority,
availability: self.availability,
erasure: self.erasure,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootCheckpointSnapshot {
pub operation: [u8; 32],
pub policy_revision: PolicyRevision,
pub authority_revision: Digest,
pub previous_checkpoint: Option<[u8; 32]>,
pub frontier_count: usize,
pub at_ms: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootSnapshot {
pub moot_id: MootId,
pub governance: MootGovernanceSnapshot,
pub roster: MootRoster,
pub checkpoint: Option<MootCheckpointSnapshot>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootCommandReceipt {
pub operation: [u8; 32],
pub snapshot: MootSnapshot,
}
#[derive(Debug, thiserror::Error)]
pub enum MootError {
#[error(transparent)]
Governance(#[from] MootGovernanceError),
#[error(transparent)]
Store(#[from] MootStoreError),
#[error("moot has no accepted retention checkpoint")]
CheckpointMissing,
#[error("moot storage directory: {0}")]
Io(#[from] std::io::Error),
}
#[derive(Clone)]
pub struct Moot<B> {
moot_id: MootId,
governance: MootGovernance<B>,
objects: MootStore<B>,
retention: MootRetentionSettings,
}
pub type MootFile = Moot<RedbBackend>;
impl Moot<MemoryBackend> {
pub fn in_memory(moot_id: MootId, founder: [u8; 32], retention: MootRetentionSettings) -> Self {
Self {
moot_id,
governance: MootGovernance::in_memory(moot_id.0, founder),
objects: MootStore::in_memory(),
retention,
}
}
}
impl Moot<RedbBackend> {
pub async fn open(
directory: impl AsRef<Path>,
moot_id: MootId,
founder: [u8; 32],
retention: MootRetentionSettings,
) -> Result<Self, MootError> {
std::fs::create_dir_all(directory.as_ref())?;
let service = Self {
moot_id,
governance: MootGovernance::open(
directory.as_ref().join("constitution.redb"),
moot_id.0,
founder,
)?,
objects: MootStore::at_path(directory.as_ref().join("objects.redb"))?,
retention,
};
match service.governance.snapshot().await {
Ok(_) => service.refresh_retention_authority().await?,
Err(MootGovernanceError::NotFounded) => {}
Err(error) => return Err(error.into()),
}
Ok(service)
}
}
impl<B: Backend + Clone> Moot<B> {
pub fn moot_id(&self) -> MootId {
self.moot_id
}
pub fn object_store(&self) -> &MootStore<B> {
&self.objects
}
async fn refresh_retention_authority(&self) -> Result<(), MootError> {
let authority = self.governance.checkpoint_authority().await?;
self.objects
.set_retention_policy(Some(self.retention.resolve(authority)));
Ok(())
}
pub async fn found(
&self,
founder_seed: [u8; 32],
parent_constitution: Option<Digest>,
divergence_point: Option<Digest>,
rules: ConstitutionRules,
at_ms: u64,
) -> Result<MootSnapshot, MootError> {
self.governance
.found(
founder_seed,
parent_constitution,
divergence_point,
rules,
at_ms,
)
.await?;
self.refresh_retention_authority().await?;
self.snapshot().await
}
pub async fn amend(
&self,
actor_seed: [u8; 32],
rules: ConstitutionRules,
at_ms: u64,
) -> Result<MootSnapshot, MootError> {
self.governance.amend(actor_seed, rules, at_ms).await?;
self.refresh_retention_authority().await?;
self.snapshot().await
}
pub async fn declare(
&self,
actor_seed: [u8; 32],
name: String,
charter: String,
at_ms: u64,
) -> Result<MootCommandReceipt, MootError> {
self.governance.snapshot().await?;
self.author_object(
actor_seed,
MootEvent::Declared {
name,
charter,
at_ms,
},
)
.await
}
pub async fn join(
&self,
actor_seed: [u8; 32],
name: String,
at_ms: u64,
) -> Result<MootCommandReceipt, MootError> {
self.governance.snapshot().await?;
self.author_object(actor_seed, MootEvent::Joined { name, at_ms })
.await
}
pub async fn share(
&self,
actor_seed: [u8; 32],
manifest_id: [u8; 32],
schema_id: String,
title: String,
at_ms: u64,
) -> Result<MootCommandReceipt, MootError> {
self.governance.snapshot().await?;
self.author_object(
actor_seed,
MootEvent::Shared {
manifest_id,
schema_id,
title,
at_ms,
},
)
.await
}
async fn author_object(
&self,
actor_seed: [u8; 32],
event: MootEvent,
) -> Result<MootCommandReceipt, MootError> {
let operation = self
.objects
.author_seed(actor_seed, self.moot_id.0, &event)
.await?;
Ok(MootCommandReceipt {
operation: *operation.hash.as_bytes(),
snapshot: self.snapshot().await?,
})
}
pub async fn checkpoint(
&self,
actor_seed: [u8; 32],
at_ms: u64,
) -> Result<MootCommandReceipt, MootError> {
self.refresh_retention_authority().await?;
let checkpoint = self.objects.build_checkpoint(self.moot_id.0, at_ms).await?;
self.author_object(
actor_seed,
MootEvent::RetentionCheckpoint {
checkpoint: Box::new(checkpoint),
},
)
.await
}
pub async fn prune_current(
&self,
actor_seed: [u8; 32],
at_ms: u64,
) -> Result<MootCommandReceipt, MootError> {
let checkpoint = self
.objects
.latest_checkpoint(self.moot_id.0)
.await?
.ok_or(MootError::CheckpointMissing)?;
let operation = self
.objects
.author_prune_seed(actor_seed, self.moot_id.0, checkpoint.operation, at_ms)
.await?;
Ok(MootCommandReceipt {
operation: *operation.hash.as_bytes(),
snapshot: self.snapshot().await?,
})
}
pub async fn snapshot(&self) -> Result<MootSnapshot, MootError> {
let governance = self.governance.snapshot().await?;
let roster = self.objects.roster(self.moot_id.0).await?;
let checkpoint = self
.objects
.latest_checkpoint(self.moot_id.0)
.await?
.map(|stored| MootCheckpointSnapshot {
operation: stored.operation,
policy_revision: stored.checkpoint.policy_revision,
authority_revision: stored.checkpoint.authority_revision,
previous_checkpoint: stored.checkpoint.previous_checkpoint,
frontier_count: stored.checkpoint.frontier.len(),
at_ms: stored.checkpoint.at_ms,
});
Ok(MootSnapshot {
moot_id: self.moot_id,
governance,
roster,
checkpoint,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::moot::{KeepBound, MootStoreError};
use identity::{IdentityProvider, InMemoryProvider};
const ID: MootId = MootId([0x6d; 32]);
fn keypair(seed: u8) -> identity::Ed25519Keypair {
InMemoryProvider::from_seed([seed; 32])
.derive_keypair(b"moot-service")
.unwrap()
}
fn retention() -> MootRetentionSettings {
MootRetentionSettings {
revision: PolicyRevision(Digest::blake3(b"moot retention settings")),
availability: AvailabilityPolicy {
promised_floor: KeepBound::Forever,
},
erasure: ErasurePolicy {
history_ceiling: KeepBound::UntilCheckpoint,
},
}
}
#[tokio::test]
async fn one_service_runs_governance_roster_checkpoint_and_rotation() {
let founder = keypair(1);
let successor = keypair(2);
let service = Moot::in_memory(ID, founder.public_key().to_bytes(), retention());
service
.found(
founder.to_seed(),
None,
None,
ConstitutionRules::founder_only(founder.public_key().to_bytes()),
1,
)
.await
.unwrap();
service
.declare(
founder.to_seed(),
"printing circle".into(),
"shared type".into(),
2,
)
.await
.unwrap();
service
.join(founder.to_seed(), "mark".into(), 3)
.await
.unwrap();
let first = service.checkpoint(founder.to_seed(), 10).await.unwrap();
let mut rotated = ConstitutionRules::founder_only(founder.public_key().to_bytes());
rotated.checkpoint_signers.clear();
rotated
.checkpoint_signers
.insert(successor.public_key().to_bytes());
service.amend(founder.to_seed(), rotated, 11).await.unwrap();
assert!(matches!(
service.checkpoint(founder.to_seed(), 12).await,
Err(MootError::Store(MootStoreError::Process(_)))
));
let second = service.checkpoint(successor.to_seed(), 13).await.unwrap();
assert_eq!(
second
.snapshot
.checkpoint
.as_ref()
.unwrap()
.previous_checkpoint,
Some(first.operation)
);
service.prune_current(founder.to_seed(), 14).await.unwrap();
let snapshot = service.snapshot().await.unwrap();
assert_eq!(snapshot.roster.declaration.unwrap().name, "printing circle");
assert_eq!(snapshot.roster.members.len(), 1);
assert_eq!(snapshot.checkpoint.unwrap().operation, second.operation);
}
#[tokio::test]
async fn durable_service_reopens_both_governance_and_roster() {
let directory = tempfile::tempdir().unwrap();
let founder = keypair(3);
let founder_id = founder.public_key().to_bytes();
let service = MootFile::open(directory.path(), ID, founder_id, retention())
.await
.unwrap();
service
.found(
founder.to_seed(),
None,
None,
ConstitutionRules::founder_only(founder_id),
1,
)
.await
.unwrap();
service
.join(founder.to_seed(), "mark".into(), 2)
.await
.unwrap();
drop(service);
let reopened = MootFile::open(directory.path(), ID, founder_id, retention())
.await
.unwrap();
assert_eq!(reopened.snapshot().await.unwrap().roster.members.len(), 1);
}
}