MARS documentation
Rust librariesmars-server

mars-server · store

Public declarations and documentation for mars-server::store.

Package: mars-server · Workspace version: 0.1.0 · Module: store

This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import.

store::memory

Storage backend trait and implementations.

Defines the [EntryStore] trait that all storage backends must implement, providing CRUD operations for entries, bonds, events, and federation peers.

pub mod memory;

Source line: 6.

store::postgres

#[cfg(feature = "postgres")]
pub mod postgres;

Source line: 10.

store::sharded_memory

#[cfg(feature = "sharding")]
pub mod sharded_memory;

Source line: 14.

pub use mars_protocol::anchoring::AnchorOperation;

pub use mars_protocol::anchoring::AnchorOperation;

Source line: 22.

store::EntryVersionPage

One bounded page from an entry's immutable version history.

#[derive(Debug, Clone, PartialEq)]
pub struct EntryVersionPage {
/// Canonically ordered snapshots in this page.

pub versions: Vec<MarsEntry>,
/// Number of versions stored for the DID before pagination.

pub total_count: u64,
/// Last returned registry sequence when another keyset page exists.

pub next_cursor: Option<u64>,
/// Whether versions exist below `next_cursor`.

pub has_more: bool
}

Source line: 49.

store::PageRequest

Validated offset/limit primitives for every potentially multi-row read.

Storage implementations must apply these bounds in the database query (or while holding the in-memory state lock), never after an unbounded fetch.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PageRequest {

}

Source line: 65.

store::PageRequest::MAX_LIMIT

Hard storage-level allocation bound, independent of HTTP configuration.

pub const MAX_LIMIT: u32;

Source line: 72.

store::PageRequest::new

Construct a validated page.

pub fn new(offset: u64, limit: u32) -> Result<Self, ServerError>;

Source line: 75.

store::PageRequest::first

First page with the requested bound.

pub fn first(limit: u32) -> Result<Self, ServerError>;

Source line: 86.

store::PageRequest::offset

Zero-based row offset.

#[must_use]
pub fn offset(self) -> u64;

Source line: 92.

store::PageRequest::limit

Maximum rows returned by this read.

#[must_use]
pub fn limit(self) -> u32;

Source line: 98.

store::PageRequest::advance

Advance by the number of rows actually consumed.

pub fn advance(self, consumed: usize) -> Result<Self, ServerError>;

Source line: 103.

store::AuditAction

Private, append-only audit action recorded with a committed mutation.

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuditAction {
    /// A registry entry was created.
    Create,
    /// A registry entry was updated.
    Update,
    /// A registry entry was revoked.
    Revoke,
    /// A transfer offer was created.
    TransferOffer,
    /// A transfer offer was accepted.
    TransferAccept,
    /// A transfer offer was declined.
    TransferDecline,
    /// A transfer offer expired.
    TransferExpire,
    /// A canonical attestation was accepted.
    Attest,
    /// A malicious-behaviour report was accepted.
    Report,
    /// A registry-local bond was provisioned.
    BondProvision,
    /// A federation sync request was served.
    FederationSync,
    /// A federation peer changed its metadata.
    PeerUpdate,
    /// Another event-only write was accepted.
    Event,
    /// An administrator requeued an anchor intent.
    AnchorRetry,
    /// An administrator permanently abandoned an anchor intent.
    AnchorAbandon,
}

Source line: 113.

store::AuditOutcome

Outcome of an authenticated mutation attempt.

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuditOutcome {
    Accepted,
    Rejected,
}

Source line: 172.

store::AuditContext

Shared provenance for one private mutation audit row.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditContext {
pub actor_did: String,
pub route: String,
pub target: String,
pub request_hash: String,
pub response_status: u16,
pub occurred_at: DateTime<Utc>
}

Source line: 180.

store::AuditContext::new

#[must_use]
pub fn new(
        actor_did: impl Into<String>,
        route: impl Into<String>,
        target: impl Into<String>,
        request_hash: impl Into<String>,
        response_status: u16,
        occurred_at: DateTime<Utc>,
    ) -> Self;

Source line: 191.

store::AuditRecord

MARS-owned private audit record persisted in the mutation transaction.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditRecord {
/// Globally unique audit record identifier.

pub audit_id: String,
/// Actor identity supplied by the authenticated boundary or caller.

pub actor_did: String,
/// Stable route template, never a client-supplied actor field.

pub route: String,
/// Operation recorded by this audit row.

pub action: AuditAction,
/// Accepted or rejected outcome.

pub outcome: AuditOutcome,
/// Entry, offer, bond, or route target affected by the operation.

pub entry_did: String,
/// Canonical semantic request hash.

pub request_hash: String,
/// HTTP status returned to the caller.

pub response_status: u16,
/// Rejection reason, absent for accepted mutations.

pub reason: Option<String>,
/// Registry sequence assigned by the transaction.

pub sequence: u64,
/// Timestamp captured before the transaction starts.

pub occurred_at: DateTime<Utc>,
/// MARS-owned contextual metadata. Never exposed by public entry APIs.

pub detail: Option<serde_json::Value>,
/// Hash of the preceding private audit row.

pub previous_hash: Option<String>,
/// SHA-256 hash of this row's canonical content and predecessor.

pub record_hash: String
}

Source line: 213.

store::AuditRecord::new

Build a private audit record for an event.

#[must_use]
pub fn new(actor_did: impl Into<String>, action: AuditAction, event: &MarsEvent) -> Self;

