OpenKache Rust client
OpenKache is a high-performance cache server designed from the ground up for modern SSDs. Use this async Rust client to store, read, and delete values in a few lines.
crates.io package · docs.rs API reference · GitHub source
Install
Rust 1.85 or newer and a native C linker are required.
# OpenKache client
The default quic-quinn client uses Tokio internally, so an active Tokio
runtime is required for Client. The example below uses #[tokio::main]; use
the runtime setup already used by your application.
Quick start
The example below assumes a local OpenKache server at 127.0.0.1:4433.
use Client;
async
The local development TLS profile does not verify the server certificate. Use this example only with a local development server.
Value is the Rust type used for structured values. Writes accept common Rust
values directly and convert them to Value; construct an explicit variant
when float width, raw bits, or model map keys matter.
The Rust client uses OpenKache's structured value format.
Serde Rust values
Client::set_serde and Client::get_serde use Serde while retaining the
same lossless structured-value format as set and get. Add Serde to the
application when defining types for these helpers:
use Client;
use ;
async
get_serde returns Result<Option<T>>; in this example, T is User, so a
hit is Some(User). The final unwrap handles the expected hit in this
small example; production code should decide how a missing key is handled.
None remains distinct from a stored Value::Null for get; a stored null
decodes as Some(None) for get_serde::<Option<T>>. Integers are
range-checked, floating-point values retain their IEEE-754 bits, and map keys
must be scalar and unique. Serde serialization happens before write admission,
so Error::SerdeSerialize cannot produce an unknown mutation. A value that
does not match the requested type returns Error::SerdeDeserialize.
set_serde stores the structured model as StructuredValue-CBOR-v1, not as
an opaque Rust-specific payload. Python and JavaScript clients can therefore
read a value written by set_serde as a structured object, array, scalar, or
null. Keep the schema within the cross-language value model; opaque bytes,
unsupported map keys, and serializer-specific representations remain
application-owned.
Structured codecs with get_with and set_with
For a non-Serde structured serializer, implement ValueCodec<T> or construct
one with FunctionCodec::new(encode, decode). This complete example maps a
Point struct to a structured Value map:
FunctionCodec is a small adapter around two application functions:
encode(&T) -> Result<Value, EncodeError> runs before a write is admitted, and
decode(Value) -> Result<T, DecodeError> runs after a value is retrieved. The
client does not inspect or invoke the application's serializer; it only stores
the resulting structured Value. An encode failure is returned as
Error::CodecEncode, and a decode failure as Error::CodecDecode.
use ;
async
Custom binary payloads
Use byte payloads when the application owns the serialized format. This example uses bincode 2; pin the serializer major version and configuration because the bytes are an application schema contract:
The client stores and returns the bytes without inspecting them; other language clients receive a byte value and need the same application format to decode it:
use config;
use ;
use ;
async
Application-owned payloads normally use ordinary get/set. A
ValueCodec can wrap an opaque serializer only when it maps the encoded bytes
to and from Value::Bytes; the client still does not inspect that format.
Reference
Client::connect(endpoint)
Opens a connection and returns a Client.
- Input: a
host:portendpoint. IPv6 endpoints use[host]:port. - Returns: an async
Result<Client>. - Errors:
Error::Corewhen the endpoint, TLS handshake, or protocol setup fails.
let client = connect.await?;
client.get(key)
Reads one Value.
- Input: anything that converts into
TypedKey: text, bytes, or a signed 64-bit integer. - Returns:
Ok(Some(value))when the key exists, orOk(None)when it does not. A storedValue::NullorValue::Undefinedis stillSome. - Errors:
Error::Corefor connection, protocol, key, or value failures.
match client.get.await?
client.set(key, value)
Stores one value with an unconditional write.
- Input: a
TypedKey-convertible key and any value that implementsInto<Value>. Common strings, byte slices, booleans, integers, and floats are accepted directly. - Returns:
Ok(SetOutcome::Created)for a new key orOk(SetOutcome::Replaced)for an existing key. - Errors:
Error::UnknownMutationwhen admission happened but the result was not confirmed; do not replay that mutation. Other failures are returned asError::Core.
let outcome = client.set.await?;
client.get_serde<T>(key)
Reads one value and decodes it into T: serde::de::DeserializeOwned.
- Returns:
Ok(Some(value))for a matching stored value, orOk(None)when the key does not exist. - Errors:
Error::SerdeDeserializefor a type mismatch, overflow, or unsupported stored value; transport and protocol failures useError::Core.
client.set_serde(key, value)
Serializes value: impl serde::Serialize and stores it with an unconditional
write. Serde serialization completes before network admission.
- Returns: the same
SetOutcomeasclient.set. - Errors:
Error::SerdeSerializefor values that cannot be represented by the structured model, or the transport and mutation errors fromclient.set.
client.get_with and client.set_with
Use an application-provided ValueCodec<T> for a non-Serde structured format.
FunctionCodec::new(encode, decode) is the convenient form when two functions
are enough; implement ValueCodec<T> directly when the codec needs state or
more control. The codec operates on Value, so it does not alter wire
admission or mutation semantics. Encoding happens before admission, so a
codec error cannot produce Error::UnknownMutation; decoding happens after
retrieval and leaves None unchanged. The value type is normally inferred from
the codec, so no turbofish is needed. If inference is ambiguous, annotate the
result as Option<Point>.
client.delete(key)
Deletes one key. Repeating the operation is safe.
- Input: a
TypedKey-convertible key. - Returns:
Ok(true)when a value was removed, orOk(false)when no value existed. - Errors:
Error::UnknownMutationwhen the result of an admitted delete was not confirmed.
let removed = client.delete.await?;
if removed
client.close()
Closes the connection after admitted operations settle. Repeated calls are safe.
- Returns:
Result<()>.
client.close.await?;
Keys
Use TypedKey constructors when you want to make the key type explicit:
TypedKey::text(value)creates a UTF-8 text key.TypedKey::bytes(value)creates an exact byte key.TypedKey::integer(value)creates a signed 64-bit integer key.TypedKey::canonical_bytes()returns the encoded key.
The client also accepts common Rust conversions directly:
client.get.await?;
client.get.await?;
client.get.await?;
KeyError describes invalid or out-of-range keys.
Values
Value is the structured value type returned by get and accepted by set:
Undefined | Null | Boolean | Integer | Float | TextString | Bytes | Array | Map
Construct values with:
Value::integer(value)for an exact integer.Value::float16(bits),Value::float32(bits), orValue::float64(bits)for exact IEEE-754 bits.Value::text(value)for UTF-8 text.Value::bytes(value)for exact bytes.Value::array(values)for an ordered array.Value::map(entries)for an ordered map with scalar, unique keys.Value::to_cbor()andValue::from_cbor(bytes)to encode or decode one complete structured value.
For common writes, the client also accepts &str, String, &[u8],
Vec<u8>, booleans, all signed and unsigned integer types, f32, and f64:
client.set.await?;
client.set.await?;
client.set.await?;
let value = map?;
client.set.await?;
Inspect a structured value with ValueKind and borrowed accessors:
use ;
async
map_get and the typed accessors do not coerce values: a missing key or a
mismatched type returns None, so reading the text name with as_bool
above is safe.
For exact integer and float construction, use Integer, Sign,
Float, and FloatWidth. ValueLimits bounds bytes, depth, item count, and
integer magnitude. ValueError reports value validation and encoding errors;
use ValueError::kind() for its stable category.
Result<T> is the result alias returned by client methods.
Results and errors
- Get methods return
Result<Option<T>>; standardOptionmethods such asunwrap,expect,unwrap_or, andunwrap_or_elsehandle missing keys. SetOutcomeisCreatedorReplaced.SetOutcome::is_createdandSetOutcome::is_replacedinspect the write outcome without matching on its variants.deletereturnstruewhen an item existed andfalseotherwise.Error::UnknownMutationmeans asetordeletemay have reached the server without a confirmed result. ItsMutationidentifies the operation; do not replay it automatically. UseError::is_unknown_mutation,Error::mutation, andError::kindto inspect errors without matching on their payloads.Error::Corereports connection, protocol, key, value, or server failures.Error::SerdeSerializeandError::SerdeDeserializereport Serde conversion failures before and after transport, respectively.Error::CodecEncodeandError::CodecDecodereport applicationValueCodecfailures before and after transport, respectively.Error::UnsupportedSetOutcomereports a server result outside the unconditional-write API.