Skip to main content

av_bridge/
kafka_bus.rs

1//! Kafka-wire connector (feature `kafka`), targeting Redpanda as the reference
2//! self-hosted broker (brief Module F). The event path uses rskafka; a statically
3//! linked librdkafka admin client provisions and verifies topic retention.
4//!
5//! TLS/SASL comes from the environment so secured endpoints need no new
6//! constructor surface: `AV_KAFKA_CA_FILE` pins a root CA (PEM) and enables
7//! TLS on both the admin and event paths; `AV_KAFKA_SASL_USERNAME` /
8//! `AV_KAFKA_SASL_PASSWORD` enable SASL with the mechanism from
9//! `AV_KAFKA_SASL_MECHANISM` (`SCRAM-SHA-256` by default — Redpanda's
10//! native credential store — or `SCRAM-SHA-512` / `PLAIN`). Credentials
11//! are only accepted together with TLS: PLAIN would ship the password in
12//! the clear, and even SCRAM without TLS is exposed to MITM relay. Use
13//! hostname (not bare-IP) broker endpoints with TLS: certificate
14//! verification runs against the dialed name, and IP-SAN support varies
15//! across rustls versions.
16
17use crate::bus::{partition_for, BusError, EventBus, PublishAck, StoredEvent};
18use crate::manifest::BridgeManifest;
19use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, ResourceSpecifier, TopicReplication};
20use rdkafka::client::DefaultClientContext;
21use rdkafka::config::ClientConfig;
22use rdkafka::types::RDKafkaErrorCode;
23use rskafka::client::partition::{Compression, OffsetAt, UnknownTopicHandling};
24use rskafka::client::{ClientBuilder, SaslConfig};
25use rskafka::record::Record;
26use std::collections::HashMap;
27use std::sync::Arc;
28
29/// Broker security material resolved from the environment (module docs).
30struct KafkaSecurity {
31    ca_file: Option<std::path::PathBuf>,
32    credentials: Option<(String, String)>,
33    mechanism: SaslMechanism,
34}
35
36#[derive(Clone, Copy, PartialEq, Eq)]
37enum SaslMechanism {
38    Plain,
39    ScramSha256,
40    ScramSha512,
41}
42
43impl SaslMechanism {
44    fn parse(value: &str) -> Result<Self, BusError> {
45        match value {
46            "PLAIN" => Ok(Self::Plain),
47            "SCRAM-SHA-256" => Ok(Self::ScramSha256),
48            "SCRAM-SHA-512" => Ok(Self::ScramSha512),
49            other => Err(BusError::Backend(format!(
50                "AV_KAFKA_SASL_MECHANISM {other:?} is not supported \
51                 (use PLAIN, SCRAM-SHA-256, or SCRAM-SHA-512)"
52            ))),
53        }
54    }
55
56    /// librdkafka's `sasl.mechanism` spelling.
57    fn librdkafka_name(self) -> &'static str {
58        match self {
59            Self::Plain => "PLAIN",
60            Self::ScramSha256 => "SCRAM-SHA-256",
61            Self::ScramSha512 => "SCRAM-SHA-512",
62        }
63    }
64}
65
66impl KafkaSecurity {
67    fn from_env() -> Result<Self, BusError> {
68        Self::from_lookup(|name| std::env::var(name).ok())
69    }
70
71    /// Testable core of [`Self::from_env`] (same pattern as the harness
72    /// config's `apply_env_overrides_from`): `get` returns the value of a
73    /// named environment variable, or `None` when unset.
74    fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self, BusError> {
75        let ca_file = get("AV_KAFKA_CA_FILE").map(std::path::PathBuf::from);
76        let credentials = match (get("AV_KAFKA_SASL_USERNAME"), get("AV_KAFKA_SASL_PASSWORD")) {
77            (Some(username), Some(password)) => Some((username, password)),
78            (None, None) => None,
79            _ => {
80                return Err(BusError::Backend(
81                    "AV_KAFKA_SASL_USERNAME and AV_KAFKA_SASL_PASSWORD must be set together".to_owned(),
82                ))
83            }
84        };
85        let mechanism = match get("AV_KAFKA_SASL_MECHANISM") {
86            Some(value) => SaslMechanism::parse(&value)?,
87            None => SaslMechanism::ScramSha256,
88        };
89        if credentials.is_some() && ca_file.is_none() {
90            return Err(BusError::Backend(
91                "Kafka SASL credentials require AV_KAFKA_CA_FILE: PLAIN ships the password in \
92                 the clear and even SCRAM without TLS is exposed to MITM relay"
93                    .to_owned(),
94            ));
95        }
96        Ok(Self {
97            ca_file,
98            credentials,
99            mechanism,
100        })
101    }
102
103    /// librdkafka admin-client settings mirroring the rskafka event path.
104    fn apply_admin(&self, config: &mut ClientConfig) {
105        let protocol = match (&self.ca_file, &self.credentials) {
106            (Some(_), Some(_)) => "sasl_ssl",
107            (Some(_), None) => "ssl",
108            (None, _) => return,
109        };
110        config.set("security.protocol", protocol);
111        if let Some(ca) = &self.ca_file {
112            config.set("ssl.ca.location", ca.to_string_lossy().as_ref());
113        }
114        if let Some((username, password)) = &self.credentials {
115            config.set("sasl.mechanism", self.mechanism.librdkafka_name());
116            config.set("sasl.username", username);
117            config.set("sasl.password", password);
118        }
119    }
120
121    /// Root-pinned rustls config for the rskafka event path.
122    fn rskafka_tls(&self) -> Result<Option<Arc<rustls_tls::ClientConfig>>, BusError> {
123        let Some(ca) = &self.ca_file else {
124            return Ok(None);
125        };
126        // Same provider discipline as NatsBus::provision: rustls 0.23
127        // resolves its process CryptoProvider lazily and panics when both
128        // `ring` and `aws-lc-rs` are compiled in with none installed.
129        let _ = rustls_tls::crypto::ring::default_provider().install_default();
130        let pem = std::fs::read(ca)
131            .map_err(|error| BusError::Backend(format!("Kafka CA file {}: {error}", ca.display())))?;
132        use rustls_pki_types::pem::PemObject as _;
133        let mut roots = rustls_tls::RootCertStore::empty();
134        let mut certs = 0usize;
135        for cert in rustls_pki_types::CertificateDer::pem_slice_iter(&pem) {
136            let cert = cert
137                .map_err(|error| BusError::Backend(format!("Kafka CA file {}: {error:?}", ca.display())))?;
138            roots
139                .add(cert)
140                .map_err(|error| BusError::Backend(format!("Kafka CA file {}: {error}", ca.display())))?;
141            certs = certs.saturating_add(1);
142        }
143        if certs == 0 {
144            return Err(BusError::Backend(format!(
145                "Kafka CA file {} contains no PEM certificates",
146                ca.display()
147            )));
148        }
149        let config = rustls_tls::ClientConfig::builder()
150            .with_root_certificates(roots)
151            .with_no_client_auth();
152        Ok(Some(Arc::new(config)))
153    }
154
155    fn rskafka_sasl(&self) -> Option<SaslConfig> {
156        self.credentials.as_ref().map(|(username, password)| {
157            let credentials = rskafka::client::Credentials::new(username.clone(), password.clone());
158            match self.mechanism {
159                SaslMechanism::Plain => SaslConfig::Plain(credentials),
160                SaslMechanism::ScramSha256 => SaslConfig::ScramSha256(credentials),
161                SaslMechanism::ScramSha512 => SaslConfig::ScramSha512(credentials),
162            }
163        })
164    }
165}
166
167/// Kafka/Redpanda bus.
168pub struct KafkaBus {
169    cold_archive: Option<crate::cold_store::ColdArchive>,
170    executor: crate::bus::ConnectorExecutor,
171    /// Per-(topic, partition) clients built once at provision. rskafka's
172    /// `Client::partition_client` performs metadata discovery and broker
173    /// connection setup; constructing one per publish flooded the broker
174    /// under 10k-connection load until audit publishes stalled admission
175    /// past the upstream timeout (observed as 502s in the 10k SLA gate).
176    /// The `Client` itself is not retained: partition clients hold their
177    /// own broker references, and every post-provision operation goes
178    /// through this cache.
179    partition_clients: HashMap<(String, u32), Arc<rskafka::client::partition::PartitionClient>>,
180    topics: HashMap<String, u32>,
181    validators: HashMap<String, jsonschema::Validator>,
182    /// Process-local idempotency memory for caller-supplied event UIDs —
183    /// the Kafka analogue of the embedded broker's `seen_event_uids`.
184    /// `publish_idempotent`'s contract is "same UID → original ack", but
185    /// rskafka `produce` has no native dedupe and the cold-outbox
186    /// staging check only fires when a prior attempt CRASHED mid-publish
187    /// (intent still staged); after a clean success a retried same-UID
188    /// call appended a duplicate record — the embedded and Kafka
189    /// backends disagreed on the trait's core promise. Bounded FIFO so
190    /// an unbounded UID stream can't grow memory (dedup across restarts
191    /// is still covered by the staged-intent + `find_event_by_uid`
192    /// recovery path).
193    recent_uids: parking_lot::Mutex<RecentUids>,
194}
195
196/// Bounded FIFO of `topic\0uid → (partition, offset)` (see
197/// `KafkaBus::recent_uids`).
198struct RecentUids {
199    map: HashMap<String, (u32, u64)>,
200    order: std::collections::VecDeque<String>,
201}
202
203/// 64Ki UIDs ≈ a few MB worst case: covers hours of same-process retry
204/// windows while staying trivially bounded.
205const RECENT_UIDS_CAP: usize = 65_536;
206
207impl RecentUids {
208    fn new() -> Self {
209        Self {
210            map: HashMap::new(),
211            order: std::collections::VecDeque::new(),
212        }
213    }
214
215    fn get(&self, topic: &str, uid: &str) -> Option<(u32, u64)> {
216        self.map.get(&format!("{topic}\0{uid}")).copied()
217    }
218
219    fn insert(&mut self, topic: &str, uid: &str, partition: u32, offset: u64) {
220        let key = format!("{topic}\0{uid}");
221        if self.map.insert(key.clone(), (partition, offset)).is_none() {
222            self.order.push_back(key);
223            while self.order.len() > RECENT_UIDS_CAP {
224                if let Some(evicted) = self.order.pop_front() {
225                    self.map.remove(&evicted);
226                }
227            }
228        }
229    }
230}
231
232impl KafkaBus {
233    /// Connect to `broker` (host:port) and provision topics per the manifest.
234    pub fn provision(broker: &str, manifest: &BridgeManifest) -> Result<Self, BusError> {
235        manifest
236            .validate()
237            .map_err(|e| BusError::Backend(e.to_string()))?;
238        let validators = crate::manifest::compile_topic_validators(manifest)?;
239        let cold_archive = crate::cold_store::ColdArchive::from_manifest(manifest)?;
240        let executor = crate::bus::ConnectorExecutor::new("agentvisor-ai-kafka")?;
241        let security = KafkaSecurity::from_env()?;
242        let mut admin_config = ClientConfig::new();
243        admin_config
244            .set("bootstrap.servers", broker)
245            .set("socket.timeout.ms", "10000");
246        security.apply_admin(&mut admin_config);
247        let admin: AdminClient<DefaultClientContext> = admin_config
248            .create()
249            .map_err(|error| BusError::Backend(error.to_string()))?;
250        let admin = Arc::new(admin);
251        for topic in &manifest.topics {
252            let admin = Arc::clone(&admin);
253            let name = topic.name.clone();
254            let partitions = topic.partitions;
255            let replication_factor = manifest.replication_factor;
256            let retention_ms = u64::from(topic.retention.hot_hours)
257                .checked_mul(av_core::units::MS_PER_HOUR)
258                .ok_or_else(|| BusError::Backend("Kafka retention overflow".to_owned()))?
259                .to_string();
260            executor
261                .run(move || provision_topic(admin, name, partitions, replication_factor, retention_ms))?
262                .map_err(BusError::Backend)?;
263        }
264        drop(admin);
265        // `broker` is a bootstrap list (`host:port[,host:port]`, the same
266        // format rdkafka's `bootstrap.servers` takes above). rskafka wants
267        // one address per element — passing the joined string as a single
268        // entry made every multi-broker list fail to connect.
269        let brokers: Vec<String> = broker
270            .split(',')
271            .map(str::trim)
272            .filter(|entry| !entry.is_empty())
273            .map(str::to_owned)
274            .collect();
275        if brokers.is_empty() {
276            return Err(BusError::Backend("Kafka bootstrap list is empty".to_owned()));
277        }
278        let tls_config = security.rskafka_tls()?;
279        let sasl_config = security.rskafka_sasl();
280        let client = executor
281            .run(move || async move {
282                let mut builder = ClientBuilder::new(brokers);
283                if let Some(tls) = tls_config {
284                    builder = builder.tls_config(tls);
285                }
286                if let Some(sasl) = sasl_config {
287                    builder = builder.sasl_config(sasl);
288                }
289                builder.build().await
290            })?
291            .map_err(|e| BusError::Backend(e.to_string()))?;
292        let client = Arc::new(client);
293        let mut topics = HashMap::new();
294        for t in &manifest.topics {
295            topics.insert(t.name.clone(), t.partitions);
296        }
297        let metadata_client = Arc::clone(&client);
298        let metadata = executor
299            .run(move || async move { metadata_client.list_topics().await })?
300            .map_err(|error| BusError::Backend(error.to_string()))?;
301        for expected in &manifest.topics {
302            let actual = metadata
303                .iter()
304                .find(|topic| topic.name == expected.name)
305                .ok_or_else(|| BusError::Backend(format!("Kafka topic {:?} is missing", expected.name)))?;
306            if actual.partitions.len() != expected.partitions as usize {
307                return Err(BusError::Backend(format!(
308                    "Kafka topic {:?} has {} partitions, manifest requires {}",
309                    expected.name,
310                    actual.partitions.len(),
311                    expected.partitions
312                )));
313            }
314        }
315        let mut partition_clients = HashMap::new();
316        for t in &manifest.topics {
317            for p in 0..t.partitions {
318                let pc_client = Arc::clone(&client);
319                let name = t.name.clone();
320                let pc = executor
321                    .run(move || async move {
322                        pc_client
323                            .partition_client(name, p as i32, UnknownTopicHandling::Error)
324                            .await
325                    })?
326                    .map_err(|error| BusError::Backend(error.to_string()))?;
327                partition_clients.insert((t.name.clone(), p), Arc::new(pc));
328            }
329        }
330        Ok(Self {
331            cold_archive,
332            executor,
333            partition_clients,
334            topics,
335            validators,
336            recent_uids: parking_lot::Mutex::new(RecentUids::new()),
337        })
338    }
339
340    /// Cached per-partition client (built at provision; see struct docs).
341    fn partition_client(
342        &self,
343        topic: &str,
344        partition: u32,
345    ) -> Result<Arc<rskafka::client::partition::PartitionClient>, BusError> {
346        self.partition_clients
347            .get(&(topic.to_owned(), partition))
348            .cloned()
349            .ok_or_else(|| BusError::UnknownTopic(topic.to_owned()))
350    }
351
352    fn publish_with_uid(
353        &self,
354        topic: &str,
355        key: &str,
356        value: &serde_json::Value,
357        event_uid: Option<&str>,
358    ) -> Result<PublishAck, BusError> {
359        crate::manifest::validate_topic_event(&self.validators, topic, value)?;
360        let partitions = *self
361            .topics
362            .get(topic)
363            .ok_or_else(|| BusError::UnknownTopic(topic.to_owned()))?;
364        let partition = partition_for(key, partitions);
365        // Idempotency fast path for caller-supplied UIDs: after a clean
366        // success the cold intent is gone, so without this a same-UID
367        // retry re-produced a duplicate record (see `recent_uids` docs).
368        let caller_uid = event_uid.is_some();
369        if let Some(uid) = event_uid {
370            if let Some((cached_partition, offset)) = self.recent_uids.lock().get(topic, uid) {
371                return Ok(PublishAck {
372                    topic: topic.to_owned(),
373                    partition: cached_partition,
374                    offset,
375                });
376            }
377        }
378        let event_uid = event_uid.map_or_else(av_core::new_event_uid, str::to_owned);
379        let stored_at = av_core::time::now_ms();
380        let record = StoredEvent {
381            partition,
382            offset: 0,
383            key: key.to_owned(),
384            value: value.clone(),
385            stored_at,
386        };
387        if let Some(archive) = &self.cold_archive {
388            let already_staged = archive.stage(topic, &record, &event_uid)?;
389            if already_staged {
390                // A prior attempt for this UID staged the intent and may
391                // have produced to the broker before its commit step
392                // failed (ENOSPC persisting the resolved offset, MAC
393                // refusal, crash). rskafka `produce` has no native dedup,
394                // so blindly re-producing would append a second record
395                // for the same logical event — a duplicate in the audit
396                // stream. Consult the partition first, exactly like the
397                // maintenance retry path does.
398                if let Some(existing) = self.find_event_by_uid(topic, key, &event_uid)? {
399                    // The event is durably on the broker; resolving the
400                    // cold intent is best-effort here. On failure the
401                    // durable intent stays queued for the maintenance
402                    // pass — do not fail a publish that succeeded.
403                    if let Err(error) = archive.commit(topic, &event_uid, existing.offset) {
404                        tracing::warn!(
405                            %error,
406                            topic,
407                            event_uid = %event_uid,
408                            "cold intent commit failed after idempotent dedup hit; left for maintenance retry"
409                        );
410                    }
411                    return Ok(existing);
412                }
413            }
414        }
415        let ack = self.publish_broker_only(topic, key, value, stored_at, &event_uid)?;
416        if let Some(archive) = &self.cold_archive {
417            archive.commit(topic, &event_uid, ack.offset)?;
418        }
419        if caller_uid {
420            self.recent_uids
421                .lock()
422                .insert(topic, &event_uid, ack.partition, ack.offset);
423        }
424        Ok(ack)
425    }
426
427    fn publish_broker_only(
428        &self,
429        topic: &str,
430        key: &str,
431        value: &serde_json::Value,
432        stored_at: u64,
433        event_uid: &str,
434    ) -> Result<PublishAck, BusError> {
435        crate::manifest::validate_topic_event(&self.validators, topic, value)?;
436        let partitions = *self
437            .topics
438            .get(topic)
439            .ok_or_else(|| BusError::UnknownTopic(topic.to_owned()))?;
440        let partition = partition_for(key, partitions);
441        let record = StoredEvent {
442            partition,
443            offset: 0,
444            key: key.to_owned(),
445            value: value.clone(),
446            stored_at,
447        };
448        let payload = serde_json::to_vec(&record)?;
449        let pc = self.partition_client(topic, partition)?;
450        let key_bytes = event_uid.as_bytes().to_vec();
451        let mut headers = std::collections::BTreeMap::new();
452        headers.insert("agentvisor-event-uid".to_owned(), event_uid.as_bytes().to_vec());
453        let offset = self
454            .executor
455            .run(move || async move {
456                let offsets = pc
457                    .produce(
458                        vec![Record {
459                            key: Some(key_bytes),
460                            value: Some(payload),
461                            headers,
462                            timestamp: chrono_now(),
463                        }],
464                        Compression::NoCompression,
465                    )
466                    .await?;
467                // One record in => exactly one offset out. An empty response
468                // is a broker anomaly; fabricating offset 0 here would persist
469                // a legitimate-looking ack that dedupe/recovery then trusts.
470                Ok::<_, rskafka::client::error::Error>(offsets.first().copied())
471            })?
472            .map_err(|e| BusError::Backend(e.to_string()))?;
473        let offset = offset.ok_or_else(|| {
474            BusError::Backend("Kafka produce succeeded but returned no offset for the record".to_owned())
475        })?;
476        let offset = u64::try_from(offset)
477            .map_err(|_| BusError::Backend(format!("Kafka returned negative offset {offset}")))?;
478        Ok(PublishAck {
479            topic: topic.to_owned(),
480            partition,
481            offset,
482        })
483    }
484}
485
486async fn provision_topic(
487    admin: Arc<AdminClient<DefaultClientContext>>,
488    name: String,
489    partitions: u32,
490    replication_factor: u32,
491    retention_ms: String,
492) -> Result<(), String> {
493    let partitions = i32::try_from(partitions)
494        .map_err(|_| format!("partition count for Kafka topic {name:?} exceeds i32"))?;
495    let replication_factor = i32::try_from(replication_factor)
496        .map_err(|_| format!("replication factor for Kafka topic {name:?} exceeds i32"))?;
497    let topic = NewTopic::new(&name, partitions, TopicReplication::Fixed(replication_factor))
498        .set("retention.ms", &retention_ms);
499    let results = admin
500        .create_topics(
501            [&topic],
502            &AdminOptions::new().operation_timeout(Some(std::time::Duration::from_secs(5))),
503        )
504        .await
505        .map_err(|error| error.to_string())?;
506    match results.into_iter().next() {
507        Some(Ok(_)) | Some(Err((_, RDKafkaErrorCode::TopicAlreadyExists))) => {}
508        Some(Err((_, error))) => return Err(format!("create Kafka topic {name:?}: {error}")),
509        None => return Err(format!("create Kafka topic {name:?} returned no result")),
510    }
511
512    let resource = ResourceSpecifier::Topic(&name);
513    let results = admin
514        .describe_configs([&resource], &AdminOptions::new())
515        .await
516        .map_err(|error| error.to_string())?;
517    let configuration = results
518        .into_iter()
519        .next()
520        .ok_or_else(|| format!("describe Kafka topic {name:?} returned no result"))?
521        .map_err(|error| format!("describe Kafka topic {name:?}: {error}"))?;
522    let actual = configuration
523        .get("retention.ms")
524        .and_then(|entry| entry.value.as_deref());
525    if actual != Some(retention_ms.as_str()) {
526        return Err(format!(
527            "Kafka topic {name:?} retention.ms is {actual:?}, manifest requires {retention_ms:?}"
528        ));
529    }
530    Ok(())
531}
532
533impl EventBus for KafkaBus {
534    fn set_control_key(&self, key: [u8; 32]) -> Result<(), BusError> {
535        if let Some(archive) = &self.cold_archive {
536            archive.set_control_key(key)?;
537        }
538        Ok(())
539    }
540
541    fn publish(&self, topic: &str, key: &str, value: &serde_json::Value) -> Result<PublishAck, BusError> {
542        let event_uid = value
543            .get("metadata")
544            .and_then(|metadata| metadata.get("uid"))
545            .and_then(serde_json::Value::as_str);
546        self.publish_with_uid(topic, key, value, event_uid)
547    }
548
549    fn publish_idempotent(
550        &self,
551        topic: &str,
552        key: &str,
553        value: &serde_json::Value,
554        event_uid: &str,
555    ) -> Result<PublishAck, BusError> {
556        self.publish_with_uid(topic, key, value, Some(event_uid))
557    }
558
559    fn find_event_by_uid(
560        &self,
561        topic: &str,
562        key: &str,
563        event_uid: &str,
564    ) -> Result<Option<PublishAck>, BusError> {
565        let partitions = *self
566            .topics
567            .get(topic)
568            .ok_or_else(|| BusError::UnknownTopic(topic.to_owned()))?;
569        let partition = partition_for(key, partitions);
570        let partition_client = self.partition_client(topic, partition)?;
571        let event_uid = event_uid.to_owned();
572        // One page per `executor.run` call: the executor imposes a hard
573        // 10 s timeout per operation, so running the whole earliest→latest
574        // scan inside a single call made lookups on partitions larger than
575        // one timeout's worth of fetches time out on every attempt, forever
576        // (each retry restarted from earliest under the same cap). Paging
577        // gives each bounded step its own budget — the same shape as the
578        // NATS implementation and the default trait implementation's
579        // per-`fetch` paging.
580        enum Page {
581            Found(i64),
582            Advanced(i64),
583            Empty,
584        }
585        let (mut offset, latest) = {
586            let client = Arc::clone(&partition_client);
587            self.executor
588                .run(move || async move {
589                    let earliest = client
590                        .get_offset(OffsetAt::Earliest)
591                        .await
592                        .map_err(|error| error.to_string())?;
593                    let latest = client
594                        .get_offset(OffsetAt::Latest)
595                        .await
596                        .map_err(|error| error.to_string())?;
597                    Ok::<_, String>((earliest, latest))
598                })?
599                .map_err(BusError::Backend)?
600        };
601        let mut empty_fetches = 0u32;
602        let found = loop {
603            if offset >= latest {
604                break None;
605            }
606            let client = Arc::clone(&partition_client);
607            let page_uid = event_uid.clone();
608            let page = self
609                .executor
610                .run(move || async move {
611                    let (records, _) = client
612                        .fetch_records(offset, 1..(16 * 1024 * 1024), 500)
613                        .await
614                        .map_err(|error| error.to_string())?;
615                    if records.is_empty() {
616                        return Ok::<_, String>(Page::Empty);
617                    }
618                    for record in &records {
619                        // `publish_with_uid` stamps the (possibly freshly
620                        // generated) uid into the `agentvisor-event-uid`
621                        // header even when the payload lacks
622                        // `metadata.uid`. Crash recovery for such an
623                        // event previously scanned only the payload
624                        // field, could never find the record it had in
625                        // fact produced, and re-published a duplicate.
626                        // Consult the header first, then the payload.
627                        if record
628                            .record
629                            .headers
630                            .get("agentvisor-event-uid")
631                            .is_some_and(|uid| uid.as_slice() == page_uid.as_bytes())
632                        {
633                            return Ok(Page::Found(record.offset));
634                        }
635                        if let Some(payload) = record.record.value.as_deref() {
636                            let stored: StoredEvent =
637                                serde_json::from_slice(payload).map_err(|error| error.to_string())?;
638                            if stored
639                                .value
640                                .get("metadata")
641                                .and_then(|metadata| metadata.get("uid"))
642                                .and_then(serde_json::Value::as_str)
643                                == Some(page_uid.as_str())
644                            {
645                                return Ok(Page::Found(record.offset));
646                            }
647                        }
648                    }
649                    let next = records
650                        .last()
651                        .and_then(|record| record.offset.checked_add(1))
652                        .ok_or_else(|| "Kafka event lookup offset overflow".to_owned())?;
653                    Ok(Page::Advanced(next))
654                })?
655                .map_err(BusError::Backend)?;
656            match page {
657                Page::Found(found_offset) => break Some(found_offset),
658                Page::Advanced(next) => {
659                    empty_fetches = 0;
660                    offset = next;
661                }
662                Page::Empty => {
663                    // `offset < latest` proves the broker still holds
664                    // records we have not seen; an empty response here is
665                    // a timing artifact (the 500 ms max_wait expired on a
666                    // loaded/rebalancing broker), NOT proof of absence.
667                    // Returning Ok(None) would let maintenance re-produce
668                    // an already-committed event — a duplicate in the
669                    // audit stream, the exact outcome this lookup exists
670                    // to prevent. Retry bounded, then fail the lookup so
671                    // the caller retries the whole pass later (the cold
672                    // intent is durable).
673                    empty_fetches += 1;
674                    if empty_fetches >= 8 {
675                        return Err(BusError::Backend(format!(
676                            "Kafka event lookup stalled: empty fetch at offset {offset} below latest {latest}"
677                        )));
678                    }
679                }
680            }
681        };
682        found
683            .map(|offset| {
684                u64::try_from(offset)
685                    .map(|offset| PublishAck {
686                        topic: topic.to_owned(),
687                        partition,
688                        offset,
689                    })
690                    .map_err(|_| BusError::Backend(format!("Kafka returned negative offset {offset}")))
691            })
692            .transpose()
693    }
694
695    fn fetch(
696        &self,
697        topic: &str,
698        partition: u32,
699        offset: u64,
700        max: usize,
701    ) -> Result<Vec<StoredEvent>, BusError> {
702        if !self.topics.contains_key(topic) {
703            return Err(BusError::UnknownTopic(topic.to_owned()));
704        }
705        let pc = self.partition_client(topic, partition)?;
706        // Reject offsets above
707        // `i64::MAX` explicitly rather than let `as i64` sign-wrap
708        // into a negative Kafka offset. The Kafka wire protocol
709        // treats -1 as "latest" and -2 as "earliest" (its own
710        // sentinel semantics), so a wrap could silently redirect
711        // the fetch to the log tail instead of the requested
712        // offset — a hard-to-diagnose replay divergence. In
713        // practice `u64` offsets that survive our provisioning
714        // stay well below 2^63, but crash recovery from a
715        // manifest whose offset field was tampered on disk could
716        // still supply a value in `(i64::MAX, u64::MAX]`.
717        let signed_offset = i64::try_from(offset).map_err(|_| {
718            BusError::Backend(format!(
719                "kafka fetch offset {offset} exceeds i64::MAX and would wrap to a negative \
720                 sentinel; refusing the fetch"
721            ))
722        })?;
723        // Contract: "read up to `max` events". The loop below checks the
724        // cap only AFTER pushing, so `max == 0` returned one event —
725        // diverging from the embedded broker, which returns an empty vec.
726        if max == 0 {
727            return Ok(Vec::new());
728        }
729        self.executor
730            .run(move || async move {
731                let (records, _high_watermark) = pc
732                    .fetch_records(signed_offset, 1..(16 * 1024 * 1024), 500)
733                    .await
734                    .map_err(|e| e.to_string())?;
735                let mut out = Vec::new();
736                for r in records {
737                    // Surface the error instead of silently
738                    // dropping a corrupt record. Parity with NatsBus and
739                    // EmbeddedBroker. An auditor or reconciler that sees a
740                    // shorter list than expected — with no error and no
741                    // offset gap — is an evidence gap. Because reconcilers
742                    // advance offset by `events.last().offset + 1`, a
743                    // silently-skipped corrupt record at offset N causes
744                    // the caller to bypass it entirely; keep the record on
745                    // the partition as forensic evidence.
746                    let value = r
747                        .record
748                        .value
749                        .ok_or_else(|| format!("fetch: null record value at offset {}", r.offset))?;
750                    let mut ev: StoredEvent = serde_json::from_slice(&value)
751                        .map_err(|e| format!("fetch decode at offset {}: {e}", r.offset))?;
752                    // Kafka offsets are non-negative by contract; a broken
753                    // or hostile broker returning a negative i64 must fail
754                    // the fetch instead of sign-wrapping into a huge u64
755                    // that corrupts the caller's offset ledger.
756                    ev.offset = u64::try_from(r.offset)
757                        .map_err(|_| format!("fetch: negative broker offset {}", r.offset))?;
758                    out.push(ev);
759                    if out.len() >= max {
760                        break;
761                    }
762                }
763                Ok::<_, String>(out)
764            })?
765            .map_err(BusError::Backend)
766    }
767
768    fn partitions(&self, topic: &str) -> Result<u32, BusError> {
769        self.topics
770            .get(topic)
771            .copied()
772            .ok_or_else(|| BusError::UnknownTopic(topic.to_owned()))
773    }
774
775    fn topics(&self) -> Vec<String> {
776        let mut t: Vec<String> = self.topics.keys().cloned().collect();
777        t.sort();
778        t
779    }
780
781    fn maintenance(&self, _now_ms: u64) -> Result<u64, BusError> {
782        self.cold_archive.as_ref().map_or(Ok(0), |archive| {
783            archive.retry_pending_with(|pending| {
784                // A crash/timeout between a successful produce and
785                // `commit()` leaves the intent offset-None while the event
786                // IS already on the partition; blindly re-producing here
787                // would append a duplicate to the audit stream. Consult the
788                // partition first and only publish when the UID is
789                // genuinely absent.
790                if let Some(ack) = self.find_event_by_uid(&pending.topic, &pending.key, &pending.event_uid)? {
791                    return Ok(ack);
792                }
793                self.publish_broker_only(
794                    &pending.topic,
795                    &pending.key,
796                    &pending.value,
797                    pending.stored_at,
798                    &pending.event_uid,
799                )
800            })
801        })
802    }
803}
804
805fn chrono_now() -> chrono::DateTime<chrono::Utc> {
806    chrono::Utc::now()
807}
808
809#[cfg(test)]
810mod tests {
811    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
812
813    use super::*;
814
815    fn lookup<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
816        move |name| {
817            pairs
818                .iter()
819                .find(|(key, _)| *key == name)
820                .map(|(_, value)| (*value).to_owned())
821        }
822    }
823
824    #[test]
825    fn no_security_env_means_plaintext_with_no_admin_overrides() {
826        let security = KafkaSecurity::from_lookup(lookup(&[])).unwrap();
827        assert!(security.ca_file.is_none() && security.credentials.is_none());
828        let mut config = ClientConfig::new();
829        security.apply_admin(&mut config);
830        assert!(config.get("security.protocol").is_none());
831        assert!(security.rskafka_tls().unwrap().is_none());
832        assert!(security.rskafka_sasl().is_none());
833    }
834
835    #[test]
836    fn partial_credentials_fail_loudly_not_anonymously() {
837        for pairs in [
838            &[("AV_KAFKA_SASL_USERNAME", "u")][..],
839            &[("AV_KAFKA_SASL_PASSWORD", "p")][..],
840        ] {
841            // No `unwrap_err`: that would require `Debug` on `KafkaSecurity`,
842            // and a derived `Debug` would make the SASL password printable.
843            let Err(error) = KafkaSecurity::from_lookup(lookup(pairs)) else {
844                panic!("partial credentials must be refused");
845            };
846            assert!(
847                error.to_string().contains("must be set together"),
848                "wrong error: {error}"
849            );
850        }
851    }
852
853    #[test]
854    fn sasl_plain_without_tls_is_refused() {
855        let Err(error) = KafkaSecurity::from_lookup(lookup(&[
856            ("AV_KAFKA_SASL_USERNAME", "u"),
857            ("AV_KAFKA_SASL_PASSWORD", "p"),
858        ])) else {
859            panic!("SASL without TLS must be refused");
860        };
861        assert!(error.to_string().contains("AV_KAFKA_CA_FILE"), "{error}");
862    }
863
864    #[test]
865    fn ca_only_selects_ssl_and_ca_plus_credentials_selects_sasl_ssl() {
866        let ssl_only = KafkaSecurity::from_lookup(lookup(&[("AV_KAFKA_CA_FILE", "/tmp/ca.crt")])).unwrap();
867        let mut config = ClientConfig::new();
868        ssl_only.apply_admin(&mut config);
869        assert_eq!(config.get("security.protocol"), Some("ssl"));
870        assert_eq!(config.get("ssl.ca.location"), Some("/tmp/ca.crt"));
871        assert!(config.get("sasl.mechanism").is_none());
872
873        let full = KafkaSecurity::from_lookup(lookup(&[
874            ("AV_KAFKA_CA_FILE", "/tmp/ca.crt"),
875            ("AV_KAFKA_SASL_USERNAME", "u"),
876            ("AV_KAFKA_SASL_PASSWORD", "p"),
877        ]))
878        .unwrap();
879        let mut config = ClientConfig::new();
880        full.apply_admin(&mut config);
881        assert_eq!(config.get("security.protocol"), Some("sasl_ssl"));
882        // SCRAM-SHA-256 is the default mechanism (Redpanda's native store).
883        assert_eq!(config.get("sasl.mechanism"), Some("SCRAM-SHA-256"));
884        assert_eq!(config.get("sasl.username"), Some("u"));
885        match full.rskafka_sasl() {
886            Some(SaslConfig::ScramSha256(credentials)) => {
887                assert_eq!(credentials.username, "u");
888                assert_eq!(credentials.password, "p");
889            }
890            other => panic!("expected SCRAM-SHA-256 sasl config, got {other:?}"),
891        }
892    }
893
894    /// Every supported mechanism maps consistently onto both client stacks,
895    /// and unknown mechanisms fail loudly instead of downgrading.
896    #[test]
897    fn sasl_mechanism_selection_is_explicit_and_validated() {
898        for (name, is_match) in [
899            (
900                "PLAIN",
901                (|s| matches!(s, Some(SaslConfig::Plain(_)))) as fn(Option<SaslConfig>) -> bool,
902            ),
903            ("SCRAM-SHA-256", |s| matches!(s, Some(SaslConfig::ScramSha256(_)))),
904            ("SCRAM-SHA-512", |s| matches!(s, Some(SaslConfig::ScramSha512(_)))),
905        ] {
906            let security = KafkaSecurity::from_lookup(lookup(&[
907                ("AV_KAFKA_CA_FILE", "/tmp/ca.crt"),
908                ("AV_KAFKA_SASL_USERNAME", "u"),
909                ("AV_KAFKA_SASL_PASSWORD", "p"),
910                ("AV_KAFKA_SASL_MECHANISM", name),
911            ]))
912            .unwrap();
913            let mut config = ClientConfig::new();
914            security.apply_admin(&mut config);
915            assert_eq!(config.get("sasl.mechanism"), Some(name));
916            assert!(is_match(security.rskafka_sasl()), "{name} must map on rskafka");
917        }
918        let Err(error) = KafkaSecurity::from_lookup(lookup(&[
919            ("AV_KAFKA_CA_FILE", "/tmp/ca.crt"),
920            ("AV_KAFKA_SASL_USERNAME", "u"),
921            ("AV_KAFKA_SASL_PASSWORD", "p"),
922            ("AV_KAFKA_SASL_MECHANISM", "GSSAPI"),
923        ])) else {
924            panic!("unsupported mechanism must be refused");
925        };
926        assert!(error.to_string().contains("not supported"), "{error}");
927    }
928
929    #[test]
930    fn missing_or_empty_ca_file_fails_loudly() {
931        let missing = KafkaSecurity {
932            ca_file: Some(std::path::PathBuf::from("/nonexistent/av-ca.crt")),
933            credentials: None,
934            mechanism: SaslMechanism::ScramSha256,
935        };
936        assert!(missing.rskafka_tls().is_err(), "missing CA file must error");
937
938        let dir = tempfile::tempdir().unwrap();
939        let empty = dir.path().join("empty.pem");
940        std::fs::write(&empty, b"not a pem").unwrap();
941        let security = KafkaSecurity {
942            ca_file: Some(empty),
943            credentials: None,
944            mechanism: SaslMechanism::ScramSha256,
945        };
946        let error = security.rskafka_tls().unwrap_err();
947        assert!(
948            error.to_string().contains("no PEM certificates"),
949            "wrong error: {error}"
950        );
951    }
952}