Skip to main content

Crate hydracache

Crate hydracache 

Source
Expand description

User-facing HydraCache runtime.

HydraCache is local-first: HydraCache::local has no network dependency. Optional client/member builders add the first cluster API shape on top of the same local cache and distributed invalidation bus.

§Quick start

use std::time::Duration;

use hydracache::{CacheOptions, HydraCache};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
}

let cache = HydraCache::local()
    .default_ttl(Duration::from_secs(300))
    .max_capacity(10_000)
    .build();

let user = cache
    .get_or_insert_with("user:42", CacheOptions::new().tag("user:42"), || async {
        User {
            id: 42,
            name: "Ada".to_owned(),
        }
    })
    .await?;

assert_eq!(user.id, 42);
cache.invalidate_tag("user:42").await?;

§Cacheable functions

Use cacheable_loader! when an ordinary async function or expensive operation should be cached without introducing database-result-cache concepts. cacheable_loader! wraps fallible loaders. cacheable_infallible! wraps loaders that return a value directly.

use std::time::Duration;

use hydracache::{cacheable_loader, cacheable_infallible, HydraCache};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Report {
    id: u64,
}

#[derive(Debug)]
struct LoadError;

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("load failed")
    }
}

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

let cache = HydraCache::local().build();

let report = cacheable_loader!(
    cache = cache,
    key = "report:42",
    tags = ["reports", "report:42"],
    ttl = Duration::from_secs(60),
    load = || async { Ok::<_, LoadError>(Report { id: 42 }) },
)
.await?;

assert_eq!(report.id, 42);

let total = cacheable_infallible!(
    cache = cache,
    key = "report-total:42",
    tags = ["reports", "report:42"],
    ttl_secs = 60,
    load = || async { 42_u64 },
)
.await?;

assert_eq!(total, 42);

Use CacheKeyBuilder and TagSet when the key and invalidation tags are generated from the same domain metadata:

use hydracache::{cacheable_loader, CacheKeyBuilder, HydraCache, TagSet};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Profile {
    id: u64,
}

#[derive(Debug)]
struct LoadError;

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("load failed")
    }
}

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

let cache = HydraCache::local().build();
let profile_id = 42_u64;
let key = CacheKeyBuilder::new()
    .entity("profile", profile_id)
    .build_string();

let profile = cacheable_loader!(
    cache = cache,
    key = key.as_str(),
    tags = TagSet::new().tag("profiles").entity("profile", profile_id),
    ttl_secs = 60,
    load = move || async move {
        Ok::<_, LoadError>(Profile { id: profile_id })
    },
)
.await?;

assert_eq!(profile.id, 42);
cache.invalidate_tag("profile:42").await?;

Use cacheable when the cached operation is naturally an async function. The cache remains an explicit argument; the generated wrapper returns CacheResult because cache errors can occur outside the user loader:

use hydracache::{cacheable, HydraCache};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Profile {
    id: u64,
}

#[derive(Debug)]
struct LoadError;

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("load failed")
    }
}

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

#[cacheable(
    cache = cache,
    key_segments = ["profile", profile_id],
    tag_segments = [["profile", profile_id], ["profiles"]],
    ttl_secs = 60
)]
async fn load_profile(
    cache: &HydraCache,
    profile_id: u64,
) -> Result<Profile, LoadError> {
    Ok(Profile { id: profile_id })
}

let cache = HydraCache::local().build();
let profile = load_profile(&cache, 42).await?;

assert_eq!(profile.id, 42);

§Typed local cache

use hydracache::{CacheOptions, HydraCache};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
}

let cache = HydraCache::local().build();
let users = cache.typed::<User>("users");

users
    .put(
        "42",
        User {
            id: 42,
            name: "Ada".to_owned(),
        },
        CacheOptions::new(),
    )
    .await?;

let cached = users.get("42").await?;
assert_eq!(cached.map(|user| user.id), Some(42));

§Cache events

Use HydraCache::subscribe when an application, actuator, or sandbox wants to observe cache mutations without wrapping every call manually. Access/load events are opt-in because hit/miss streams can be noisy.

use hydracache::{CacheEventKind, CacheOptions, HydraCache};

let cache = HydraCache::local().build();
let mut events = cache.subscribe_mutations();

cache
    .put("user:42", 42_u64, CacheOptions::new().tag("users"))
    .await?;

let event = events.recv().await.expect("stored event");
assert_eq!(event.kind(), CacheEventKind::Stored);
assert_eq!(event.key(), Some("user:42"));
assert_eq!(event.tags(), &["users".to_owned()]);

Callback listeners are adapters over the same subscription stream:

use hydracache::{CacheOptions, HydraCache};

let cache = HydraCache::local().build();
let listener = cache.on_mutation(|event| {
    println!("cache changed: {event:?}");
});

cache.put("user:42", 42_u64, CacheOptions::new()).await?;
listener.unsubscribe();

Event publication is preflighted before HydraCache builds owned event payloads. If an event kind is disabled or no active subscriber can receive it, the cache operation skips the event allocation path. Access events still require both a subscriber and HydraCacheBuilder::enable_access_events.

use hydracache::{CacheEventKind, CacheOptions, HydraCache};

let quiet_cache = HydraCache::local().build();
quiet_cache
    .put("user:42", "Ada", CacheOptions::new().tag("users"))
    .await?;
assert_eq!(quiet_cache.stats().events_published, 0);

let observed_cache = HydraCache::local().build();
let mut events = observed_cache.subscribe_mutations();
observed_cache
    .put("user:43", "Grace", CacheOptions::new().tag("users"))
    .await?;

let event = events.recv().await.expect("stored event");
assert_eq!(event.kind(), CacheEventKind::Stored);
assert_eq!(observed_cache.stats().events_published, 1);

