Skip to main content

Crate inferadb_ledger_sdk

Crate inferadb_ledger_sdk 

Source
Expand description

Production-grade Rust SDK for InferaDB Ledger service.

Provides a high-level, ergonomic API for Rust applications to interact with Ledger’s blockchain database. Wraps the gRPC services with automatic idempotency, resilient connectivity, and streaming support.

§Features

  • Type-safe API: Strong typing for all Ledger operations
  • Automatic idempotency: Server-assigned sequences with UUID-based deduplication
  • Resilient connectivity: Exponential backoff retry and failover
  • Streaming support: WatchBlocks with automatic reconnection
  • Cancellation support: Per-request and client-level cancellation via CancellationToken
  • Minimal-overhead abstractions: Efficient serialization and connection pooling

§Durability

A successful write response implies WAL durability: the Raft log has fsynced the committed entry and every replica has applied it in-memory. State-DB materialization (the B-tree dual-slot persist) is lazy — it lands on the next checkpointer tick, or immediately on graceful shutdown, snapshot, or backup. Crash recovery replays the WAL tail to rebuild any unpersisted state; replay is idempotent. See docs/architecture/durability.md for the full contract.

External event ingestion (see LedgerClient::ingest_events) carries the same WAL-durability guarantee: a successful response means the events committed through Raft and applied to the events.db in-memory, not that they have been fsynced to the events-state DB. Ingested event IDs are stable byte-identical across crash recovery — see the method docstring for the apply-phase caveat.

Handler-phase audit events (emitted as a side-effect of non-ingest RPCs — admin mutations, authorization checks, lifecycle operations) are now checkpoint-covered rather than per-emission-fsynced: the server enqueues them into an in-memory flush queue, a background flusher drains the queue into the events.db page cache, and durability lands on the next StateCheckpointer tick (~500 ms default). This is the same durability class as apply-phase events, except the emission itself is not WAL-backed, so a crash before the next checkpoint loses the flushed-but-uncheckpointed entries. Strict-durability deployments can disable the queue via the UpdateConfig admin RPC (event_writer_batch.enabled = false), restoring strict per-emission fsync semantics. Apply-phase and ingested events are unaffected. See docs/architecture/durability.md for the full contract and the EventFilter::handler_phase_only docstring for the consumer-visible caveat.

§Quick Start

use inferadb_ledger_sdk::{LedgerClient, ClientConfig, Operation, OrganizationSlug, UserSlug, ServerSource};

#[tokio::main]
async fn main() -> inferadb_ledger_sdk::Result<()> {
    let config = ClientConfig::builder()
        .servers(ServerSource::from_static(["http://localhost:50051"]))
        .client_id("my-app-001")
        .build()?;

    let client = LedgerClient::new(config).await?;

    // Read operations
    let value = client.read(caller, organization, None, "user:123", None, None).await?;

    // Write operations with automatic idempotency
    let operations = vec![Operation::set_entity("user:123", b"data".to_vec(), None, None)];
    let result = client.write(caller, organization, None, operations, None).await?;
    println!("Committed at block {} with sequence {}", result.block_height, result.assigned_sequence);

    Ok(())
}

§Architecture

┌─────────────────────────────────────────────────────────────┐
│                    LedgerClient (Public API)                │
│  .read() │ .write() │ .watch_blocks() │ .admin()           │
├─────────────────────────────────────────────────────────────┤
│                   Idempotency Layer                         │
│   UUID generation │ Retry key preservation │ Dedup         │
├─────────────────────────────────────────────────────────────┤
│                   Resilience Layer (retry + cancellation)    │
│   Retry middleware │ Exponential backoff │ Timeout         │
├─────────────────────────────────────────────────────────────┤
│                   Connection Pool                           │
│   Channel management │ Load balancing │ Health checks      │
├─────────────────────────────────────────────────────────────┤
│                   Tonic gRPC Clients                        │
│   ReadServiceClient │ WriteServiceClient │ AdminService    │
└─────────────────────────────────────────────────────────────┘

Re-exports§