Source line: 247.

store::AuditRecord::accepted

Build an accepted mutation row.

#[must_use]
pub fn accepted(
        context: AuditContext,
        action: AuditAction,
        detail: Option<serde_json::Value>,
    ) -> Self;

Source line: 268.

store::AuditRecord::rejected

Build a rejected mutation row. The store seals it into the private hash chain before committing it.

#[must_use]
pub fn rejected(context: AuditContext, action: AuditAction, reason: impl Into<String>) -> Self;

Source line: 294.

store::AuditChainVerification

Result of a complete private audit-chain verification pass.

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuditChainVerification {
pub record_count: u64,
pub head_hash: Option<String>
}

Source line: 358.

store::EventChainVerification

Result of a complete public protocol-event chain verification pass.

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventChainVerification {
pub record_count: u64,
pub head_hash: Option<String>
}

Source line: 365.

store::LedgerChainVerification

Combined immutable-ledger verification result.

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LedgerChainVerification {
pub audit: AuditChainVerification,
pub events: EventChainVerification
}

Source line: 372.

store::AnchorIntent

Optional anchor work requested by a mutation.

Stores persist this as an outbox row. Network adapters consume it only after the database transaction commits.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnchorIntent {
/// Stable outbox intent identifier.

pub intent_id: String,
/// Mutation operation that produced the intent.

pub operation: AnchorOperation,
/// MARS-owned payload consumed by a later adapter.

pub payload: serde_json::Value,
/// Intent creation timestamp.

pub created_at: DateTime<Utc>
}

Source line: 395.

store::PersistedAnchorIntent

Persisted view of an anchor outbox row.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PersistedAnchorIntent {
/// Stable outbox intent identifier.

pub intent_id: String,
/// Entry snapshot to anchor.

pub entry_did: String,
/// Registry sequence of the immutable snapshot.

pub sequence: u64,
/// Mutation operation that produced the intent.

pub operation: AnchorOperation,
/// MARS-owned adapter payload.

pub payload: serde_json::Value,
/// Durable worker state.

pub state: AnchorOutboxState,
/// Number of submission attempts started.

pub attempts: u32,
/// Earliest time this row may be claimed or polled.

pub available_at: DateTime<Utc>,
/// Worker currently holding the lease.

pub claimed_by: Option<String>,
/// Expiration of the current worker lease.

pub lease_expires_at: Option<DateTime<Utc>>,
/// Opaque token required to complete the current claim.

pub lease_token: Option<String>,
/// Latest provider-neutral transaction identifier.

pub transaction_id: Option<String>,
/// Latest bounded failure diagnostic.

pub last_error: Option<String>,
/// Time the latest transaction was first accepted.

pub submitted_at: Option<DateTime<Utc>>,
/// Time the provider reported final confirmation.

pub confirmed_at: Option<DateTime<Utc>>,
/// Time processing was permanently abandoned.

pub abandoned_at: Option<DateTime<Utc>>,
/// Intent creation timestamp.

pub created_at: DateTime<Utc>,
/// Last durable state transition.

pub updated_at: DateTime<Utc>,
/// Immutable adapter observations, in observation order.

pub receipts: Vec<AnchorReceiptRecord>
}

Source line: 409.

store::AnchorIntentCursor

Stable position in an entry's combined hot and archived anchor history.

Ordering is lexicographic and ascending over (sequence, created_at, intent_id). The encoded representation is canonical, URL-safe, and opaque to API clients.

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnchorIntentCursor {

}

Source line: 456.

store::AnchorIntentCursor::MAX_ENCODED_LEN

Maximum accepted encoded cursor size.

pub const MAX_ENCODED_LEN: usize;

Source line: 464.

store::AnchorIntentCursor::from_intent

Construct the cursor representing a returned intent.

#[must_use]
pub fn from_intent(intent: &PersistedAnchorIntent) -> Self;

Source line: 468.

store::AnchorIntentCursor::encode

Encode this cursor as canonical unpadded base64url JSON.

pub fn encode(&self) -> Result<String, ServerError>;

Source line: 477.

store::AnchorIntentCursor::decode

Decode and validate a canonical cursor received from the public API.

pub fn decode(encoded: &str) -> Result<Self, ServerError>;

Source line: 492.

store::AnchorIntentPage

One bounded keyset page from combined hot and archived anchor history.

#[derive(Debug, Clone, PartialEq)]
pub struct AnchorIntentPage {
/// Canonically ordered intents in this page.

pub intents: Vec<PersistedAnchorIntent>,
/// Cursor for the last returned intent when another page exists.

pub next_cursor: Option<AnchorIntentCursor>,
/// Whether another intent exists after `next_cursor`.

pub has_more: bool
}

Source line: 540.

store::AnchorClaim

One exclusively leased outbox row.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnchorClaim {
pub intent: PersistedAnchorIntent,
pub lease_token: String
}

Source line: 552.

store::AnchorOutboxMetrics

Current outbox measurements used by health checks and Prometheus gauges.

#[derive(Debug, Clone, PartialEq)]
pub struct AnchorOutboxMetrics {
pub backlog: u64,
pub oldest_age_seconds: f64,
pub total_attempts: u64,
pub maximum_attempts: u32,
pub pending: u64,
pub claimed: u64,
pub submitted: u64,
pub failed: u64,
pub confirmed: u64,
pub abandoned: u64,
pub retained_terminal: u64,
pub archived_confirmed: u64,
pub archived_abandoned: u64
}