§Distributed invalidation bus

Use InMemoryInvalidationBus when several cache instances in one process should propagate invalidation intent to each other. The bus only sends invalidate_key, invalidate_tag, remove, and flush operations; cached values are not replicated.

use std::sync::Arc;
use std::time::Duration;

use hydracache::{CacheEventOrigin, CacheOptions, HydraCache, InMemoryInvalidationBus};

let bus = Arc::new(InMemoryInvalidationBus::default());
let first = HydraCache::local()
    .shared_invalidation_bus(bus.clone())
    .invalidation_node_id("first")
    .build();
let second = HydraCache::local()
    .shared_invalidation_bus(bus)
    .invalidation_node_id("second")
    .build();

first
    .put("user:42", 42_u64, CacheOptions::new().tag("users"))
    .await?;
second
    .put("user:42", 42_u64, CacheOptions::new().tag("users"))
    .await?;

let mut events = second.subscribe_tag("users");
first.invalidate_tag("users").await?;

// Remote invalidation is applied by a background task, so applications that
// need to observe it immediately should wait on events or diagnostics.
let event = tokio::time::timeout(Duration::from_millis(500), events.recv())
    .await
    .expect("remote invalidation event")
    .expect("subscription stays open");

assert_eq!(event.origin(), CacheEventOrigin::DistributedBus);
assert!(!second.contains_key("user:42").await);

// Runtime counters expose the same path for diagnostics and metrics.
let _publisher_stats = first.stats();
let _receiver_stats = second.stats();

InMemoryFramedInvalidationBus is a transport spike for cross-process adapters. It serializes each message into CacheInvalidationFrame bytes before delivery, so tests can exercise the same encoding boundary future TCP, Redis, NATS, or Postgres adapters will need.

Custom transports implement CacheInvalidationBus and return CacheInvalidationReceive::Message, CacheInvalidationReceive::Lagged, CacheInvalidationReceive::DecodeError, or CacheInvalidationReceive::Closed from their receivers. HydraCache records lag, decode errors, publish failures, and closed receivers in hydracache_core::CacheStats so applications can detect bus health issues without parsing logs.

§Client and member cluster mode

HydraCache::client creates an application-side near-cache. HydraCache::member creates an in-process cluster member. In v0.20 both can share an InMemoryCluster for tests, demos, and embedded applications while the future discovery/Raft adapters are still being designed. Custom adapters can implement ClusterDiscovery for discovery/liveness and ClusterControlPlane for admission/metadata decisions. ChitchatStyleDiscovery is a dependency-free seed-node discovery spike that records chitchat-shaped candidates and liveness events without starting a network runtime. RaftStyleMetadataControlPlane is a dependency-free metadata-log spike that records committed membership commands and snapshots without starting a Raft runtime.

use std::sync::Arc;

use hydracache::{
    CacheEventOrigin, CacheOptions, ClusterGeneration, HydraCache, InMemoryCluster,
    InMemoryClusterDiscovery,
};

let cluster = Arc::new(InMemoryCluster::new("orders-prod"));
let discovery = Arc::new(InMemoryClusterDiscovery::new());

let member = HydraCache::member()
    .cluster("orders-prod")
    .shared_cluster(cluster.clone())
    .shared_discovery(discovery.clone())
    .node_id("member-a")
    .generation(ClusterGeneration::new(1))
    .bind("127.0.0.1:7000")
    .start()
    .await?;

let client = HydraCache::client()
    .cluster("orders-prod")
    .shared_cluster(cluster)
    .shared_discovery(discovery.clone())
    .node_id("api-client-a")
    .bootstrap("127.0.0.1:7000")
    .connect()
    .await?;

client
    .put("user:42", 42_u64, CacheOptions::new().tag("user:42"))
    .await?;

let mut events = client.subscribe_tag("user:42");
member.invalidate_tag("user:42").await?;

let event = events.recv().await.expect("subscription stays open");
assert_eq!(event.origin(), CacheEventOrigin::DistributedBus);
assert!(!client.contains_key("user:42").await);

let diagnostics = client.cluster_diagnostics().expect("cluster runtime");
assert_eq!(diagnostics.member_count, 1);
assert_eq!(diagnostics.client_count, 1);
assert!(diagnostics.lifecycle.is_running());
assert_eq!(discovery.candidates().len(), 2);

client.leave_cluster().await?;
assert!(client.cluster_diagnostics().unwrap().lifecycle.is_stopped());

§Observability

Use HydraCache::diagnostics for quick local smoke checks. It combines lightweight stats with the approximate local backend entry count.

use hydracache::{CacheOptions, HydraCache};

let cache = HydraCache::local().build();

let first = cache
    .get_or_insert_with("answer", CacheOptions::new(), || async { 42_u64 })
    .await?;
let second = cache
    .get_or_insert_with("answer", CacheOptions::new(), || async { 7_u64 })
    .await?;

let diagnostics = cache.diagnostics().await;
assert_eq!((first, second), (42, 42));
assert_eq!(diagnostics.stats.loads, 1);
assert_eq!(diagnostics.stats.hits, 1);
assert_eq!(diagnostics.hit_ratio(), Some(0.5));

Modules§

testing
Deterministic staging helpers for HydraCache release gates and sandbox labs.

Macros§

cacheable_infallible
Cache an ordinary async loader that cannot fail in application terms.
cacheable_loader
Cache an ordinary fallible async loader with explicit local-cache metadata.

Structs§

