Expand description
Connection management and request dispatch for Apache Kafka in Rust.
This crate is the first I/O-doing layer of Krabka. It wraps
krabka-protocol’s typed request/response messages in a tokio-based
TCP client that:
- Opens one connection per broker and multiplexes requests by correlation ID.
- Negotiates API versions on connect.
- Manages a
BrokerPoolkeyed on broker id with lazy connect. - Resolves bootstrap addresses in the builder.
§Quick start
use krabka_client_core::Client;
use krabka_protocol::owned::api_versions_request::ApiVersionsRequest;
let client = Client::builder()
.bootstrap("localhost:9092")
.client_id("my-app")
.build()
.await?;
let resp = client.send(ApiVersionsRequest::default()).await?;
println!("broker supports {} APIs", resp.api_keys.len());
client.close();§Scope and boundaries
This crate is the shared transport and request-dispatch layer. It supplies bootstrap resolution, API-version negotiation, broker-id connection pooling, typed request/response dispatch, low-level fetch helpers, and client-side TLS/SASL negotiation. Higher-level semantics live in the producer, consumer, and admin crates built on top of this one. Those semantics are batching, idempotence, consumer-group heartbeats, commits, admin retries, and transactions.
TLS / SASL: a client-side security surface lives in security and
sasl. Set ConnectionOptions::security (or the Client
builder’s .security(...)) to negotiate TLS then SASL before the
API-versions bootstrap. None (the default) is plaintext.
Sockets: transport::dial opens every outbound TCP connection. An
embedder that supplies its own sockets installs a
transport::Connector.
§WebAssembly
The crate builds for wasm32-wasip1 with --cfg tokio_unstable, which
tokio needs for its net feature on WebAssembly. It runs on a
current-thread tokio runtime. On that target:
- WASI preview 1 has no
connectcall, so the embedder installs atransport::Connectorbefore the first connection. - WASI has no name resolution, so broker addresses are IP address
literals, such as
10.0.0.1:9092. client.dns.lookup=resolve_canonical_bootstrap_servers_onlydoes no reverse lookup, so each bootstrap address keeps its IP address text.- A TLS connection needs a configured trust store, because there is no platform trust store.
- SASL/GSSAPI fails with
SaslAuthenticationError::UnsupportedMechanism, with or without thegssapifeature.
§Cargo features
mock— exposesMockBrokerbeyond#[cfg(test)]for downstream testing.gssapi(off by default) — the SASL/GSSAPI (Kerberos) client, throughkrabka-security/gssapi. It stays out ofdefaultbecause the Kerberos stack depends onrsa0.10, which carries RUSTSEC-2023-0071 and has no patched release; a build without the feature compiles norsa. Without it, aSaslCredentials::Gssapicredential failsConnectionOptions::validate, and so client construction, withClientError::InvalidConfig; a connection that skips validation fails the handshake withSaslAuthenticationError::UnsupportedMechanism. The admin, consumer and producer crates forward the feature.
Re-exports§
pub use sasl::OAuthBearerTokenSource;pub use sasl::OutboundSaslError;pub use sasl::SaslAuthenticationError;pub use sasl::SaslCredentials;pub use sasl::SaslSession;pub use sasl::outbound_sasl;pub use security::ClientSecurity;pub use security::KeyStore;pub use security::Password;pub use security::TlsConfigError;pub use security::TlsConnectorConfig;pub use security::TlsVersion;pub use security::TrustStore;pub use security::connection_target_host;
Modules§
- oauth
- OAUTHBEARER tokens: the token provider seam, an OAuth 2 client credentials provider and a jwt-bearer client assertion provider (KIP-768), and a background refresh task for either.
- sasl
- Transport-agnostic outbound SASL handshake for the client.
- security
- Client-side TLS/SASL security surface for
crate::Client. - telemetry
- Client metrics push (KIP-714).
- transport
- Outbound TCP connections and name resolution.
Structs§
- ApiVersion
Table - Broker
Handle - A handle to a specific broker within a
Client’s pool. - Broker
Info - Information about a single Kafka broker, as reported by a
MetadataResponse. - Broker
Pool - Pool of
Arc<Connection>keyed by broker id. - Client
- A Kafka client backed by a
BrokerPool. - Client
DnsTimeout - Positive, whole-millisecond DNS lookup deadline.
- Client
Frame Max - Positive whole-byte accepted-frame limit bounded by the fixed security ceiling.
- Connection
- A connection to a single Kafka broker.
- Connection
Dispatch Queue Capacity - Positive capacity of one connection’s pending request dispatch queue.
- Connection
Options - Connect-time + per-request configuration knobs.
- Coordinator
Endpoint - The broker that coordinates one consumer group or one transactional id.
- Epoch
EndOffset - One leader-epoch end-offset answer for a partition.
- Exponential
Backoff - Kafka’s
ExponentialBackoff:initial * multiplier^attempts, times a random factor in[1 - jitter, 1 + jitter), and never abovemax. - Fetch
MinBytes - Positive whole-byte minimum response size for a single-partition fetch.
- Fetch
Partition Result - Records returned by a fetch together with the next safe partition offset.
- Fetched
Record - One record decoded from a single-partition fetch.
- Finalized
Features - The finalized feature levels of a broker (KIP-584), from
ApiVersionsv3 and later, as Kafka’sApiVersions.FinalizedFeaturesInfoholds them. - Isolated
Fetch - Parameters for a single-partition fetch with an explicit isolation level.
- Metadata
Recovery Rebootstrap Trigger - Non-negative, whole-millisecond KIP-1102 rebootstrap trigger.
- Metadata
Topics - The topics of a client’s metadata requests, with the last time that each topic was used.
- Version
Bounded Request - A protocol request with a narrower version range than its wire type.
Enums§
- Authentication
Error - The reason that a peer rejected authentication. Each variant is a subclass
of Kafka’s
AuthenticationException. - Client
DnsLookup - How the client resolves broker host names (Kafka
client.dns.lookup). - Client
Error - Errors returned by
Client,Connection, and the broker pool. - Coordinator
KeyType - The key space that a
FindCoordinatorlookup asks about. - Metadata
Recovery Strategy - Kafka client behavior when its last-known broker metadata can no longer be refreshed.
- Metadata
Scope - Which topics
crate::Client::refresh_metadataasks for.
Constants§
- DEFAULT_
CLIENT_ DNS_ TIMEOUT - Default deadline for one client DNS lookup.
- DEFAULT_
CLIENT_ FRAME_ MAX - Default maximum accepted client frame size.
- DEFAULT_
CLIENT_ REQUEST_ TIMEOUT - Default deadline for one client request.
- DEFAULT_
CONNECTIONS_ MAX_ IDLE - Kafka’s producer and consumer
connections.max.idle.msdefault (9 minutes, below the broker’s 10 minutes). - DEFAULT_
CONNECTION_ DISPATCH_ QUEUE_ CAPACITY - Default capacity of one connection’s pending request dispatch queue.
- DEFAULT_
FETCH_ MIN - Default minimum response size for a single-partition fetch.
- DEFAULT_
FETCH_ RESPONSE_ MAX - Default whole-response byte limit for single-partition fetch helpers.
- DEFAULT_
METADATA_ RECOVERY_ REBOOTSTRAP_ TRIGGER - KIP-1102’s default interval from the first unsuccessful metadata attempt until the client repeats bootstrap discovery.
- DEFAULT_
RECEIVE_ BUFFER - Kafka’s consumer and admin
receive.buffer.bytesdefault. The producer default is 32 KiB. - DEFAULT_
RECONNECT_ BACKOFF - Kafka’s
reconnect.backoff.msdefault. - DEFAULT_
RECONNECT_ BACKOFF_ MAX - Kafka’s
reconnect.backoff.max.msdefault. - DEFAULT_
SEND_ BUFFER - Kafka’s producer, consumer and admin
send.buffer.bytesdefault. - DEFAULT_
SOCKET_ CONNECTION_ SETUP_ TIMEOUT - Kafka’s
socket.connection.setup.timeout.msdefault: the TCP connect deadline of the first attempt to a broker. - DEFAULT_
SOCKET_ CONNECTION_ SETUP_ TIMEOUT_ MAX - Kafka’s
socket.connection.setup.timeout.max.msdefault: the connect deadline grows exponentially per failed attempt up to this value. - KAFKA_
BACKOFF_ JITTER - The jitter of Kafka’s connection and retry backoffs.
- KAFKA_
BACKOFF_ MULTIPLIER - The multiplier of Kafka’s connection and retry backoffs.
- MAX_
CLIENT_ FRAME_ BYTES - Fixed security ceiling for accepted client frames.
- UNKNOWN_
FINALIZED_ FEATURES_ EPOCH - Kafka’s
ApiVersionsResponse.UNKNOWN_FINALIZED_FEATURES_EPOCH.
Traits§
- Client
Duplex - Trait alias for the duplex stream types
Connection::from_streamaccepts, such asTcpStreamandtokio_rustls::client::TlsStream. - Protocol
Request - Implemented by every generated Request struct in
krabka-protocol.
Functions§
- all_
topics_ request - The
Metadatarequest for every topic of the cluster (MetadataRequest.Builder.allTopics): a null topic list. - build_
find_ coordinator - Build a
FindCoordinatorrequest forkeythat works at any negotiated version. - coordinator_
endpoint - Read the coordinator endpoint for
keyout of aFindCoordinatorresponse. - fetch_
partition - Fetch up to
partition_maxfrom(topic, partition)atfetch_offset. - fetch_
partition_ with_ isolation - Like
fetch_partition, but lets the caller set the KafkaFetch.isolation_level(0=READ_UNCOMMITTED,1=READ_COMMITTED). - fetch_
partition_ with_ isolation_ progress - Fetch a partition with isolation and return both visible records and cursor progress across filtered transactional and control batches.
- find_
coordinator - Ask the broker behind
connwhich broker coordinateskey. - offset_
for_ leader_ epoch - Send a single-partition
OffsetForLeaderEpochrequest. - topics_
request - A
Metadatarequest that namestopics(MetadataRequest.BuilderforTopicNames). An empty list asks for no topic.
Type Aliases§
- AllTopics
Offset Fetch - An admin
OffsetFetchrequest for all topics, which needs v2 through v9. - Fetched
Header - One Kafka record header decoded from a fetched record.
- Members
Only Leave Group - A
LeaveGrouprequest that carries its member list, needing v3 or newer. - Topic
Name Offset Commit - An
OffsetCommitrequest that names its topics, capped at v9. - Topic
Name Offset Fetch - An
OffsetFetchrequest that names its topics, capped at v9.