Source line: 559.

store::AnchorOutboxArchiveResult

Outcome of one bounded terminal-outbox archival transaction.

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AnchorOutboxArchiveResult {
pub archived: u64,
pub confirmed: u64,
pub abandoned: u64
}

Source line: 597.

store::AnchorAdminCommand

Idempotent administrative state transition for one anchor intent.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnchorAdminCommand {
pub intent_id: String,
pub occurred_at: DateTime<Utc>,
pub audit: AuditRecord,
pub idempotency: IdempotencyRequest
}

Source line: 606.

store::StoredHttpResponse

Exact HTTP response stored for an idempotent mutation.

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredHttpResponse {
pub status: u16,
pub content_type: Option<String>,
pub body: Vec<u8>
}

Source line: 616.

store::StoredHttpResponse::json

Construct a JSON response using the same compact serializer as Axum.

pub fn json<T: Serialize>(status: u16, value: &T) -> Result<Self, ServerError>;

Source line: 624.

store::StoredHttpResponse::empty

Construct a body-less response.

#[must_use]
pub fn empty(status: u16) -> Self;

Source line: 636.

store::StoredHttpResponse::into_axum_response

Convert the persisted response into an Axum response without changing its status or body bytes.

pub fn into_axum_response(self) -> Result<axum::response::Response, ServerError>;

Source line: 646.

store::IdempotencyRequest

Optional caller-provided idempotency reservation.

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdempotencyRequest {
/// Stable authenticated route template.

pub route: String,
/// Stable idempotency key.

pub key: String,
/// Canonical hash of the semantic request.

pub request_hash: String,
/// Exact response template. Entry commits replace the body after assigning

/// the authoritative registry sequence.

pub response: StoredHttpResponse,
/// Whether the committed entry is the response body.

pub response_from_entry: bool,
/// Server-controlled expiry time.

pub expires_at: DateTime<Utc>
}

Source line: 671.

store::IdempotencyRequest::for_test_entry_projection

Construct a test reservation using internal route/status/expiry defaults and an entry-projection response.

Production HTTP paths must use [Self::for_entry_projection] or [Self::for_stored_response] so route, response, and expiry semantics remain explicit.

#[must_use]
pub fn for_test_entry_projection(
        key: impl Into<String>,
        request_hash: impl Into<String>,
    ) -> Self;

Source line: 695.

store::IdempotencyRequest::for_entry_projection

Construct a reservation whose response body is reconstructed from the authoritative entry projection after sequence assignment.

This must only be used by commands that commit a [MarsEntry] and return that exact entry as the successful response body.

#[must_use]
pub fn for_entry_projection(
        route: impl Into<String>,
        key: impl Into<String>,
        request_hash: impl Into<String>,
        status: u16,
        expires_at: DateTime<Utc>,
    ) -> Self;

Source line: 715.

store::IdempotencyRequest::for_stored_response

Construct a reservation retaining the exact serialized HTTP response.

Use this for transfer offers, attestations, admin controls, reports, and every endpoint whose body is not exactly a committed entry.

#[must_use]
pub fn for_stored_response(
        route: impl Into<String>,
        key: impl Into<String>,
        request_hash: impl Into<String>,
        response: StoredHttpResponse,
        expires_at: DateTime<Utc>,
    ) -> Self;

Source line: 737.

store::MutationMetadata

Metadata persisted atomically beside every accepted mutation.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MutationMetadata {
/// Public protocol event.

pub event: MarsEvent,
/// Private audit record.

pub audit: AuditRecord,
/// Optional idempotency reservation.

pub idempotency: Option<IdempotencyRequest>,
/// Optional post-commit anchor work.

pub anchor_intent: Option<AnchorIntent>,
/// Revalidate the referenced registry-local bond inside the mutation

/// transaction to close validation/commit races.

#[serde(default)]
pub bond_recheck: bool
}

Source line: 772.

store::CreateEntryCommand

Atomic create unit of work.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateEntryCommand {
/// Unsequenced entry supplied by the caller.

pub entry: MarsEntry,
/// Mutation metadata persisted in the same transaction.

pub metadata: MutationMetadata
}

Source line: 803.

store::CreateEntryCommand::new

Construct an atomic create command.

#[must_use]
pub fn new(entry: MarsEntry, event: MarsEvent, actor_did: impl Into<String>) -> Self;

Source line: 813.

store::CreateEntryCommand::with_idempotency

Attach an idempotency reservation.

#[must_use]
pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self;

Source line: 822.

store::CreateEntryCommand::with_anchor_intent

Attach post-commit anchor work.

#[must_use]
pub fn with_anchor_intent(mut self, intent: AnchorIntent) -> Self;

Source line: 830.

store::CreateEntryCommand::with_bond_recheck

Require a same-transaction bond status/binding recheck.

#[must_use]
pub fn with_bond_recheck(mut self) -> Self;

Source line: 837.

store::UpdateEntryCommand

Atomic update unit of work with compare-and-set concurrency control.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateEntryCommand {
/// Replacement latest entry. The store assigns its sequence.

pub entry: MarsEntry,
/// Latest sequence observed by the caller.

pub expected_sequence: u64,
/// Mutation metadata persisted in the same transaction.

pub metadata: MutationMetadata
}

Source line: 846.

store::UpdateEntryCommand::new

Construct an atomic compare-and-set update command.