AckRequirement
Acknowledgement requirement computed from a consistency level and effective placement.
ActiveActiveConfig
Active-active mode configuration for one cache/grid slice.
ActiveActiveConfigError
Error returned when active-active is requested without the loud acknowledgement.
ActiveActiveState
Deterministic active-active state machine used by release gates and adapters.
AdaptiveWindow
AIMD flow-control window for one backup replication stream.
AdmissionController
Admission controller with FIFO backlog.
AdmissionLimits
Admission limits for count, memory and backlog.
AdmissionPermit
Permit returned for admitted work.
AdmissionQueueTicket
FIFO queue ticket.
AdmissionSnapshot
Admission controller snapshot.
AntiEntropyTask
Throttled anti-entropy executor config.
AppliedSet
Locally applied dependency high-water stamps.
AtRestSealer
At-rest artifact sealer.
AtomicInvalidationError
Error returned by atomic invalidation helpers.
AutoRepairDecision
Auto-repair decision.
AutoRepairPolicy
Policy for operational self-healing.
AutoscalerAdmission
Accepted autoscaler admission result.
AutoscalerAdmissionPolicy
Guardrails used to admit an autoscaler intent.
AutoscalerIntentError
Error returned by autoscaler intent admission.
BackupDataset
Source/restore dataset used by the backup seam.
BackupEntry
One manifest entry.
BackupManifest
Full backup manifest.
BackupPromotion
Backup promotion operation for one partition.
BatchInvalidationState
Deterministic state machine for validating batch atomicity.
BoundedStalenessMetrics
Bounded staleness metrics.
CacheDiagnostics
User-facing diagnostic snapshot for a local cache instance.
CacheEvent
Metadata-only cache event.
CacheEventListenerHandle
Handle for a callback-style cache event listener.
CacheEventOptions
Subscription filters for cache events.
CacheEventSubscriber
Receiver for cache events emitted by one HydraCache.
CacheInvalidationFrame
Binary envelope for invalidation messages that cross a process boundary.
CacheInvalidationMessage
Invalidation message published on a CacheInvalidationBus.
CacheKey
A logical cache key.
CacheKeyBuilder
Builder for cache keys made of escaped :-separated segments.
CacheOptions
Per-entry cache behavior.
CacheStats
Snapshot of lightweight cache counters.
CapacityAutoscalerMetrics
Bounded metric snapshot for capacity/autoscaler surfaces.
CapacitySample
One capacity sample consumed by the recommendation engine.
CapacitySignal
Structured capacity signal exported by status/metrics.
CapacityThresholds
Tunables for capacity recommendations.
CausalApplyDeferred
Error returned when a causal write is not yet visible.
CausalConsistencyMetrics
Causal consistency metrics.
CausalSummary
Bounded causal dependency summary carried by a session write.
CausalWrite
Session write with attached causal dependency summary.
CertificateBundle
Certificate material tracked during a rotation window.
CertificateRotationWindow
Certificate rotation window that accepts current and explicitly retained previous certs.
CheckpointCoordinator
In-memory coordinator for cluster-wide checkpoint collection.
ChecksummedReplicatedValueRecord
Durable replicated value record plus checksum metadata.
ChitchatStyleDiscovery
Dependency-free, chitchat-style discovery adapter for tests and API spikes.
ClusterAdmissionBridge
Polls discovery candidates and admits them into an authoritative control plane.
ClusterAdmissionBridgeConfig
Polling behavior for ClusterAdmissionBridge.
ClusterAdmissionBridgeDiagnostics
Lightweight counters for a cluster admission bridge.
ClusterAdmissionBridgeHandle
Handle for a background ClusterAdmissionBridge polling task.
ClusterCacheCounters
Three-part groupcache-style counters for pilot dashboards.
ClusterCandidate
Candidate discovered before authoritative membership admission.
ClusterCheckpointError
Error returned by checkpoint collection, verification, and restore fencing.
ClusterCheckpointManifest
Cluster-wide consistent cut over durable per-node snapshot manifests.
ClusterComponentError
Error returned by a background cluster component.
ClusterDiagnostics
ClusterDiscoveryDiagnostics
Discovery diagnostics visible from a HydraCache client/member runtime.
ClusterEndpoints
ClusterEpoch
Committed cluster metadata epoch.
ClusterFillCounters
Point-in-time owner/remote/hot fill counters for cluster staging.
ClusterGeneration
Monotonic process generation for a cluster node id.
ClusterGridCounters
Aggregate grid counters; high-cardinality detail stays in diagnostics.
ClusterGridDiagnostics
High-cardinality grid detail kept out of metrics.
ClusterLifecycleComponent
Minimal reusable lifecycle component for adapters that already own work.
ClusterLifecycleDiagnostics
Point-in-time lifecycle diagnostics for an embedded cluster component.
ClusterLoadReport
Structured cluster load report used by deterministic staging gates.
ClusterMember
Admitted cluster participant snapshot.
ClusterMembershipSubscriber
Receiver for cluster membership events from a control plane.
ClusterMergeOutcome
Result of applying a merge policy.
ClusterMetricDescriptor
Bounded metric descriptor used by cardinality tests and exporters.
ClusterNode
IO-free cluster node state machine.
ClusterNodeConfig
Configuration for a sans-IO cluster node.
ClusterNodeId
Stable logical id for a HydraCache cluster participant.
ClusterOwnershipDecision
ClusterOwnershipDiagnostics
Ownership diagnostics visible from a cluster control plane.
ClusterPeerFetchDiagnostics
Point-in-time counters for an InMemoryPeerFetch registry.
ClusterPeerFetchGenerationMismatch
Requested owner generation did not match the current owner generation.
ClusterPeerFetchRequest
ClusterPeerFetchResponse
Response returned by a peer-fetch implementation.
ClusterPilotReadiness
Boolean readiness contract for a controlled internal production pilot.
ClusterPilotReport
Dashboard-ready pilot snapshot.
ClusterStagingCounters
Additional staging counters that do not belong to local cache stats.
ClusterStagingHealth
Staging-focused health summary derived from diagnostics and counters.
CompatVersion
Semantic version used by upgrade guard checks.
ConditionalMetrics
Conditional-write metrics.
ConsistencyInvalidate
ConsistencyReadiness
Readiness summary for read-after-write overlap at chosen levels.
ConsistencyToken
ConsistencyUnsatisfiable
Loud error returned when a requested consistency level cannot be satisfied.
ConsumerIsolation
Tenant isolation state.
ConsumerIsolationConfig
Process-global and tenant admission limits.
ControlPlaneSnapshot
Control-plane snapshot used by backup/restore.
CrdtMergeStats
Bounded-label CRDT merge counters.
CrdtMetadataGcGate
Confirmation gate for CRDT metadata GC.
Diagnostics
User-facing diagnostic snapshot for a local cache instance.
DiscardLoser
Always discard loser-side entries.
DurabilityError
Durability write-path error.
DurabilityMetricsSnapshot
Bounded aggregate metrics for the durability path.
DurabilitySnapshotManifest
Durable snapshot manifest with a checksum-protected recovery watermark.
DurabilityWritePath
Durability write-path coordinator for one local node.
EffectiveReplicationMap
Effective placement used while rebalance is in flight.
FailureDetectorMetrics
Metrics emitted by the detector.
FenceToken
Monotonic fencing token returned by a lock acquisition.
ForegroundReadRepairOutcome
Result of foreground read-repair.
GCounter
Grow-only counter CRDT.
GeoBatch
WAN replication batch. Compression is represented by deterministic accounting; adapters can map the payload to their concrete wire codec.
GeoBatchApplyReport
Apply report for one received batch.
GeoWrite
Active-active write stamped at the accepting region.
GeoWriteAck
Result of accepting a local write.
HedgePolicy
Adaptive hedge delay source.
HedgedReadPlan
Hedged read execution plan.
HigherVersionWins
Default policy: keep the highest (version, epoch) and let tombstones win ties through ReplicatedValueRecord::merge.
Hint
Missed write captured for a replica that was temporarily unavailable.
HintBudget
Bounded hint retention policy.
HintError
Errors returned by hint storage.
HintMetrics
Hint store metrics with bounded labels represented by counters.
HotCacheDirectory
Tracks which nodes hold hot copies for authoritative invalidation fan-out.
HybridLogicalClock
Hybrid logical clock timestamp used for deterministic cross-region tie-breaks.
HydraCache
Local async cache runtime.
HydraCacheBuilder
Builder for a local HydraCache instance.
HydraCacheClientBuilder
Builder for a client near-cache connected to a HydraCache cluster.
HydraCacheMemberBuilder
Builder for an in-process HydraCache cluster member.
IdempotencyKey
Idempotency key attached to a cross-region replication write.
InMemoryCluster
In-process cluster model for tests, demos, and the first client/member API.
InMemoryClusterDiscovery
In-memory discovery journal for tests, demos, and future adapter contracts.
InMemoryClusterStorage
In-memory deterministic storage implementation useful for tests.
InMemoryFramedInvalidationBus
In-memory framed invalidation bus for cross-process transport experiments.
InMemoryHintStore
In-memory bounded hint store used by tests and embedded adapters.
InMemoryInvalidationBus
In-process invalidation bus for tests, demos, and embedded multi-cache apps.
InMemoryObjectStore
In-memory object store for tests and examples.
InMemoryPeerFetch
In-memory peer-fetch implementation for tests, demos, and sandbox reports.
InMemoryReplicatedValueStore
Deterministic in-memory implementation used by the fast 0.42 tests and as the model for durable engine semantics.
InMemorySnapshotSink
In-memory snapshot sink used by tests and examples.
InMemoryTransport
In-memory transport endpoint used by W1/W5 deterministic tests.
InvalidateBatch
Single-partition invalidation batch.
InvalidationEvent
Sequence-numbered invalidation retained for replay.
InvalidationRelay
Async relay between a local invalidation bus and an external transport.
InvalidationRelayHandle
Running invalidation relay with observable metrics.
InvalidationRing
Bounded replayable invalidation ring for one partition.
InvalidationRingMetrics
Ring metrics with bounded label sets represented as counters.
InvalidationRingSnapshot
Durable-adapter snapshot of the recent invalidation window.
InvalidationSaga
Cross-partition best-effort invalidation fan-out unit.
InvalidationTarget
One target of a best-effort invalidation saga.
KeyMaterial
Operator-supplied key material.
KeyRange
Inclusive key range that needs repair.
LiveReadYourWritesDecision
Live read-path decision, including readiness posture.
LiveReplicationPeer
Peer-local replication stream state.
LiveReplicationSend
Outcome of one live replication send attempt.
LiveSplitBrainResolution
Result of resolving a healed split-brain against live side snapshots.
LoadBreakerPolicy
Per-key loader circuit-breaker policy.
LockHold
Current state of one held fenced lock.
LockOwner
Owner identity for a session-bound fenced lock.
LogicalDuration
Logical simulator duration in milliseconds.
LogicalTime
Logical simulator time in milliseconds.
LwwRegister
Last-writer-wins register CRDT using HLC as the deterministic tie-break.
ManualClusterClock
Manually advanced clock for tests and simulators.
MerkleTree
Compact Merkle representation for one partition.
MetaDataContainer
Per-partition near-cache watermark metadata.
MonotonicReadViolation
Error returned by strict monotonic read application.
MonotonicWriteViolation
Error returned by strict monotonic write application.
NamespaceMetricLabels
Bounded namespace labels for durability metrics.
NamespacePersistenceRule
One ordered persistence rule.
NamespacePersistenceSettings
Concrete rule applied after namespace pattern matching.
NamespaceQuota
Quota for one tenant-owned namespace.
NodeCheckpointManifest
Per-node durable manifests collected for a cluster-wide checkpoint.
NodeTopology
Authoritative topology attached to a cluster node.
Options
Per-entry cache behavior.
OrSet
Observed-remove set CRDT.
OrSetTag
Unique add/remove tag used by OR-set entries.
OutboundClusterMessage
Message ready to be sent by a production or simulator driver.
PartitionDigest
Digest exchanged by regions during anti-entropy.
PartitionId
Stable partition id used as a thin indirection over rendezvous ownership.
PartitionKey
Session-visible partition/region dependency key.
PartitionMove
One resumable partition movement.
PartitionReplicaVersions
Per-replica version table used by anti-entropy.
PersistenceConfig
Declarative persistence configuration mirroring Hazelcast-style per-map blocks.
PersistenceConfigError
Persistence config validation error.
PersistenceMaintenance
Durable maintenance settings resolved from persistence config.
PersistenceMaintenanceConfig
Serde-friendly durable maintenance config.
PersistenceNamespaceConfig
Per-namespace persistence config.
PersistencePolicy
Deterministic namespace persistence policy.
PersistencePolicyError
Persistence policy construction/validation error.
PersistenceRecoveryConfig
Recovery settings in serde-friendly seconds.
PersistenceRegionPlacement
Placement regions for a namespace used by persistence-region validation.
PhiAccrualConfig
Phi-accrual detector configuration.
PhiAccrualDetector
Adaptive heartbeat detector that outputs suspicion level, not ownership.
PitrLog
PITR log shipped after a full backup checkpoint.
PitrRecord
One point-in-time restore change record.
PnCounter
Positive-negative counter CRDT.
PostcardCodec
Default compact binary codec for v0.
PromotionFreezeWindow
Measured write-freeze window for backup promotion.
PutIfAbsent
Keep loser entries only when the winner side has no value.
QuorumReadDecision
Decision returned by a quorum read.
RaftMetadataSnapshot
Snapshot of the raft-style metadata journal.
RaftStyleMetadataControlPlane
Dependency-free, raft-style cluster metadata control plane.
ReadOptions
Read options carrying the per-operation consistency override.
RebalancePlan
Rebalance plan committed by the single coordinator.
RebalanceTaskAck
Acknowledgement for one rebalance task.
RecoveredNamespace
Recovery result for one namespace.
RecoveryError
Recovery error.
RecoveryNamespace
Namespace recovery input.
RecoveryPolicy
Full-cluster-restart recovery policy.
RecoveryReport
Aggregate recovery report.
RefreshOptions
Refresh behavior for loader-based cache reads.
RegionFailoverError
Error returned by region failover helpers.
RegionFailoverMetrics
Bounded metric snapshot for region failover surfaces.
RegionId
Stable region identifier used by zone-aware placement.
RegionLink
WAN-aware replication link state.
RegionLinkError
Error returned by region-link helpers.
RegionObservation
Conservative input for region-state detection.
RegionPromotion
Region-home promotion committed through the control-plane topology epoch.
RegionPromotionReport
Result of a region-home promotion.
RegionRestore
DR restore input: control-plane snapshot plus operator-restored durable values.
RegionRestoreError
Error returned by DR restore helpers.
RegionRestoreOutcome
Completed DR restore result.
RegionRestoreReport
Operator-visible DR restore report.
RegionStateDetector
Conservative detector: automatic checks can only move a region to Suspect.
RendezvousClusterOwnership
Deterministic rendezvous-style ownership resolver.
RepairReport
Report from one repair session run.
RepairSession
Repair session state for one partition.
RepairToken
Incremental repair watermark.
RepairingTask
Per-partition near-cache repair task.
ReplicaObservation
Health and latency observation for one replica.
ReplicaScorer
EWMA/zone-aware replica scorer.
Replicas
Primary plus backup owners for one replicated key or partition.
ReplicatedValueRecord
Durable replicated value record keyed externally by cache key.
ReplicationConfig
Replication/quorum configuration for the 0.41 grid slice.
ReplicationCryptoError
Error returned by replication encryption/decryption providers.
ReplicationPayload
Prepared replicated payload plus posture metadata.
RescaleWithCheckpointPlan
Reshard plan bound to a verified cluster-wide checkpoint.
ReshardPlan
Resumable online resharding plan.
ReshardPlanError
Error returned when a move would break placement invariants.
ResidencyAuditEvent
Append-only residency audit event retained until W6 installs a pluggable sink.
ResidencyLinkSendReport
WAN send report after applying residency governance.
ResidencyMetricsSnapshot
Bounded residency metrics.
ResidencyNarrowingReport
Report for policy-narrowing remediation.
ResidencyPolicy
A namespace/key residency policy committed through the authoritative control plane.
ResidencyPolicyEnforcer
Runtime policy enforcer for placement, WAN movement, reads, and policy changes.
ResidencyPolicyError
Error returned while committing or validating residency policies.
ResidencyPolicySet
Authoritative residency policy set.
ResidencyRejection
Loud residency rejection surfaced to callers and audit sinks.
ResidencyValueLocation
One value location used when a narrowed policy is evaluated.
ResolvedPersistence
Resolved namespace persistence decision.
ScrubError
Scrubber error with key context.
ScrubReport
Scrubber run report.
Scrubber
Rate-limited replicated-record scrubber.
SealedArtifact
Persistable sealed at-rest artifact.
SessionContextMetrics
Aggregate session-context metrics.
SessionFailoverRecovery
Bounded failover recovery report for diagnostics/audit.
SessionGuaranteeUnmet
Error returned when a session guarantee cannot be met within budget.
SessionHeartbeats
Logical heartbeat table for session-owned fenced locks.
SessionId
Stable client/application session id.
SessionMonotonicMetrics
Session monotonicity metrics.
SessionReadBudget
Escalation budget for a session read.
SessionRywMetrics
Session RYW metrics.
SessionSequence
Monotonic per-session sequence assigned by the caller or session coordinator.
SessionToken
Tamper-evident client-carried session token.
SessionTtl
Session token TTL in logical milliseconds.
SessionWatermark
Bounded session watermark carried by the client token.
SessionWriteStamp
Last accepted write stamp for one session and partition.
SingleKeyConditionalStore
Deterministic single-key conditional store backed by versioned records.
SnapshotError
Snapshot sink error.
SplitBrainReport
Split-brain merge report retained in diagnostics.
StalenessBound
Explicit staleness budget for a session read.
StaticAtRestKeyProvider
Static key provider useful for tests and operator-wired deployments.
Stats
Snapshot of lightweight cache counters.
StorageOp
Storage request ready to be performed by the driver.
StorageResult
Storage result returned by the driver.
TagSet
A reusable set of cache invalidation tags.
Tenant
Configured tenant.
TenantId
Bounded tenant identifier from the configured roster.
TenantMetricsSnapshot
Bounded tenant metrics.
TenantRoster
Configured tenant roster. Unknown tenants are refused before metrics labels.
TieredValueStore
Two-tier replicated value store used by the 0.43 tiering gate.
TombstoneBudget
Tombstone retention budget.
TombstoneTracker
Small deterministic tombstone budget tracker used by the 0.41 gate tests.
TopologyAuthority
Control-plane-owned topology catalog. Gossip observations never become authoritative until committed here.
TopologyFence
Minimal epoch fence for topology-authoritative decisions.
TransportConfig
Configuration for an invalidation relay.
TransportMetricDescriptor
Static metric descriptor used by observability adapters.
TransportMetrics
Bounded-label invalidation relay counters.
TransportMetricsSnapshot
Snapshot of invalidation relay counters.
TransportPosture
Transport-security posture declared for a controlled cluster pilot.
TypedCache
A typed, namespaced view over a HydraCache.
UpgradeGuard
Upgrade guard backed by the compatibility register.
UpgradeGuardError
Upgrade guard error.
UpgradeStep
One rolling-upgrade step.
ValueStoreError
Value-store admission error.
VersionStamp
Version stamp used by session watermarks.
VersionSummary
Per-partition version summary for cross-region anti-entropy.
WriteBarrierToken
WriteOptions
Write options carrying the per-operation consistency override.
WriteWatermark
Client-carried write watermark for read-your-writes reads.
ZoneAwareReplicaSet
Replica set with topology tags and underspread diagnostics.
ZoneAwareReplicationStrategy
Zone-aware placement strategy that preserves flat rendezvous behavior when all nodes belong to one zone.
ZoneId
Stable availability-zone identifier used by placement and locality reads.
ZonePlacementReadiness
Readiness report for zone-aware placement.