pub use region_resolver::RegionLeaderCache;
pub use server::DnsConfig;
pub use server::FileConfig;
pub use server::ResolvedServer;
pub use server::ServerResolver;
pub use server::ServerSelector;
pub use server::ServerSource;
pub use token::PublicKeyInfo;
pub use token::TokenPair;
pub use token::ValidatedToken;
pub use vault_resolver::LeaderEntry as VaultLeaderEntry;
pub use vault_resolver::VaultLeaderCache;

Modules§

mock
Mock gRPC server for SDK integration testing.
region_resolver
Region leader resolution and caching for data residency routing.
server
Server discovery and selection.
token
SDK types for the Token service.
vault_resolver
Per-vault leader cache for fine-grained routing.

Structs§

AppClientAssertionInfo
A client assertion entry (public metadata only — private key is never returned after creation).
AppClientSecretStatus
Result of getting a client secret’s status.
AppCredentialsInfo
Credential configuration for an app.
AppId
Internal sequential identifier for an application within an organization.
AppInfo
SDK representation of a client application.
AppSlug
Snowflake-generated external identifier for an application.
AppVaultConnectionInfo
A vault connection for an app.
BatchReadBuilder
Fluent builder for batch read requests.
BlindingKeyRehashStatus
Status of a blinding key rehash operation.
BlindingKeyRotationStatus
Status of a blinding key rotation initiated by LedgerClient::rotate_blinding_key.
Block
A complete block including its header and all transactions.
BlockAnnouncement
A block announcement from the WatchBlocks stream.
BlockHeader
Block header containing cryptographic commitments.
ChainProof
Chain proof linking a trusted height to a response height.
ChainTip
Current chain tip information for a vault.
CheckRelationshipOutcome
Result of a LedgerClient::check_relationship call.
CircuitBreaker
Per-endpoint circuit breaker.
CircuitBreakerConfig
Configuration for the per-endpoint circuit breaker.
ClientAssertionId
Internal sequential identifier for a client assertion entry.
ClientConfig
Configuration for the Ledger SDK client.
ClientConfigBuilder
Use builder syntax to set the inputs and finish with build().
ConnectionPool
Manages tonic gRPC channels with lazy connection establishment.
CreateAppClientAssertionResult
Result of creating a client assertion — includes the private key PEM (returned only once).
DiscoveryConfig
Configuration for peer discovery.
DiscoveryResult
Result of a peer discovery refresh operation.
DiscoveryService
Service for discovering cluster peers and managing dynamic endpoints.
EmailVerificationCode
Verification code returned by LedgerClient::initiate_email_verification.
Entity
An entity stored in the ledger.
EventFilter
Filter criteria for event queries.
EventPage
Paginated result from event queries.
HealthCheckResult
Result of a health check operation.
HeightTracker
Height-based position tracker.
HistoricalRead
Result of a historical read at a specific block height.
IngestRejection
A single rejected event from an ingestion batch.
IngestResult
Result of an event ingestion request.
InvitationCreated
Response from creating an organization invitation.
InvitationInfo
Admin-facing invitation information.
InvitationPage
Paginated list of admin-facing invitations.
InviteSlug
External Snowflake identifier for an organization invitation.
LeaderHint
A hint about the current Raft leader for a region, extracted from server ErrorDetails on a NotLeader response.
LedgerClient
High-level client for interacting with the Ledger service.
ListEntitiesOpts
Options for listing entities.
ListRelationshipsOpts
Options for listing relationships.
ListResourcesOpts
Options for listing resources.
MerkleProof
Merkle proof for verifying state inclusion.
MerkleSibling
A sibling node in a Merkle proof path.
MetricsSdkMetrics
Metrics implementation using the metrics crate facade.
MigrationInfo
Information about an in-progress organization migration.
NoopSdkMetrics
No-op metrics implementation with zero overhead.
OrganizationDeleteInfo
Information returned when an organization is soft-deleted.
OrganizationId
Internal sequential identifier for an organization (storage-layer only).
OrganizationInfo
Information about an organization.
OrganizationMemberInfo
Information about an organization member.
OrganizationSlug
Snowflake-generated external identifier for an organization.
PagedResult
Paginated result from query operations.
PasskeyCredentialInfo
WebAuthn passkey credential data.
PeerInfo
Information about a discovered peer in the cluster.
ReceivedInvitationInfo
User-facing invitation information.
ReceivedInvitationPage
Paginated list of user-facing received invitations.
ReconnectingStream
A stream wrapper that automatically reconnects on disconnect.
RecoveryCodeCredentialInfo
Recovery code credential data.
RecoveryCodeResult
Result of consuming a recovery code.
Region
Geographic / jurisdictional region for data residency.
RegistrationResult
Result of LedgerClient::complete_registration.
Relationship
A relationship in a vault (authorization tuple).
RelationshipQueryBuilder
Fluent builder for relationship list queries.
RetryPolicy
Retry policy with exponential backoff and jitter.
SchemaDeployResult
Result of deploying a schema.
SchemaDiffChange
A single field-level change in a schema diff.
SchemaVersion
A full schema version with its definition.
SchemaVersionSummary
Summary of a single schema version in a listing.
SdkEventEntry
An audit event entry from the events system.
SdkIngestEventEntry
A single event for external ingestion (from Engine or Control).
ServerErrorDetails
Structured error details decoded from gRPC Status.details bytes.
TeamId
Internal sequential identifier for a team within an organization.
TeamInfo
Information about an organization team.
TeamMemberInfo
A member of a team.
TeamSlug
Snowflake-generated external identifier for a team.
TlsConfig
TLS configuration for secure connections.
TlsConfigBuilder
Use builder syntax to set the inputs and finish with build().
TotpCredentialInfo
TOTP credential data (RFC 6238).
TraceConfig
Configuration for distributed tracing in the SDK.
Transaction
A single transaction stored in a block.
UserCredentialId
Internal sequential identifier for a user credential.
UserCredentialInfo
A user authentication credential as returned by the Ledger API.
UserEmailId
Unique identifier for a user email record. Never exposed in APIs.
UserEmailInfo
SDK representation of a user email record.
UserInfo
SDK representation of a user record.
UserMigrationInfo
Information about a user region migration.
UserSlug
Snowflake-generated external identifier for a user.
VaultId
Internal sequential identifier for a vault within an organization (storage-layer only).
VaultInfo
Information about a vault.
VaultSlug
Snowflake-generated external identifier for a vault.
VerifiedValue
Result of a verified read operation.
VerifyOpts
Options for verified read operations.
WriteBuilder
Fluent builder for constructing write requests.
WriteSuccess
Result of a successful write operation.