#[must_use]
pub fn new(
        entry: MarsEntry,
        expected_sequence: u64,
        event: MarsEvent,
        actor_did: impl Into<String>,
    ) -> Self;

Source line: 858.

store::UpdateEntryCommand::with_audit_action

Override the private audit action for a specialized update.

#[must_use]
pub fn with_audit_action(mut self, action: AuditAction) -> Self;

Source line: 873.

store::UpdateEntryCommand::with_idempotency

Attach an idempotency reservation.

#[must_use]
pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self;

Source line: 880.

store::UpdateEntryCommand::with_anchor_intent

Attach post-commit anchor work.

#[must_use]
pub fn with_anchor_intent(mut self, intent: AnchorIntent) -> Self;

Source line: 888.

store::UpdateEntryCommand::with_bond_recheck

Require a same-transaction bond status/binding recheck.

#[must_use]
pub fn with_bond_recheck(mut self) -> Self;

Source line: 895.

store::RevokeEntryCommand

Atomic revoke unit of work with compare-and-set concurrency control.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RevokeEntryCommand {
/// Entry DID to revoke.

pub entry_did: String,
/// Latest sequence observed by the caller.

pub expected_sequence: u64,
/// Mutation metadata persisted in the same transaction.

pub metadata: MutationMetadata
}

Source line: 904.

store::RevokeEntryCommand::new

Construct an atomic revoke command.

#[must_use]
pub fn new(
        entry_did: impl Into<String>,
        expected_sequence: u64,
        event: MarsEvent,
        actor_did: impl Into<String>,
    ) -> Self;

Source line: 916.

store::RevokeEntryCommand::with_idempotency

Attach an idempotency reservation.

#[must_use]
pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self;

Source line: 931.

store::RevokeEntryCommand::with_anchor_intent

Attach post-commit anchor work.

#[must_use]
pub fn with_anchor_intent(mut self, intent: AnchorIntent) -> Self;

Source line: 939.

store::EventCommitCommand

Event-only durable write used by report and protocol-event paths.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventCommitCommand {
/// Public event to append.

pub event: MarsEvent,
/// Private audit record persisted with the event.

pub audit: AuditRecord,
/// Optional idempotency reservation and exact response.

pub idempotency: Option<IdempotencyRequest>
}

Source line: 948.

store::EventCommitCommand::new

Construct an event and audit atomic unit.

#[must_use]
pub fn new(event: MarsEvent, actor_did: impl Into<String>) -> Self;

Source line: 960.

store::EventCommitCommand::with_audit_action

Select the domain-specific private audit action.

#[must_use]
pub fn with_audit_action(mut self, action: AuditAction) -> Self;

Source line: 971.

store::EventCommitCommand::with_idempotency

Persist an exact idempotent response with the event.

#[must_use]
pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self;

Source line: 978.

store::RejectedMutationCommand

Atomic private audit and idempotency write for a rejected mutation.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RejectedMutationCommand {
pub audit: AuditRecord,
pub idempotency: Option<IdempotencyRequest>
}

Source line: 988.

store::TransferOfferCommand

Atomic creation of a signed transfer offer.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferOfferCommand {
pub offer: TransferOffer,
pub expected_entry_sequence: u64,
pub audit: AuditRecord,
pub idempotency: IdempotencyRequest
}

Source line: 996.

store::TransferAcceptCommand

Atomic recipient acceptance and entry replacement.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferAcceptCommand {
pub offer_id: String,
pub recipient_did: String,
pub entry: MarsEntry,
pub expected_entry_sequence: u64,
pub accepted_at: DateTime<Utc>,
pub event: MarsEvent,
pub audit: AuditRecord,
pub idempotency: IdempotencyRequest,
pub anchor_intent: Option<AnchorIntent>
}

Source line: 1006.

store::TransferDeclineCommand

Atomic recipient decline.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferDeclineCommand {
pub offer_id: String,
pub recipient_did: String,
pub declined_at: DateTime<Utc>,
pub reason: Option<String>,
pub audit: AuditRecord,
pub idempotency: IdempotencyRequest
}

Source line: 1021.

store::AttestationCommitCommand

Atomic canonical-attestation, event, audit, and idempotency commit.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AttestationCommitCommand {
pub attestation: VerifiableAttestationRecord,
pub event: MarsEvent,
pub audit: AuditRecord,
pub idempotency: IdempotencyRequest,
pub anchor_intent: Option<AnchorIntent>
}

Source line: 1033.

store::BondCommitCommand

Atomic registry-local bond provisioning command.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BondCommitCommand {
pub bond: Bond,
pub audit: AuditRecord,
pub idempotency: IdempotencyRequest
}

Source line: 1044.

store::PeerCommitCommand

Atomic peer metadata update command.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PeerCommitCommand {
pub peer: FederationPeer,
pub audit: AuditRecord,
pub idempotency: IdempotencyRequest
}

Source line: 1053.

store::FederationPeerState

Durable synchronization, health, lease, and breaker state for one peer.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FederationPeerState {
pub peer: FederationPeer,
pub cursor: u64,
pub remote_head: u64,
pub breaker_state: mars_protocol::federation::FederationBreakerState,
pub consecutive_failures: u32,
pub latency_ms: Option<u64>,
pub lag: u64,
pub quarantines: u64,
pub last_success_at: Option<DateTime<Utc>>,
pub next_attempt_at: DateTime<Utc>,
pub lease_owner: Option<String>,
pub lease_token: Option<String>,
pub lease_expires_at: Option<DateTime<Utc>>,
pub updated_at: DateTime<Utc>
}