Enums§

ActiveActiveAcknowledgement
Explicit acknowledgement that active-active weakens cross-region consistency.
AdmissionError
Admission error returned instead of unbounded queueing.
AdmissionRejection
Structured admission rejection.
AdmissionRejectionReason
Retryable rejection reason.
ApplyDecision
Causal apply decision.
AutoscalerIntent
Autoscaler membership intent accepted through the guarded admission surface.
BackupError
Backup and restore errors.
CacheError
Errors returned by HydraCache.
CacheEventKind
Kind of cache event emitted by a HydraCache runtime.
CacheEventOrigin
Origin of a cache event.
CacheEventRecvError
Error returned by CacheEventSubscriber::recv.
CacheEventScope
Logical scope affected by a cache event.
CacheEventValueMode
Value payload mode requested by event subscribers.
CacheInvalidation
Cache invalidation operation that can be propagated to another cache node.
CacheInvalidationReceive
Result of polling an invalidation receiver.
CasResult
Result of a single-key compare-and-set operation.
CausalDependencyMissing
Dependency that is missing before a causal write can become visible.
ClientAck
Immediate acknowledgement returned by the sans-IO node.
ClientOp
Client operation accepted by the sans-IO node.
ClusterAdmissionBridgeEvent
Event emitted by a cluster admission bridge.
ClusterAdmissionIgnoreReason
Reason why the admission bridge ignored a discovered candidate.
ClusterAdmissionRejectReason
Reason why the admission bridge rejected a discovered candidate.
ClusterCheckpointErrorKind
Stable checkpoint error kind used by recovery and tests.
ClusterDiscoveryEvent
ClusterHealthReason
Machine-readable reason used by ClusterHealthState.
ClusterHealthState
Derived staging health state with machine-readable reasons.
ClusterLifecycleStatus
Lifecycle state for an embedded cluster component.
ClusterMembershipEvent
ClusterMembershipRecvError
Error returned by ClusterMembershipSubscriber::recv.
ClusterNodeMessage
Transport-neutral cluster message emitted by a sans-IO node.
ClusterReplicaConfigError
Replica/quorum pilot configuration error.
ClusterRole
Runtime role of a HydraCache instance.
ConditionalError
Errors returned by conditional writes and fenced locks.
ConsistencyLevel
Per-operation consistency level for grid reads, writes, and invalidations.
ConsistencyMode
ConsistencyOutcome
DegradeReason
DurabilityErrorKind
Stable durability error kind.
DurableWriteOutcome
Result of routing one write through the durability path.
HintOutcome
Outcome of admitting or replaying a hint.
HintReplayDecision
Result of applying a hint against the target’s current record.
Liveness
Liveness signal that feeds gossip suspicion and repair/handoff gates.
MonotonicReadDecision
Monotonic read guard decision.
MonotonicWriteDecision
Monotonic write guard decision.
MovePhase
Phase of an online partition move.
MultitenancyError
Configuration errors for tenant isolation.
NearCacheRepairAction
Action selected by near-cache watermark repair.
PersistenceConfigErrorKind
Stable persistence config error kind.
PersistenceDurability
Namespace persistence durability mode.
PersistenceDurabilityConfig
Serde-friendly persistence durability config.
PersistenceEviction
Persistence-time eviction intent for a namespace.
PersistenceInMemoryFormat
In-memory representation preference mirrored from Hazelcast-style configs.
PersistenceMatcher
A Hazelcast-style namespace pattern.
PersistenceRegionSelectorConfig
Serde-friendly region selector.
PromotionPhase
Promotion phase for deterministic backup failover.
QuorumPosture
Quorum posture reported by readiness and status surfaces.
RaftMetadataCommand
Metadata command committed by RaftStyleMetadataControlPlane.
ReadConsistency
Read consistency mode.
ReadEscalation
Session read escalation decision.
RebalanceTask
Rebalance work materialized as committed data.
RecoveryErrorKind
Stable recovery error kind.
RecoveryMode
Recovery strictness for persistent namespaces.
RegionSelector
Region selection for persistent namespaces.
RegionState
Operator-visible region health state used by region failover decisions.
RejoiningRegionDecision
Decision for a region that rejoins after a promotion.
RepairAction
Repair action scheduled or recommended by self-healing.
RepairKind
Repair execution mode.
RepairMode
Auto-repair mode.
ReplayResult
Replay result for a subscriber.
ReplicaSelection
Read replica selection mode.
ReplicatedSlot
Replicated value slot with tombstones participating in version ordering.
ReplicatedValueSecurityPosture
Replicated payload confidentiality posture.
Replication
Value-level replication eligibility.
ReplicationConfigError
Errors returned by ReplicationConfig::validate.
RescaleCheckpointPhase
Phase of the stop-checkpoint-redistribute-resume rescale flow.
ResidencyAuditAction
Residency audit action.
ResidencyDecision
Residency decision used by diagnostics and policy dry-runs.
ResidencyFailoverDecision
Failover decision that never chooses an out-of-policy home.
ResidencyRejectionKind
Residency rejection kind.
ResidencyRemediationAction
Remediation action for a value location after policy narrowing.
RoutingMode
Client-side routing behavior for owner peer-fetch traffic.
ScaleAction
Accepted scale action.
ScaleRecommendation
Recommendation emitted for an external autoscaler or operator.
ScrubErrorKind
Scrubber error kind.
SecurityError
Security lifecycle errors.
SessionFailoverAction
Session failover recovery action.
SessionLifecycleDecision
Session lifecycle validation decision.
SessionReadMode
Session read freshness mode.
SessionRequest
Request session mode.
SessionTokenError
Token verification error.
StalenessDecision
Bounded-staleness read decision.
StalenessEscalationReason
Why a bounded-staleness read had to escalate.
StorageOpKind
Storage request kind emitted by a sans-IO node.
TombstoneAdmission
Result of admitting a tombstone under budget.
TombstoneCrdtDecision
Outcome of checking a CRDT update against an existing tombstone.
TransportError
Error reported by an external invalidation transport.
WriteAuthority
Write-authority mode for a geo-distributed partition.