Enums§

AppCredentialType
Credential type for enable/disable operations.
CertificateData
Certificate data that can be either PEM or DER encoded.
CircuitState
Circuit breaker states.
ConnectionEvent
Events for connection lifecycle tracking.
CredentialData
Type-specific credential data.
CredentialType
The type of authentication credential.
Direction
Direction of a sibling in a Merkle proof.
EmailVerificationResult
Result of LedgerClient::verify_email_code.
EventEmissionPath
Emission path of an event (how it was generated).
EventOutcome
Outcome of an audited operation.
EventScope
Scope of an event (system-wide or organization-scoped).
EventSource
Identifies which InferaDB component is the source of ingested events.
HealthStatus
Health status of a node or vault.
InvitationStatus
Status of an organization invitation.
Operation
A write operation to be submitted to the ledger.
OrganizationMemberRole
Role of a member within an organization.
OrganizationStatus
Status of an organization.
OrganizationTier
Billing tier for an organization.
ReadConsistency
Consistency level for read operations.
SdkError
SDK error types with context-rich error messages.
SetCondition
Condition for compare-and-set (CAS) writes.
TeamMemberRole
Role within a team.
TotpAlgorithm
TOTP hash algorithm (RFC 6238).
UserRole
User authorization role.
UserStatus
User account lifecycle status.
VaultStatus
Status of a vault.

Traits§

SdkMetrics
Trait for SDK-side metrics collection.

Functions§

with_retry
Executes an async operation with retry using exponential backoff.
with_retry_cancellable
Executes an async operation with retry and cancellation support.

Type Aliases§

Result
Result type alias for SDK operations.