Source line: 1062.

store::FederationPeerState::new

Construct the initial restart-safe state for a configured peer.

pub fn new(peer: FederationPeer, now: DateTime<Utc>) -> Result<Self, ServerError>;

Source line: 1081.

store::FederationPeerState::status

Secret-free projection returned by protected status routes.

#[must_use]
pub fn status(&self) -> mars_protocol::federation::FederationPeerStatus;

Source line: 1114.

store::FederationPeerClaim

Exclusively leased peer synchronization work.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FederationPeerClaim {
pub state: FederationPeerState,
pub lease_token: String
}

Source line: 1132.

store::FederationQuarantineReason

Bounded quarantine reason persisted without exposing parser internals.

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FederationQuarantineReason {
    Envelope,
    PublisherSignature,
    Validation,
    Conflict,
    VisibilityPolicy,
}

Source line: 1140.

store::FederationQuarantineRecord

Durable evidence for one rejected remote payload.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FederationQuarantineRecord {
pub quarantine_id: String,
pub peer_did: String,
pub request_digest: String,
pub entry_did: Option<String>,
pub reason: FederationQuarantineReason,
pub payload_digest: String,
pub payload: serde_json::Value,
pub observed_at: DateTime<Utc>
}

Source line: 1164.

store::FederationImportCommand

Validated, replay-safe remote entry import.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FederationImportCommand {
pub registry_did: String,
pub peer_did: String,
pub delivery_digest: String,
pub entry: MarsEntry,
pub source_sequence: u64,
pub content_digest: String,
pub expected_local_sequence: Option<u64>,
pub local_signature_verified: bool,
pub observed_at: DateTime<Utc>
}

Source line: 1178.

store::FederationImportOutcome

Result of one idempotent federation delivery.

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FederationImportOutcome {
    Imported,
    RetainedLocal,
    DuplicateDelivery,
}

Source line: 1193.

store::FederationMetrics

Bounded federation health metrics from durable state.

#[derive(Debug, Clone, Default, PartialEq)]
pub struct FederationMetrics {
pub peers: u64,
pub closed: u64,
pub open: u64,
pub half_open: u64,
pub quarantined: u64,
pub lag: u64,
pub quarantine_records: u64
}

Source line: 1201.

store::AuditedResponseCommand

Atomic audit plus exact response for authenticated mutations with no other local state change, such as pull-based federation sync.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditedResponseCommand {
pub audit: AuditRecord,
pub idempotency: IdempotencyRequest
}

Source line: 1215.

store::RejectedMutationCommand::new

#[must_use]
pub fn new(audit: AuditRecord) -> Self;

Source line: 1222.

store::RejectedMutationCommand::with_idempotency

#[must_use]
pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self;

Source line: 1230.

store::MutationCommit

Result returned by create, update, and revoke commits.

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MutationCommit {
/// Latest entry after the transaction committed.

pub entry: MarsEntry,
/// Event persisted by the transaction.

pub event: MarsEvent,
/// Whether this response came from a prior idempotent commit.

pub idempotent_replay: bool,
/// Exact response stored under the idempotency key.

pub response: StoredHttpResponse
}

Source line: 1240.

store::EntryStore

Storage backend trait for the MARS registry.

Implementations must be thread-safe (Send + Sync). The async, object-safe interface permits PostgreSQL and in-memory stores to share one production path without runtime blocking bridges.

#[async_trait]
pub trait EntryStore: Send + Sync {
    /// Return an unexpired exact replay, reject hash reuse, or report no match.
    async fn lookup_idempotency(
        &self,
        actor_did: &str,
        route: &str,
        key: &str,
        request_hash: &str,
        now: DateTime<Utc>,
    ) -> Result<Option<StoredHttpResponse>, ServerError>;

    /// Atomically append a rejected audit row and, when present, its exact
    /// idempotency response.
    async fn commit_rejection(&self, command: RejectedMutationCommand) -> Result<(), ServerError>;

    /// Remove expired idempotency responses.
    async fn cleanup_idempotency(&self, before: DateTime<Utc>) -> Result<u64, ServerError>;

    /// Verify every private audit row and the persisted chain head.
    async fn verify_audit_chain(&self) -> Result<AuditChainVerification, ServerError>;

    /// Verify the public protocol-event chain and its persisted head.
    async fn verify_event_chain(&self) -> Result<EventChainVerification, ServerError> ;

    /// Verify both immutable hash chains.
    async fn verify_ledger_chains(&self) -> Result<LedgerChainVerification, ServerError> ;