Constants§

AT_REST_ARTIFACT_FORMAT_VERSION
Current at-rest sealed artifact format.
BACKUP_MANIFEST_FORMAT_VERSION
Current full-backup manifest format.
CACHE_INVALIDATION_FRAME_VERSION
Current binary encoding version for cross-process invalidation frames.
CLUSTER_CHECKPOINT_MANIFEST_FORMAT_VERSION
Cluster checkpoint manifest format version registered in docs/COMPAT.md.
CLUSTER_PEER_FETCH_BASE_URL_METADATA_KEY
Metadata key used by members to advertise their peer-fetch base URL.
CONTROL_PLANE_SNAPSHOT_FORMAT_VERSION
Control-plane snapshot format version registered in docs/COMPAT.md.
DURABILITY_SNAPSHOT_FORMAT_VERSION
Snapshot manifest format version registered in docs/COMPAT.md.
NODE_TOPOLOGY_REGION_METADATA_KEY
Metadata key used for a node’s authoritative region.
NODE_TOPOLOGY_ZONE_METADATA_KEY
Metadata key used for a node’s authoritative zone.
OTHER_NAMESPACE_METRIC_LABEL
Aggregate label used when a namespace is not in the bounded metric roster.
REPLICATED_VALUE_RECORD_CHECKSUM_FORMAT_VERSION
Checksummed durable envelope version registered in docs/COMPAT.md.
REPLICATED_VALUE_RECORD_FORMAT_VERSION
Durable value-store format version registered in docs/COMPAT.md.
RESIDENCY_POLICY_FORMAT_VERSION
Residency policy format registered in docs/COMPAT.md.

