aura_sync/lib.rs
1//! # Aura Sync - Layer 5: Feature/Protocol Implementation
2//!
3//! This crate provides complete end-to-end synchronization protocol implementations.
4//!
5//! ## Purpose
6//!
7//! Layer 5 feature crate providing reusable protocol building blocks for:
8//! - Journal state synchronization using CRDT semilattice semantics
9//! - Anti-entropy protocols for state reconciliation between peers
10//! - Snapshot creation and restoration for efficient sync initialization
11//! - OTA upgrade coordination with threshold approval
12//! - Receipt verification for distributed protocol commitment
13//!
14//! ## Architecture Constraints
15//!
16//! This crate depends on:
17//! - **Layer 1** (aura-core): Core types, effects, errors, session management
18//! - **Layer 2** (aura-journal): CRDT semantics and fact storage
19//! - **Layer 3** (aura-effects): Effect handler implementations
20//! - **Layer 4** (aura-protocol): Orchestration and guard chain
21//!
22//! ## What Belongs Here
23//!
24//! - Complete protocol implementations (anti-entropy, journal sync, snapshots, OTA, receipts)
25//! - Protocol coordination for multi-party synchronization
26//! - Configuration and policy for sync strategies
27//! - Metrics collection and health monitoring
28//! - Session management for protocol coordination
29//! - Infrastructure utilities (peer management, retry logic, caching, rate limiting)
30//! - MPST protocol definitions for sync ceremonies
31//!
32//! ## What Does NOT Belong Here
33//!
34//! - Effect handler implementations (belong in aura-effects)
35//! - Handler composition or registry (belong in aura-composition)
36//! - Low-level multi-party coordination (belong in aura-protocol)
37//! - Journal implementations (belong in aura-journal)
38//! - Storage backend implementations
39//!
40//! ## Design Principles
41//!
42//! - All protocols parameterized by effect traits: generic over effect implementations
43//! - Protocols are effect-driven: composition, testing, and deployment flexibility
44//! - CRDT semantics ensure idempotent, convergent synchronization
45//! - Anti-entropy ensures eventual consistency without coordination overhead
46//! - Session-based coordination allows stateless protocol implementation
47//! - Integration with guard chain ensures authorization before synchronization
48//! - Metrics collection enables observability and performance tuning
49//!
50//! ## Authority vs Device Model
51//!
52//! This crate uses Aura's authority-centric identity model:
53//!
54//! - **`AuthorityId`**: Represents the *owner* of state and operations. Authorities are
55//! cryptographic identities that own journals, create attestations, and authorize actions.
56//! State is synchronized *per authority*, not per device.
57//!
58//! - **`DeviceId`**: Represents a *connection endpoint* for network communication.
59//! Devices connect to each other to exchange state, but state ownership is always
60//! attributed to authorities, not devices.
61//!
62//! In sync protocols:
63//! - Peers are identified by `DeviceId` for network addressing
64//! - Journal operations and facts are attributed to `AuthorityId`
65//! - Authorization decisions use `AuthorityId` via Biscuit tokens
66//! - State merges resolve conflicts using authority-attributed timestamps
67//!
68//! See `docs/102_authority_and_identity.md` for the complete authority model.
69//!
70//! ## Time System
71//!
72//! This crate uses the unified time system from `aura-core`:
73//!
74//! - **`PhysicalTime`**: Wall-clock timestamps with optional uncertainty bounds.
75//! Used for timestamps, timeouts, and coordination deadlines.
76//! - All time access goes through `PhysicalTimeEffects` trait, never direct `SystemTime` calls
77//! - Time is passed explicitly to methods, enabling deterministic testing
78//!
79//! See `docs/103_effect_system.md` for the unified time architecture.
80
81// Allow disallowed methods/types in protocol implementations that coordinate effects
82#![allow(clippy::disallowed_methods, clippy::disallowed_types)]
83//!
84//! # Usage
85//!
86//! ```rust,ignore
87//! use aura_sync::{
88//! protocols::{AntiEntropyProtocol, JournalSyncProtocol},
89//! core::{SyncConfig, MetricsCollector, SessionManager},
90//! };
91//! use aura_core::effects::{NetworkEffects, JournalEffects, CryptoEffects};
92//!
93//! // Create sync configuration
94//! let config = SyncConfig::for_production();
95//!
96//! // Set up metrics collection
97//! let metrics = MetricsCollector::new();
98//!
99//! // Create session manager for protocol coordination
100//! let session_manager = SessionManager::new(config.sessions());
101//!
102//! // Use protocols with any effect implementation
103//! async fn sync_with_peer<E>(
104//! effects: &E,
105//! peer: DeviceId,
106//! ) -> SyncResult<()>
107//! where
108//! E: NetworkEffects + JournalEffects + CryptoEffects,
109//! {
110//! let protocol = AntiEntropyProtocol::new(&config);
111//! protocol.sync_with_peer(effects, peer).await
112//! }
113//! ```
114
115// Missing docs are temporarily allowed while protocol surfaces stabilize.
116#![allow(missing_docs)]
117#![forbid(unsafe_code)]
118
119#[cfg(all(feature = "transparent_onion", not(any(test, debug_assertions))))]
120compile_error!(
121 "Feature `transparent_onion` is a debug/test/simulation-only tool and must \
122 not be enabled in release production builds."
123);
124
125// =============================================================================
126// Core Foundation Modules
127// =============================================================================
128
129/// Typed capability families owned by sync protocols.
130pub mod capabilities;
131
132/// Core abstractions and unified patterns for sync protocols
133///
134/// This module provides the foundational types and patterns used throughout
135/// all sync protocols: unified error handling, message frameworks, configuration
136/// management, metrics collection, and session coordination.
137pub mod core;
138
139/// Infrastructure utilities for sync operations
140///
141/// This module provides supporting infrastructure including peer management,
142/// connection pooling, retry logic, cache management, and rate limiting.
143/// All components follow Layer 5 patterns with effect-based interfaces.
144pub mod infrastructure;
145
146/// Protocol implementations for synchronization
147///
148/// This module provides complete end-to-end protocol implementations including
149/// anti-entropy, journal sync, snapshots, OTA upgrades, and receipt verification.
150/// All protocols follow Layer 5 patterns and are effect-based.
151pub mod protocols;
152
153/// Service layer for sync operations
154///
155/// This module provides high-level services that orchestrate protocols and
156/// infrastructure to provide complete synchronization functionality.
157/// All services implement the unified Service trait.
158pub mod services;
159
160/// Verification module for Merkle-based fact verification
161///
162/// This module provides cryptographic verification of facts during synchronization
163/// using Merkle trees and Bloom filters from the IndexedJournalEffects.
164pub mod verification;
165
166/// Operation category map (A/B/C) for protocol gating and review.
167pub const OPERATION_CATEGORIES: &[(&str, &str)] = &[
168 ("sync:anti-entropy", "A"),
169 ("sync:journal-sync", "A"),
170 ("sync:snapshot", "A"),
171 ("sync:ota-ceremony", "C"),
172 ("sync:receipt-verify", "A"),
173];
174
175/// Lookup the operation category (A/B/C) for a given operation.
176pub fn operation_category(operation: &str) -> Option<&'static str> {
177 OPERATION_CATEGORIES
178 .iter()
179 .find(|(op, _)| *op == operation)
180 .map(|(_, category)| *category)
181}
182
183// Re-export core types for convenience
184pub use core::{
185 MetricsCollector, SessionManager, SessionResult, SessionState, SyncConfig, SyncResult,
186};
187
188// Protocol re-exports
189pub use protocols::{WriterFence, WriterFenceGuard};
190
191// Services re-exports
192pub use services::maintenance;
193
194// Verification re-exports
195pub use verification::{MerkleComparison, MerkleVerifier, VerificationResult, VerificationStats};
196
197// =============================================================================
198// Integration Documentation
199// =============================================================================
200
201/// Integration documentation and patterns.
202///
203/// This module is intentionally inline so `aura-sync` does not depend on an
204/// external markdown file being present at compile time.
205///
206/// `aura-sync` integration summary:
207///
208/// - Layer: L5 feature crate.
209/// - Runtime wiring is owned by L6 (`aura-agent`), not by this crate.
210/// - TUI/CLI surfaces operations through `aura-app` workflows.
211///
212/// Primary operation categories:
213///
214/// - `sync:anti-entropy` (`A`)
215/// - `sync:journal-sync` (`A`)
216/// - `sync:snapshot` (`A`)
217/// - `sync:ota-ceremony` (`C`)
218/// - `sync:receipt-verify` (`A`)
219pub mod integration_docs {}
220
221// =============================================================================
222// Layer Dependencies Re-exports
223// =============================================================================
224
225// Re-export essential foundation types from Layer 1 (aura-core)
226pub use aura_core::{AuraError, AuraResult, SessionId};
227
228// Re-export CrdtCoordinator when crdt-sync feature is enabled.
229// This provides choreography-based CRDT synchronization as an alternative
230// to digest-based anti-entropy sync for general CRDT state.
231#[cfg(feature = "crdt-sync")]
232pub use aura_protocol::effects::crdt::{CrdtCoordinator, CrdtCoordinatorError};
233
234// Note: Other layer dependencies are imported as needed but not re-exported
235// to maintain clean API boundaries and avoid dependency pollution.
236// Users should import from the appropriate layer crates directly.