    /// Atomically create one live transfer offer for an entry.
    async fn commit_transfer_offer(
        &self,
        command: TransferOfferCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// Fetch a transfer offer, projecting elapsed live offers as expired.
    async fn get_transfer_offer(
        &self,
        offer_id: &str,
        now: DateTime<Utc>,
    ) -> Result<Option<TransferOffer>, ServerError>;

    /// Atomically accept an offer and replace the entry with the fully
    /// recipient-signed version.
    async fn commit_transfer_accept(
        &self,
        command: TransferAcceptCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// Atomically decline a live offer.
    async fn commit_transfer_decline(
        &self,
        command: TransferDeclineCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// Atomically store a canonical attestation and its event/audit metadata.
    async fn commit_attestation(
        &self,
        command: AttestationCommitCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// List separately stored attestations, excluding expired/revoked records
    /// unless explicitly requested.
    async fn list_attestations(
        &self,
        entry_did: &str,
        now: DateTime<Utc>,
        include_expired: bool,
        include_revoked: bool,
        page: PageRequest,
    ) -> Result<Vec<VerifiableAttestationRecord>, ServerError>;

    /// Whether a credential has a locally available revocation fact.
    async fn is_attestation_revoked(&self, attestation_id: &str) -> Result<bool, ServerError>;

    /// Atomically provision bond metadata with audit/idempotency records.
    async fn commit_bond(
        &self,
        command: BondCommitCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// Atomically update self-bound peer metadata.
    async fn commit_peer(
        &self,
        command: PeerCommitCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// Atomically persist an accepted audit and exact idempotency response.
    async fn commit_audited_response(
        &self,
        command: AuditedResponseCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// Atomically commit a new entry, immutable snapshot, event, audit record,
    /// idempotency reservation, and optional anchor outbox row.
    async fn commit_create(
        &self,
        command: CreateEntryCommand,
    ) -> Result<MutationCommit, ServerError>;

    /// Atomically compare-and-set an updated entry and all mutation records.
    async fn commit_update(
        &self,
        command: UpdateEntryCommand,
    ) -> Result<MutationCommit, ServerError>;

    /// Atomically compare-and-set a revocation and all mutation records.
    async fn commit_revoke(
        &self,
        command: RevokeEntryCommand,
    ) -> Result<MutationCommit, ServerError>;

    /// Atomically append an event and its private audit record.
    async fn commit_event(&self, command: EventCommitCommand) -> Result<MarsEvent, ServerError>;

    /// Compatibility create helper. This delegates to the production commit
    /// path so fixtures cannot bypass event and audit persistence.
    async fn put_entry(&self, entry: MarsEntry) -> Result<(), ServerError> ;

    /// Get an entry by DID. Returns the latest version.
    async fn get_entry(&self, did: &str) -> Result<Option<MarsEntry>, ServerError>;

    /// Get a specific version of an entry by DID and semver string.
    async fn get_entry_version(
        &self,
        did: &str,
        version: &str,
    ) -> Result<Option<MarsEntry>, ServerError>;

    /// List a bounded page of stored versions in stable newest-first order.
    ///
    /// Implementations order by the registry-assigned sequence descending,
    /// then by semantic version descending as a deterministic tie-breaker.
    async fn list_entry_versions(
        &self,
        did: &str,
        before_sequence: Option<u64>,
        limit: u64,
    ) -> Result<EntryVersionPage, ServerError>;

    /// Compatibility update helper using a store read followed by the same CAS
    /// production commit path used by HTTP mutations.
    async fn update_entry(&self, entry: MarsEntry) -> Result<(), ServerError> ;

    /// Compatibility revoke helper delegated to the production commit path.
    async fn delete_entry(&self, did: &str) -> Result<(), ServerError> ;

    /// List all entries, optionally filtered by entry type.
    async fn list_entries(
        &self,
        entry_type: Option<&EntryType>,
        page: PageRequest,
    ) -> Result<Vec<MarsEntry>, ServerError>;

    /// Execute one validated MARS-QL query through the backend's native query
    /// engine. Durable implementations must filter, order, and keyset-page in
    /// the database rather than materializing an unbounded candidate set.
    async fn execute_query(
        &self,
        query: &crate::search::QueryExecution,
    ) -> Result<crate::search::QueryPage, ServerError>;

    /// Get the current global sequence number.
    async fn current_sequence(&self) -> Result<u64, ServerError>;

    // --- Bond operations ---

    /// Provision a bond exactly once.
    ///
    /// Existing bond IDs are immutable. Status or amount changes require a
    /// separately authorized transition API; this primitive never upserts.
    async fn put_bond(&self, bond: Bond) -> Result<(), ServerError>;

    /// Get a bond by ID.
    async fn get_bond(&self, bond_id: &str) -> Result<Option<Bond>, ServerError>;

    // --- Event log ---

    /// Append an event to the log.
    async fn append_event(&self, event: MarsEvent) -> Result<(), ServerError> ;

    /// Read a bounded event page after an optional event cursor.
    ///
    /// `None` begins at the oldest event. A nonempty cursor must exist.
    /// `page.offset()` must be zero; callers advance only with event IDs.
    async fn event_tail(
        &self,
        after_event_id: Option<&str>,
        page: PageRequest,
    ) -> Result<Vec<MarsEvent>, ServerError>;

    /// List private audit records for an entry in sequence order.
    async fn audit_records(
        &self,
        entry_did: &str,
        page: PageRequest,
    ) -> Result<Vec<AuditRecord>, ServerError>;

    /// List anchor records across hot and archive storage in stable ascending
    /// `(sequence, created_at, intent_id)` order.
    ///
    /// `None` starts at the oldest record. A cursor must exactly identify a
    /// record for `entry_did`; implementations reject unknown or cross-entry
    /// cursors and return at most `limit` records.
    async fn anchor_intents(
        &self,
        entry_did: &str,
        after: Option<&AnchorIntentCursor>,
        limit: u32,
    ) -> Result<AnchorIntentPage, ServerError>;

    /// Read one anchor intent by its stable identifier.
    async fn anchor_intent(
        &self,
        intent_id: &str,
    ) -> Result<Option<PersistedAnchorIntent>, ServerError>;

    /// Exclusively lease available work. PostgreSQL implementations must use
    /// `FOR UPDATE SKIP LOCKED` so replicas never execute the same lease.
    async fn claim_anchor_intents(
        &self,
        worker_id: &str,
        now: DateTime<Utc>,
        lease_expires_at: DateTime<Utc>,
        limit: u32,
        max_attempts: u32,
    ) -> Result<Vec<AnchorClaim>, ServerError>;

    /// Idempotently persist one adapter observation and release the claim.
    async fn persist_anchor_receipt(
        &self,
        claim: &AnchorClaim,
        receipt: AnchorReceiptRecord,
        next_available_at: DateTime<Utc>,
        persisted_at: DateTime<Utc>,
    ) -> Result<PersistedAnchorIntent, ServerError>;

    /// Persist one failed attempt, scheduling a retry or terminal abandonment.
    async fn fail_anchor_claim(
        &self,
        claim: &AnchorClaim,
        error: &str,
        retry_at: DateTime<Utc>,
        failed_at: DateTime<Utc>,
        abandon: bool,
    ) -> Result<PersistedAnchorIntent, ServerError>;

    /// Requeue a failed or abandoned intent with exact-response idempotency.
    async fn retry_anchor(
        &self,
        command: AnchorAdminCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// Permanently abandon a non-submitted intent with exact-response
    /// idempotency.
    async fn abandon_anchor(
        &self,
        command: AnchorAdminCommand,
    ) -> Result<StoredHttpResponse, ServerError>;

    /// Snapshot outbox backlog and attempt measurements.
    async fn anchor_outbox_metrics(
        &self,
        now: DateTime<Utc>,
    ) -> Result<AnchorOutboxMetrics, ServerError>;

    /// Move a bounded batch of retained terminal intents into durable archive
    /// storage while preserving their receipt history.
    async fn archive_terminal_anchor_intents(
        &self,
        before: DateTime<Utc>,
        limit: u32,
    ) -> Result<AnchorOutboxArchiveResult, ServerError>;

    // --- Federation peers ---

    /// Atomically consume one signed-envelope nonce.
    ///
    /// Returns `true` only for the first unexpired `(peer_did, nonce)` pair.
    /// Durable implementations must enforce uniqueness in the database so
    /// concurrent replicas cannot both accept the same envelope.
    async fn consume_federation_nonce(
        &self,
        peer_did: &str,
        nonce: &str,
        request_digest: &str,
        expires_at: DateTime<Utc>,
        now: DateTime<Utc>,
    ) -> Result<bool, ServerError>;

    /// Insert or update durable runtime state for a configured peer.
    async fn put_federation_peer_state(
        &self,
        state: FederationPeerState,
    ) -> Result<(), ServerError>;

    /// Read one peer's durable runtime state.
    async fn get_federation_peer_state(
        &self,
        peer_did: &str,
    ) -> Result<Option<FederationPeerState>, ServerError>;

    /// List peer runtime state in stable DID order.
    async fn list_federation_peer_states(
        &self,
        page: PageRequest,
    ) -> Result<Vec<FederationPeerState>, ServerError>;

    /// Exclusively lease peers whose retry/breaker window permits a request.
    async fn claim_federation_peers(
        &self,
        worker_id: &str,
        now: DateTime<Utc>,
        lease_expires_at: DateTime<Utc>,
        limit: u32,
    ) -> Result<Vec<FederationPeerClaim>, ServerError>;

    /// Complete a peer claim and advance its cursor monotonically.
    async fn complete_federation_peer_claim(
        &self,
        claim: &FederationPeerClaim,
        next_cursor: u64,
        remote_head: u64,
        latency_ms: u64,
        next_attempt_at: DateTime<Utc>,
        completed_at: DateTime<Utc>,
    ) -> Result<FederationPeerState, ServerError>;

    /// Fail a peer claim and persist retry/circuit-breaker state.
    async fn fail_federation_peer_claim(
        &self,
        claim: &FederationPeerClaim,
        breaker_state: mars_protocol::federation::FederationBreakerState,
        next_attempt_at: DateTime<Utc>,
        failed_at: DateTime<Utc>,
    ) -> Result<FederationPeerState, ServerError>;

    /// Persist one malicious or malformed remote payload and increment the
    /// peer's bounded status counter.
    async fn quarantine_federation_payload(
        &self,
        record: FederationQuarantineRecord,
    ) -> Result<(), ServerError>;

    /// Count quarantine records, optionally scoped to one peer.
    async fn count_federation_quarantine(&self, peer_did: Option<&str>)
        -> Result<u64, ServerError>;

    /// Idempotently apply a publisher-verified remote entry. Conflict
    /// selection and the delivery record commit in one transaction.
    async fn commit_federation_import(
        &self,
        command: FederationImportCommand,
    ) -> Result<FederationImportOutcome, ServerError>;

    /// Whether local immutable anchor evidence confirms this exact entry hash.
    async fn has_confirmed_anchor(
        &self,
        entry_did: &str,
        item_data_hash: &str,
    ) -> Result<bool, ServerError>;

    /// Snapshot durable federation metrics.
    async fn federation_metrics(&self) -> Result<FederationMetrics, ServerError>;

    /// Persist or update a peer agreement.
    async fn put_federation_agreement(
        &self,
        peer_did: &str,
        agreement: FederationAgreement,
    ) -> Result<(), ServerError>;

    /// List active agreements for one peer in stable ID order.
    async fn list_federation_agreements(
        &self,
        peer_did: &str,
        page: PageRequest,
    ) -> Result<Vec<FederationAgreement>, ServerError>;

    /// Append a signed federation request audit record.
    async fn commit_federation_audit(&self, audit: AuditRecord) -> Result<(), ServerError>;

    /// Register or update a federation peer.
    async fn put_peer(&self, peer: FederationPeer) -> Result<(), ServerError>;

    /// List a bounded page of known federation peers.
    async fn list_peers(&self, page: PageRequest) -> Result<Vec<FederationPeer>, ServerError>;

    /// Get entries changed since a given sequence number (for federation sync).
    ///
    /// Returns `(entries, next_sequence, has_more)`.
    async fn entries_since_sequence(
        &self,
        from_seq: u64,
        max: u32,
    ) -> Result<(Vec<MarsEntry>, u64, bool), ServerError>;

    /// Liveness probe for the storage backend.
    ///
    /// Default implementation always returns `Ok(())`. The PostgreSQL backend
    /// overrides this to execute a `SELECT 1` round-trip so the deep health
    /// endpoint can detect connection pool exhaustion or a downed database.
    async fn health_check(&self) -> Result<(), ServerError> ;
}

Source line: 1284.

store::ShardedStore

Storage backend trait for shard-aware operations.

When the sharding feature is enabled, this trait extends the storage layer with shard routing, placement, and scatter-gather capabilities.

#[cfg(feature = "sharding")]
#[async_trait]
pub trait ShardedStore: Send + Sync {
    /// Get the shard IDs managed by this store.
    fn shard_ids(&self) -> Vec<String>;

    /// Get the store for a specific shard.
    fn shard_store(&self, shard_id: &str) -> Option<std::sync::Arc<dyn EntryStore>>;

    /// Assign an entry to a shard based on its DID and publisher DID.
    fn assign_shard(&self, entry_did: &str, publisher_did: &str) -> Result<String, ServerError>;

    /// Execute a query against specific shards (scatter).
    ///
    /// If `shard_ids` is empty, queries all shards.
    async fn scatter_query(
        &self,
        shard_ids: &[String],
        query: &mars_protocol::marsql::ast::MarsQuery,
    ) -> Result<Vec<MarsEntry>, ServerError>;
}

Source line: 1771.

Source provenance

Source: mars-server/src/store/mod.rs · SHA-256 ba6b32053130efece077c63639b344eecbb61afab1e265d1d5c675abc2f19d07. Package overview.

On this page

store::memorystore::postgresstore::sharded_memorypub use mars_protocol::anchoring::AnchorOperation;store::EntryVersionPagestore::PageRequeststore::PageRequest::MAX_LIMITstore::PageRequest::newstore::PageRequest::firststore::PageRequest::offsetstore::PageRequest::limitstore::PageRequest::advancestore::AuditActionstore::AuditOutcomestore::AuditContextstore::AuditContext::newstore::AuditRecordstore::AuditRecord::newstore::AuditRecord::acceptedstore::AuditRecord::rejectedstore::AuditChainVerificationstore::EventChainVerificationstore::LedgerChainVerificationstore::AnchorIntentstore::PersistedAnchorIntentstore::AnchorIntentCursorstore::AnchorIntentCursor::MAX_ENCODED_LENstore::AnchorIntentCursor::from_intentstore::AnchorIntentCursor::encodestore::AnchorIntentCursor::decodestore::AnchorIntentPagestore::AnchorClaimstore::AnchorOutboxMetricsstore::AnchorOutboxArchiveResultstore::AnchorAdminCommandstore::StoredHttpResponsestore::StoredHttpResponse::jsonstore::StoredHttpResponse::emptystore::StoredHttpResponse::into_axum_responsestore::IdempotencyRequeststore::IdempotencyRequest::for_test_entry_projectionstore::IdempotencyRequest::for_entry_projectionstore::IdempotencyRequest::for_stored_responsestore::MutationMetadatastore::CreateEntryCommandstore::CreateEntryCommand::newstore::CreateEntryCommand::with_idempotencystore::CreateEntryCommand::with_anchor_intentstore::CreateEntryCommand::with_bond_recheckstore::UpdateEntryCommandstore::UpdateEntryCommand::newstore::UpdateEntryCommand::with_audit_actionstore::UpdateEntryCommand::with_idempotencystore::UpdateEntryCommand::with_anchor_intentstore::UpdateEntryCommand::with_bond_recheckstore::RevokeEntryCommandstore::RevokeEntryCommand::newstore::RevokeEntryCommand::with_idempotencystore::RevokeEntryCommand::with_anchor_intentstore::EventCommitCommandstore::EventCommitCommand::newstore::EventCommitCommand::with_audit_actionstore::EventCommitCommand::with_idempotencystore::RejectedMutationCommandstore::TransferOfferCommandstore::TransferAcceptCommandstore::TransferDeclineCommandstore::AttestationCommitCommandstore::BondCommitCommandstore::PeerCommitCommandstore::FederationPeerStatestore::FederationPeerState::newstore::FederationPeerState::statusstore::FederationPeerClaimstore::FederationQuarantineReasonstore::FederationQuarantineRecordstore::FederationImportCommandstore::FederationImportOutcomestore::FederationMetricsstore::AuditedResponseCommandstore::RejectedMutationCommand::newstore::RejectedMutationCommand::with_idempotencystore::MutationCommitstore::EntryStorestore::ShardedStoreSource provenance