Traits§

AtRestKeyProvider
Provider responsible for current and previous at-rest keys.
CacheInvalidationBus
Transport abstraction for cross-cache invalidation.
CacheInvalidationFrameSink
A bus that can apply an already encoded invalidation frame locally.
CacheInvalidationReceiver
Receiver side of a cache invalidation bus.
ClusterClock
Deterministic clock seam used by the sans-IO cluster node.
ClusterComponent
Uniform lifecycle surface for background cluster components.
ClusterControlPlane
Transport-neutral control-plane contract for cluster admission and metadata.
ClusterDiscovery
Transport-neutral discovery contract for cluster candidates and liveness.
ClusterOwnershipResolver
Strategy for mapping cache keys to admitted cluster members.
ClusterPeerFetch
Transport-neutral peer-fetch seam for future owner-side value loading.
ClusterReplicationStrategy
Strategy for selecting primary and backup owners for a cache key.
ClusterStorage
Deterministic storage seam for production and simulation drivers.
ConflictFreeValue
Conflict-free value that can converge under active-active replication.
DurableFlush
Adapter hook used by the durability write path to force a durable flush.
HintStore
Bounded hint storage contract.
InvalidationTransport
Async transport for moving invalidation frames outside the process.
MergePolicy
Merge policy for loser-side entries after split-brain detection.
ObjectStore
Minimal object-store contract for backup backends.
RedactReplicatedValue
Optional redaction hook before replicated bytes are sealed/sent.
ReplicatedValueStore
Durable replicated value-store seam.
ReplicationKeyProvider
Operator-supplied sealing boundary for replicated value bytes.
SnapshotSink
Operator-supplied control-plane snapshot sink.
TenantResolver
Resolve a client identity to a bounded tenant id.

Functions§

admit_autoscaler_intent
Validate an autoscaler intent against zone, quorum, and COMPAT invariants.
anti_entropy_diff
Return keys where local is newer or missing from remote.
anti_entropy_repair
Repair a backup from a primary snapshot after anti-entropy detects lag.
apply_causal_write
Apply a causal write or return the dependencies that must be repaired first.
apply_hint
Apply a hint if it is still newer than the target state and does not resurrect a tombstone.
apply_monotonic_read
Apply a monotonic read by updating the watermark only if the candidate is safe.
apply_monotonic_write
Apply a monotonic write, returning the new accepted stamp on success.
causal_apply
Decide whether a causal write can become visible on this replica.
choose_hlc_tiebreak
Deterministically choose between equal (version, epoch) writes using HLC.
cluster_grid_metric_descriptors
Aggregate metric descriptors exported by the grid slice.
converge_replicated_values
Reduce concurrent replicated records to one converged value through the merge policy.
decode_transport_frame
Decode transport bytes using the relay’s fail-closed error taxonomy.
diff_effective_maps
Deterministically diff two maps for one partition.
evaluate_capacity
Compute one capacity recommendation with dwell-time hysteresis.
foreground_read_repair
Select the freshest record and repair divergent replicas inline.
hedge_winner
Choose the freshest read response by (version, epoch).
live_read_your_writes
Apply the read-your-writes quorum rule using the live replication config.
liveness_allows_ownership_change
Return whether a liveness signal is allowed to change ownership.
liveness_allows_repair_or_handoff
Return whether handoff/repair may talk to this peer.
merge_split_brain_records
Merge loser-side records into winner-side records using a deterministic policy.
partition_for_key
Return the deterministic partition for a key.
plan_hedged_read
Build a hedged read plan without changing the required quorum count.
prepare_replicated_payload
Prepare bytes for replication, honoring LocalOnly/redaction/encryption.
promote_region_home
Promote partitions whose primary/home node belonged to from_home.
quorum_read_your_writes
Select a value for a RYOW quorum read.
read_manifest
Read and decode a manifest from object storage.
rebuild_expired_sessionless
Convert an expired-token outcome into the safe downgrade path.
recover_cluster_checkpoint
Recover persistent namespaces through a verified cluster checkpoint cut.
recover_namespaces
Recover persistent namespaces from an existing replicated value store.
recover_session_after_failover
Recover a client-carried session after region promotion.
rejoining_region_authority
Apply the A1-style epoch fence to a rejoining region.
replay_hints
Replay all hints for a target against caller-provided current state.
replicated_slot_version
Compose the version used for replicated values/tombstones.
rescale_with_checkpoint
Create a rescale-with-checkpoint flow from a verified checkpoint and reshard plan.
resolve_live_split_brain
Resolve a healed split-brain from two live side snapshots.
resolve_monotonic_read
Resolve whether a candidate read preserves monotonic reads.
resolve_monotonic_write
Resolve whether an incoming write preserves session write order.
resolve_session_read
Resolve a session read against the current watermark.
resolve_session_read_mode
Resolve a read under either strict causal or bounded-staleness mode.
restore_backup_to_point
Restore a full backup and replay PITR records up to target_sequence.
restore_topology_from_snapshot
Restore a topology authority from a snapshot.
scale_in_removal_allowed
Return whether a scale-in drain completed and the node can be removed.
scale_out_counts_toward_quorum
Return whether every move has reached the committed owner.
select_backup_promotion
Select the first backup as the deterministic promotion candidate.
serve_session_read
Serve a session read and update the watermark, or fail loud if below the watermark.
split_brain_winner
Return (winner, loser) epochs according to the authority rule.
tombstone_crdt_decision
Enforce the A5 rule: a tombstone at an equal/higher (version, epoch) wins.
topology_from_member_metadata
Extract topology metadata from a member snapshot, when present.
transport_metric_descriptors
Return the bounded-label metric descriptors emitted by the relay.
validate_move_preserves_zone_quorum
Reject a move target that would co-locate write quorum in one zone.
validate_replica_config
Validate the narrow 0.40 pilot replica/quorum shape.
validate_session_lifecycle
Validate a token’s MAC/nonce/session and TTL.
within_staleness_bound
Return whether the read can be served locally under the chosen mode.
write_full_backup
Write a full backup to an object store and return its manifest.
write_pitr_log
Write a PITR log object and return its key.

Type Aliases§

CacheResult
HydraCache result type.
SealedBytes
Bytes after the operator-supplied replication boundary has sealed/redacted them. Durable stores persist these bytes, never the original plaintext.
SharedInvalidationRing
Shared invalidation-ring handle reserved for resume support.
SharedReplicationKeyProvider
Shared pointer alias for operator-provided key providers.
ValueVersion
Monotonic version used by replicated value records.

Attribute Macros§

cacheable
Cache an ordinary async function with explicit local-cache metadata.