Skip to main content

mz_storage/source/
kafka.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11use std::collections::btree_map::Entry;
12use std::ops::{ControlFlow, RangeInclusive};
13use std::rc::Rc;
14use std::str::{self};
15use std::sync::Arc;
16use std::thread;
17use std::time::Duration;
18
19use anyhow::anyhow;
20use chrono::{DateTime, NaiveDateTime};
21use differential_dataflow::{AsCollection, Hashable};
22use futures::StreamExt;
23use itertools::Itertools;
24use maplit::btreemap;
25use mz_dyncfg::{Config, ConfigSet};
26use mz_kafka_util::client::{
27    GetPartitionsError, MzClientContext, PartitionId, TunnelingClientContext, get_partitions,
28};
29use mz_ore::assert_none;
30use mz_ore::cast::CastFrom;
31use mz_ore::error::ErrorExt;
32use mz_ore::future::InTask;
33use mz_ore::iter::IteratorExt;
34use mz_repr::adt::timestamp::CheckedTimestamp;
35use mz_repr::{Datum, Diff, GlobalId, Row, adt::jsonb::Jsonb};
36use mz_ssh_util::tunnel::SshTunnelStatus;
37use mz_storage_types::connections::KafkaConnection;
38use mz_storage_types::dyncfgs::{
39    KAFKA_SOURCE_FETCH_MESSAGE_MAX_BYTES, KAFKA_SOURCE_RECEIVE_MESSAGE_MAX_BYTES,
40};
41use mz_storage_types::errors::{
42    ContextCreationError, DataflowError, SourceError, SourceErrorDetails,
43};
44use mz_storage_types::sources::kafka::{
45    KafkaMetadataKind, KafkaSourceConnection, KafkaTimestamp, RangeBound,
46};
47use mz_storage_types::sources::{MzOffset, SourceExport, SourceExportDetails, SourceTimestamp};
48use mz_timely_util::antichain::AntichainExt;
49use mz_timely_util::builder_async::{
50    AsyncOutputHandle, Event, OperatorBuilder as AsyncOperatorBuilder, PressOnDropButton,
51};
52use mz_timely_util::containers::stack::FueledBuilder;
53use mz_timely_util::order::Partitioned;
54use rdkafka::consumer::base_consumer::PartitionQueue;
55use rdkafka::consumer::{BaseConsumer, Consumer, ConsumerContext};
56use rdkafka::error::KafkaError;
57use rdkafka::message::{BorrowedMessage, Headers};
58use rdkafka::statistics::Statistics;
59use rdkafka::topic_partition_list::Offset;
60use rdkafka::{ClientContext, Message, TopicPartitionList};
61use serde::{Deserialize, Serialize};
62use timely::PartialOrder;
63use timely::container::CapacityContainerBuilder;
64use timely::dataflow::channels::pact::Pipeline;
65use timely::dataflow::operators::Capability;
66use timely::dataflow::operators::core::Partition;
67use timely::dataflow::operators::vec::Broadcast;
68use timely::dataflow::{Scope, StreamVec};
69use timely::progress::Antichain;
70use timely::progress::Timestamp;
71use tokio::sync::{Notify, OnceCell, mpsc};
72use tracing::{error, info, trace, warn};
73
74use crate::healthcheck::{HealthStatusMessage, HealthStatusUpdate, StatusNamespace};
75use crate::metrics::source::kafka::KafkaSourceMetrics;
76use crate::source::types::{
77    FuelSize, Probe, ResumeUppers, SignaledFuture, SourceRender, StackedCollection,
78};
79use crate::source::{RawSourceCreationConfig, SourceMessage, probe};
80
81#[derive(
82    Clone,
83    Debug,
84    Default,
85    PartialEq,
86    Eq,
87    PartialOrd,
88    Ord,
89    Serialize,
90    Deserialize
91)]
92struct HealthStatus {
93    kafka: Option<HealthStatusUpdate>,
94    ssh: Option<HealthStatusUpdate>,
95}
96
97impl HealthStatus {
98    fn kafka(update: HealthStatusUpdate) -> Self {
99        Self {
100            kafka: Some(update),
101            ssh: None,
102        }
103    }
104
105    fn ssh(update: HealthStatusUpdate) -> Self {
106        Self {
107            kafka: None,
108            ssh: Some(update),
109        }
110    }
111}
112
113/// Contains all information necessary to ingest data from Kafka
114pub struct KafkaSourceReader {
115    /// Name of the topic on which this source is backed on
116    topic_name: String,
117    /// Name of the source (will have format kafka-source-id)
118    source_name: String,
119    /// Source global ID
120    id: GlobalId,
121    /// Kafka consumer for this source, created once this worker is responsible for a partition.
122    consumer: Rc<OnceCell<Arc<ReaderConsumer>>>,
123    /// List of consumers. A consumer should be assigned per partition to guarantee fairness
124    partition_consumers: Vec<PartitionConsumer>,
125    /// Worker ID
126    worker_id: usize,
127    /// Total count of workers
128    worker_count: usize,
129    /// The most recently read offset for each partition known to this source
130    /// reader by output-index. An offset of -1 indicates that no prior message
131    /// has been read for the given partition.
132    last_offsets: BTreeMap<usize, BTreeMap<PartitionId, i64>>,
133    /// The offset to start reading from for each partition.
134    start_offsets: BTreeMap<PartitionId, u64>,
135    /// Channel to receive Kafka statistics JSON blobs from the stats callback.
136    stats_rx: crossbeam_channel::Receiver<Jsonb>,
137    /// A handle to the partition specific metrics
138    partition_metrics: KafkaSourceMetrics,
139    /// Per partition capabilities used to produce messages
140    partition_capabilities: BTreeMap<PartitionId, PartitionCapability>,
141}
142
143type ReaderConsumer = BaseConsumer<TunnelingClientContext<GlueConsumerContext>>;
144
145struct PartitionCapability {
146    /// The capability of the data produced
147    data: Capability<KafkaTimestamp>,
148}
149
150/// The high/low watermark offsets of a Kafka partition.
151///
152/// This is the offset of either the first available or the latest message in the topic/partition
153///  available for consumption + 1.
154type PartitionWatermark = u64;
155
156/// Processes `resume_uppers` stream updates, committing them upstream and
157/// reporting each export's `offset_committed`.
158pub struct KafkaResumeUpperProcessor {
159    config: RawSourceCreationConfig,
160    topic_name: String,
161    /// Shared with [`KafkaSourceReader::consumer`].
162    consumer: Rc<OnceCell<Arc<ReaderConsumer>>>,
163    /// The offsets this worker last committed upstream. Only a successful commit updates it, so a
164    /// failed commit is retried on the next resume upper.
165    committed_offsets: Vec<(PartitionId, MzOffset)>,
166}
167
168/// Computes whether this worker is responsible for consuming a partition. It assigns partitions to
169/// workers in a round-robin fashion, starting at an arbitrary worker based on the hash of the
170/// source id.
171fn responsible_for_pid(config: &RawSourceCreationConfig, pid: i32) -> bool {
172    let pid = usize::try_from(pid).expect("positive pid");
173    ((config.responsible_worker(config.id) + pid) % config.worker_count) == config.worker_id
174}
175
176struct SourceOutputInfo {
177    id: GlobalId,
178    output_index: usize,
179    resume_upper: Antichain<KafkaTimestamp>,
180    metadata_columns: Vec<KafkaMetadataKind>,
181}
182
183impl SourceRender for KafkaSourceConnection {
184    // TODO(petrosagg): The type used for the partition (RangeBound<PartitionId>) doesn't need to
185    // be so complicated and we could instead use `Partitioned<PartitionId, Option<u64>>` where all
186    // ranges are inclusive and a time of `None` signifies that a particular partition is not
187    // present. This requires an shard migration of the remap shard.
188    type Time = KafkaTimestamp;
189
190    const STATUS_NAMESPACE: StatusNamespace = StatusNamespace::Kafka;
191
192    fn render<'scope>(
193        self,
194        scope: Scope<'scope, KafkaTimestamp>,
195        config: &RawSourceCreationConfig,
196        resume_uppers: impl futures::Stream<Item = ResumeUppers<KafkaTimestamp>> + 'static,
197        start_signal: impl std::future::Future<Output = ()> + 'static,
198    ) -> (
199        BTreeMap<
200            GlobalId,
201            StackedCollection<'scope, KafkaTimestamp, Result<SourceMessage, DataflowError>>,
202        >,
203        StreamVec<'scope, KafkaTimestamp, HealthStatusMessage>,
204        StreamVec<'scope, KafkaTimestamp, Probe<KafkaTimestamp>>,
205        Vec<PressOnDropButton>,
206    ) {
207        let (metadata, probes, metadata_token) =
208            render_metadata_fetcher(scope, self.clone(), config.clone());
209        let (data, health, reader_token) = render_reader(
210            scope,
211            self,
212            config.clone(),
213            resume_uppers,
214            metadata,
215            start_signal,
216        );
217
218        let partition_count = u64::cast_from(config.source_exports.len());
219        let data_streams: Vec<_> = data.inner.partition::<CapacityContainerBuilder<_>, _, _>(
220            partition_count,
221            |((output, data), time, diff)| {
222                let output = u64::cast_from(output);
223                (output, (data, time, diff))
224            },
225        );
226        let mut data_collections = BTreeMap::new();
227        for (id, data_stream) in config.source_exports.keys().zip_eq(data_streams) {
228            data_collections.insert(*id, data_stream.as_collection());
229        }
230
231        (
232            data_collections,
233            health,
234            probes,
235            vec![metadata_token, reader_token],
236        )
237    }
238}
239
240/// Render the reader of a Kafka source.
241///
242/// The reader is responsible for polling the Kafka topic partitions for new messages, and
243/// transforming them into a `SourceMessage` collection.
244fn render_reader<'scope>(
245    scope: Scope<'scope, KafkaTimestamp>,
246    connection: KafkaSourceConnection,
247    config: RawSourceCreationConfig,
248    resume_uppers: impl futures::Stream<Item = ResumeUppers<KafkaTimestamp>> + 'static,
249    metadata_stream: StreamVec<'scope, KafkaTimestamp, (mz_repr::Timestamp, MetadataUpdate)>,
250    start_signal: impl std::future::Future<Output = ()> + 'static,
251) -> (
252    StackedCollection<'scope, KafkaTimestamp, (usize, Result<SourceMessage, DataflowError>)>,
253    StreamVec<'scope, KafkaTimestamp, HealthStatusMessage>,
254    PressOnDropButton,
255) {
256    let name = format!("KafkaReader({})", config.id);
257    let mut builder = AsyncOperatorBuilder::new(name, scope.clone());
258
259    let (data_output, stream) = builder.new_output::<FueledBuilder<_>>();
260    let (health_output, health_stream) = builder.new_output::<CapacityContainerBuilder<Vec<_>>>();
261
262    let mut metadata_input = builder.new_disconnected_input(metadata_stream.broadcast(), Pipeline);
263
264    let mut outputs = vec![];
265
266    // Contains the `SourceStatistics` entries for exports that require a snapshot.
267    let mut all_export_stats = vec![];
268    let mut snapshot_export_stats = vec![];
269    for (idx, (id, export)) in config.source_exports.iter().enumerate() {
270        let SourceExport {
271            details,
272            storage_metadata: _,
273            data_config: _,
274        } = export;
275        let resume_upper = Antichain::from_iter(
276            config
277                .source_resume_uppers
278                .get(id)
279                .expect("all source exports must be present in source resume uppers")
280                .iter()
281                .map(Partitioned::<RangeBound<PartitionId>, MzOffset>::decode_row),
282        );
283
284        let metadata_columns = match details {
285            SourceExportDetails::Kafka(details) => details
286                .metadata_columns
287                .iter()
288                .map(|(_name, kind)| kind.clone())
289                .collect::<Vec<_>>(),
290            _ => panic!("unexpected source export details: {:?}", details),
291        };
292
293        let statistics = config
294            .statistics
295            .get(id)
296            .expect("statistics have been initialized")
297            .clone();
298        // export requires snapshot
299        if resume_upper.as_ref() == &[Partitioned::minimum()] {
300            snapshot_export_stats.push(statistics.clone());
301        }
302        all_export_stats.push(statistics);
303
304        let output = SourceOutputInfo {
305            id: *id,
306            resume_upper,
307            output_index: idx,
308            metadata_columns,
309        };
310        outputs.push(output);
311    }
312
313    let busy_signal = Arc::clone(&config.busy_signal);
314    let button = builder.build(move |caps| {
315        SignaledFuture::new(busy_signal, async move {
316            let [mut data_cap, health_cap] = caps.try_into().unwrap();
317
318            let client_id = connection.client_id(
319                config.config.config_set(),
320                &config.config.connection_context,
321                config.id,
322            );
323            let group_id = connection.group_id(&config.config.connection_context, config.id);
324            let KafkaSourceConnection {
325                connection,
326                topic,
327                topic_metadata_refresh_interval,
328                start_offsets,
329                metadata_columns: _,
330                // Exhaustive match protects against forgetting to apply an
331                // option. Ignored fields are justified below.
332                connection_id: _,   // not needed here
333                group_id_prefix: _, // used above via `connection.group_id`
334            } = connection;
335
336            info!(
337                source_id = config.id.to_string(),
338                worker_id = config.worker_id,
339                num_workers = config.worker_count,
340                "instantiating Kafka source reader at offsets {start_offsets:?}"
341            );
342
343            let (stats_tx, stats_rx) = crossbeam_channel::unbounded();
344            let notificator = Arc::new(Notify::new());
345
346            let consumer_setup = ReaderConsumerSetup {
347                config: config.clone(),
348                connection,
349                topic: topic.clone(),
350                topic_metadata_refresh_interval,
351                group_id,
352                client_id,
353                notificator: Arc::clone(&notificator),
354                stats_tx,
355                outputs: outputs.iter().map(|o| (o.id, o.output_index)).collect(),
356                data_output: data_output.clone(),
357                health_output: health_output.clone(),
358                health_cap: health_cap.clone(),
359            };
360            let consumer: Rc<OnceCell<Arc<ReaderConsumer>>> = Rc::default();
361
362            // Start offsets is a map from partition to the next offset to read from.
363            let mut start_offsets: BTreeMap<_, u64> = start_offsets
364                .clone()
365                .into_iter()
366                .filter(|(pid, _offset)| responsible_for_pid(&config, *pid))
367                .map(|(pid, offset)| (pid, u64::try_from(offset).expect("start offsets must be non-negative and fit into u64")))
368                .collect();
369
370            let mut partition_capabilities = BTreeMap::new();
371            let mut max_pid = None;
372            let resume_upper = Antichain::from_iter(
373                outputs
374                    .iter()
375                    .map(|output| output.resume_upper.clone())
376                    .flatten(),
377            );
378
379            tracing::info!(
380                source_id = config.id.to_string(),
381                worker_id = config.worker_id,
382                num_workers = config.worker_count,
383                "Kafka source reader starting rehydration with resume upper: {resume_upper:?} and start offsets: {start_offsets:?}"
384            );
385
386            for ts in resume_upper.elements() {
387                if let Some(pid) = ts.interval().singleton() {
388                    let pid = pid.unwrap_exact();
389                    max_pid = std::cmp::max(max_pid, Some(*pid));
390
391                    if responsible_for_pid(&config, *pid) {
392                        let restored_offset = ts.timestamp().offset;
393                        if let Some(start_offset) = start_offsets.get_mut(pid) {
394                            *start_offset = std::cmp::max(restored_offset, *start_offset);
395                        } else {
396                            start_offsets.insert(*pid, restored_offset);
397                        }
398
399                        let part_ts = Partitioned::new_singleton(
400                            RangeBound::exact(*pid),
401                            ts.timestamp().clone(),
402                        );
403                        let part_cap = PartitionCapability {
404                            data: data_cap.delayed(&part_ts),
405                        };
406                        partition_capabilities.insert(*pid, part_cap);
407                    }
408                }
409            }
410            let lower = max_pid
411                .map(RangeBound::after)
412                .unwrap_or(RangeBound::NegInfinity);
413            let future_ts =
414                Partitioned::new_range(lower, RangeBound::PosInfinity, MzOffset::from(0));
415            data_cap.downgrade(&future_ts);
416
417            // Each consumer owns librdkafka threads, one per broker plus internal ones, so only
418            // workers responsible for a partition create one. A worker that knows of no such
419            // partition yet creates its consumer when a metadata update assigns it one.
420            if !start_offsets.is_empty()
421                && consumer_setup
422                    .get_or_create(&consumer, &mut start_offsets, &data_cap)
423                    .await
424                    .is_break()
425            {
426                return;
427            }
428
429            // Note that we wait for this AFTER we downgrade to the source `resume_upper`. This
430            // allows downstream operators (namely, the `reclock_operator`) to downgrade to the
431            // `resume_upper`, which is necessary for this basic form of backpressure to work.
432            start_signal.await;
433            info!(
434                source_id = config.id.to_string(),
435                worker_id = config.worker_id,
436                num_workers = config.worker_count,
437                "kafka worker noticed rehydration is finished, starting partition queues..."
438            );
439
440            let partition_ids = start_offsets.keys().copied().collect();
441            let offset_commit_metrics = config.metrics.get_offset_commit_metrics(config.id);
442
443            let mut reader = KafkaSourceReader {
444                topic_name: topic.clone(),
445                source_name: config.name.clone(),
446                id: config.id,
447                partition_consumers: Vec::new(),
448                consumer: Rc::clone(&consumer),
449                worker_id: config.worker_id,
450                worker_count: config.worker_count,
451                last_offsets: outputs
452                    .iter()
453                    .map(|output| (output.output_index, BTreeMap::new()))
454                    .collect(),
455                start_offsets,
456                stats_rx,
457                partition_metrics: config.metrics.get_kafka_source_metrics(
458                    partition_ids,
459                    topic.clone(),
460                    config.id,
461                ),
462                partition_capabilities,
463            };
464
465            let mut offset_committer = KafkaResumeUpperProcessor {
466                config: config.clone(),
467                topic_name: topic.clone(),
468                consumer: Rc::clone(&consumer),
469                committed_offsets: Vec::new(),
470            };
471
472            // Seed the progress metrics from the resume uppers if we are snapshotting.
473            if !snapshot_export_stats.is_empty() {
474                let seed = ResumeUppers {
475                    source: Some(resume_upper.clone()),
476                    exports: outputs
477                        .iter()
478                        .map(|output| (output.id, output.resume_upper.clone()))
479                        .collect(),
480                };
481                if let Err(e) = offset_committer.process_frontier(&seed).await {
482                    offset_commit_metrics.offset_commit_failures.inc();
483                    tracing::warn!(
484                        %e,
485                        "timely-{worker_id} source({source_id}) failed to commit offsets: resume_upper={upper}",
486                        worker_id = config.worker_id,
487                        source_id = config.id,
488                        upper = resume_upper.pretty()
489                    );
490                }
491                // Reset snapshot statistics for any exports that are not involved
492                // in this round of snapshotting. Those that are snapshotting this round will
493                // see updates as the snapshot commences.
494                for statistics in config.statistics.values() {
495                    statistics.set_snapshot_records_known(0);
496                    statistics.set_snapshot_records_staged(0);
497                }
498            }
499
500            let refresh_interval = mz_storage_types::dyncfgs::KAFKA_OFFSET_COMMIT_REFRESH_INTERVAL
501                .get(config.config.config_set());
502            let resume_uppers_process_loop = async move {
503                tokio::pin!(resume_uppers);
504                // Zero disables the refresh. `interval` panics on a zero period, so the tick arm
505                // below is what honors it.
506                let mut refresh =
507                    tokio::time::interval(refresh_interval.max(Duration::from_millis(1)));
508                // A commit that outlasts a period must not be followed by a burst of recommits.
509                refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
510                let report = |e: anyhow::Error, what: &dyn std::fmt::Display| {
511                    offset_commit_metrics.offset_commit_failures.inc();
512                    tracing::warn!(
513                        %e,
514                        "timely-{worker_id} source({source_id}) failed to commit offsets: {what}",
515                        worker_id = config.worker_id,
516                        source_id = config.id,
517                    );
518                };
519                loop {
520                    tokio::select! {
521                        uppers = resume_uppers.next() => match uppers {
522                            Some(uppers) => {
523                                if let Err(e) = offset_committer.process_frontier(&uppers).await {
524                                    report(e, &uppers);
525                                }
526                            }
527                            None => break,
528                        },
529                        _ = refresh.tick(), if !refresh_interval.is_zero() => {
530                            if let Err(e) = offset_committer.refresh().await {
531                                report(e, &"refresh");
532                            }
533                        }
534                    }
535                }
536                // During dataflow shutdown this loop can end due to the general chaos caused by
537                // dropping tokens as a means to shutdown. This call ensures this future never ends
538                // and we instead rely on this operator being dropped altogether when *its* token
539                // is dropped.
540                std::future::pending::<()>().await;
541            };
542            tokio::pin!(resume_uppers_process_loop);
543
544            let mut metadata_update: Option<MetadataUpdate> = None;
545            let mut snapshot_total = None;
546
547            let max_wait_time =
548                mz_storage_types::dyncfgs::KAFKA_POLL_MAX_WAIT.get(config.config.config_set());
549            loop {
550                // Wait for data or metadata events while also making progress with offset
551                // committing.
552                tokio::select! {
553                    // TODO(petrosagg): remove the timeout and rely purely on librdkafka waking us
554                    // up
555                    _ = tokio::time::timeout(max_wait_time, notificator.notified()) => {},
556
557                    _ = metadata_input.ready() => {
558                        // Collect all pending updates, then only keep the most recent one.
559                        let mut updates = Vec::new();
560                        while let Some(event) = metadata_input.next_sync() {
561                            if let Event::Data(_, mut data) = event {
562                                updates.append(&mut data);
563                            }
564                        }
565                        metadata_update = updates
566                            .into_iter()
567                            .max_by_key(|(ts, _)| *ts)
568                            .map(|(_, update)| update);
569                    }
570
571                    // This future is not cancel safe but we are only passing a reference to it in
572                    // the select! loop so the future stays on the stack and never gets cancelled
573                    // until the end of the function.
574                    _ = resume_uppers_process_loop.as_mut() => {},
575                }
576
577                match metadata_update.take() {
578                    Some(MetadataUpdate::Partitions(partitions)) => {
579                        let max_pid = partitions.keys().last().cloned();
580                        let lower = max_pid
581                            .map(RangeBound::after)
582                            .unwrap_or(RangeBound::NegInfinity);
583                        let future_ts = Partitioned::new_range(
584                            lower,
585                            RangeBound::PosInfinity,
586                            MzOffset::from(0),
587                        );
588
589                        let mut offset_known = 0;
590                        for (&pid, &high_watermark) in &partitions {
591                            if responsible_for_pid(&config, pid) {
592                                offset_known += high_watermark;
593                                let kafka_consumer = match consumer_setup
594                                    .get_or_create(&consumer, &mut reader.start_offsets, &data_cap)
595                                    .await
596                                {
597                                    ControlFlow::Continue(kafka_consumer) => {
598                                        Arc::clone(kafka_consumer)
599                                    }
600                                    ControlFlow::Break(()) => return,
601                                };
602                                reader.ensure_partition(&kafka_consumer, pid);
603                                if let Entry::Vacant(entry) =
604                                    reader.partition_capabilities.entry(pid)
605                                {
606                                    let start_offset =
607                                        reader.start_offsets.get(&pid).copied().unwrap_or(0);
608                                    let part_since_ts = Partitioned::new_singleton(
609                                        RangeBound::exact(pid),
610                                        MzOffset::from(start_offset),
611                                    );
612
613                                    entry.insert(PartitionCapability {
614                                        data: data_cap.delayed(&part_since_ts),
615                                    });
616                                }
617                            }
618                        }
619
620                        // If we are snapshotting, record our first set of partitions as the snapshot
621                        // size.
622                        if !snapshot_export_stats.is_empty() && snapshot_total.is_none() {
623                            // Note that we want to represent the _number of offsets_, which
624                            // means the watermark's frontier semantics is correct, without
625                            // subtracting (Kafka offsets start at 0).
626                            snapshot_total = Some(offset_known);
627                        }
628
629                        // Clear all the health namespaces we know about.
630                        // Note that many kafka sources's don't have an ssh tunnel, but the
631                        // `health_operator` handles this fine.
632                        for output in &outputs {
633                            for namespace in [StatusNamespace::Kafka, StatusNamespace::Ssh] {
634                                health_output.give(
635                                    &health_cap,
636                                    HealthStatusMessage {
637                                        id: Some(output.id),
638                                        namespace,
639                                        update: HealthStatusUpdate::running(),
640                                    },
641                                );
642                            }
643                        }
644                        for namespace in [StatusNamespace::Kafka, StatusNamespace::Ssh] {
645                            health_output.give(
646                                &health_cap,
647                                HealthStatusMessage {
648                                    id: None,
649                                    namespace,
650                                    update: HealthStatusUpdate::running(),
651                                },
652                            );
653                        }
654
655                        for export_stat in all_export_stats.iter() {
656                            export_stat.set_offset_known(offset_known);
657                        }
658
659                        data_cap.downgrade(&future_ts);
660                    }
661                    Some(MetadataUpdate::TransientError(status)) => {
662                        if let Some(update) = status.kafka {
663                            health_output.give(
664                                &health_cap,
665                                HealthStatusMessage {
666                                    id: None,
667                                    namespace: StatusNamespace::Kafka,
668                                    update: update.clone(),
669                                },
670                            );
671                            for (output, update) in outputs.iter().repeat_clone(update) {
672                                health_output.give(
673                                    &health_cap,
674                                    HealthStatusMessage {
675                                        id: Some(output.id),
676                                        namespace: StatusNamespace::Kafka,
677                                        update,
678                                    },
679                                );
680                            }
681                        }
682                        if let Some(update) = status.ssh {
683                            health_output.give(
684                                &health_cap,
685                                HealthStatusMessage {
686                                    id: None,
687                                    namespace: StatusNamespace::Ssh,
688                                    update: update.clone(),
689                                },
690                            );
691                            for (output, update) in outputs.iter().repeat_clone(update) {
692                                health_output.give(
693                                    &health_cap,
694                                    HealthStatusMessage {
695                                        id: Some(output.id),
696                                        namespace: StatusNamespace::Ssh,
697                                        update,
698                                    },
699                                );
700                            }
701                        }
702                    }
703                    Some(MetadataUpdate::DefiniteError(error)) => {
704                        health_output.give(
705                            &health_cap,
706                            HealthStatusMessage {
707                                id: None,
708                                namespace: StatusNamespace::Kafka,
709                                update: HealthStatusUpdate::stalled(
710                                    error.to_string(),
711                                    None,
712                                ),
713                            },
714                        );
715                        let error = Err(error.into());
716                        let time = data_cap.time().clone();
717                        for (output, error) in
718                            outputs.iter().map(|o| o.output_index).repeat_clone(error)
719                        {
720                            let update = ((output, error), time, Diff::ONE);
721                            let size = update.fuel_size();
722                            data_output
723                                .give_fueled(&data_cap, update, size)
724                                .await;
725                        }
726
727                        return;
728                    }
729                    None => {}
730                }
731
732                // Poll the consumer once. We split the consumer's partitions out into separate
733                // queues and poll those individually, but it's still necessary to drive logic that
734                // consumes from rdkafka's internal event queue, such as statistics callbacks.
735                //
736                // Additionally, assigning topics and splitting them off into separate queues is
737                // not atomic, so we expect to see at least some messages to show up when polling
738                // the consumer directly.
739                let polled_consumer = reader.consumer.get().map(Arc::clone);
740                while let Some(result) = polled_consumer
741                    .as_ref()
742                    .and_then(|consumer| consumer.poll(Duration::from_secs(0)))
743                {
744                    match result {
745                        Err(e) => {
746                            let error = format!(
747                                "kafka error when polling consumer for source: {} topic: {} : {}",
748                                reader.source_name, reader.topic_name, e
749                            );
750                            let status = HealthStatusUpdate::stalled(error, None);
751                            health_output.give(
752                                &health_cap,
753                                HealthStatusMessage {
754                                    id: None,
755                                    namespace: StatusNamespace::Kafka,
756                                    update: status.clone(),
757                                },
758                            );
759                            for (output, status) in outputs.iter().repeat_clone(status) {
760                                health_output.give(
761                                    &health_cap,
762                                    HealthStatusMessage {
763                                        id: Some(output.id),
764                                        namespace: StatusNamespace::Kafka,
765                                        update: status,
766                                    },
767                                );
768                            }
769                        }
770                        Ok(message) => {
771                            let output_messages = outputs
772                                .iter()
773                                .map(|output| {
774                                    let (message, ts) = construct_source_message(
775                                        &message,
776                                        &output.metadata_columns,
777                                    );
778                                    (output.output_index, message, ts)
779                                })
780                                // This vec allocation is required to allow obtaining a `&mut`
781                                // on `reader` for the `reader.handle_message` call in the
782                                // loop below since  `message` is borrowed from `reader`.
783                                .collect::<Vec<_>>();
784                            for (output_index, message, ts) in output_messages {
785                                if let Some((msg, time, diff)) =
786                                    reader.handle_message(message, ts, &output_index)
787                                {
788                                    let pid = time.interval().singleton().unwrap().unwrap_exact();
789                                    let part_cap = &reader.partition_capabilities[pid].data;
790                                    let msg = msg.map_err(|e| {
791                                        DataflowError::SourceError(Box::new(SourceError {
792                                            error: SourceErrorDetails::Other(e.to_string().into()),
793                                            hint: None,
794                                        }))
795                                    });
796                                    let update = ((output_index, msg), time, diff);
797                                    let size = update.fuel_size();
798                                    data_output
799                                        .give_fueled(part_cap, update, size)
800                                        .await;
801                                }
802                            }
803                        }
804                    }
805                }
806
807                reader.update_stats();
808
809                // Take the consumers temporarily to get around borrow checker errors
810                let mut consumers = std::mem::take(&mut reader.partition_consumers);
811                for consumer in consumers.iter_mut() {
812                    let pid = consumer.pid();
813                    // We want to make sure the rest of the actions in the outer loops get
814                    // a chance to run. If rdkafka keeps pumping data at us we might find
815                    // ourselves in a situation where we keep dumping data into the
816                    // dataflow without signaling progress. For this reason we consume at most
817                    // 10k messages from each partition and go around the loop.
818                    let mut partition_exhausted = false;
819                    for _ in 0..10_000 {
820                        let Some(message) = consumer.get_next_message().transpose() else {
821                            partition_exhausted = true;
822                            break;
823                        };
824
825                        for output in outputs.iter() {
826                            let message = match &message {
827                                Ok((msg, pid)) => {
828                                    let (msg, ts) =
829                                        construct_source_message(msg, &output.metadata_columns);
830                                    assert_eq!(*pid, ts.0);
831                                    Ok(reader.handle_message(msg, ts, &output.output_index))
832                                }
833                                Err(err) => Err(err),
834                            };
835                            match message {
836                                Ok(Some((msg, time, diff))) => {
837                                    let pid = time.interval().singleton().unwrap().unwrap_exact();
838                                    let part_cap = &reader.partition_capabilities[pid].data;
839                                    let msg = msg.map_err(|e| {
840                                        DataflowError::SourceError(Box::new(SourceError {
841                                            error: SourceErrorDetails::Other(e.to_string().into()),
842                                            hint: None,
843                                        }))
844                                    });
845                                    let update =
846                                        ((output.output_index, msg), time, diff);
847                                    let size = update.fuel_size();
848                                    data_output
849                                        .give_fueled(part_cap, update, size)
850                                        .await;
851                                }
852                                // The message was from an offset we've already seen.
853                                Ok(None) => continue,
854                                Err(err) => {
855                                    let last_offset = reader
856                                        .last_offsets
857                                        .get(&output.output_index)
858                                        .expect("output known to be installed")
859                                        .get(&pid)
860                                        .expect("partition known to be installed");
861
862                                    let status = HealthStatusUpdate::stalled(
863                                        format!(
864                                            "error consuming from source: {} topic: {topic}:\
865                                             partition: {pid} last processed offset:\
866                                             {last_offset} : {err}",
867                                            config.name
868                                        ),
869                                        None,
870                                    );
871                                    health_output.give(
872                                        &health_cap,
873                                        HealthStatusMessage {
874                                            id: None,
875                                            namespace: StatusNamespace::Kafka,
876                                            update: status.clone(),
877                                        },
878                                    );
879                                    health_output.give(
880                                        &health_cap,
881                                        HealthStatusMessage {
882                                            id: Some(output.id),
883                                            namespace: StatusNamespace::Kafka,
884                                            update: status,
885                                        },
886                                    );
887                                }
888                            }
889                        }
890                    }
891                    if !partition_exhausted {
892                        notificator.notify_one();
893                    }
894                }
895                // We can now put them back
896                assert!(reader.partition_consumers.is_empty());
897                reader.partition_consumers = consumers;
898
899                let positions = match reader.consumer.get() {
900                    Some(consumer) => consumer.position().unwrap(),
901                    None => TopicPartitionList::new(),
902                };
903                let topic_positions = positions.elements_for_topic(&reader.topic_name);
904                let mut snapshot_staged = 0;
905
906                for position in topic_positions {
907                    // The offset begins in the `Offset::Invalid` state in which case we simply
908                    // skip this partition.
909                    if let Offset::Offset(offset) = position.offset() {
910                        let pid = position.partition();
911                        let upper_offset = MzOffset::from(u64::try_from(offset).unwrap());
912                        let upper =
913                            Partitioned::new_singleton(RangeBound::exact(pid), upper_offset);
914
915                        let part_cap = reader.partition_capabilities.get_mut(&pid).unwrap();
916                        match part_cap.data.try_downgrade(&upper) {
917                            Ok(()) => {
918                                if !snapshot_export_stats.is_empty() {
919                                    // The `.position()` of the consumer represents what offset we have
920                                    // read up to.
921                                    snapshot_staged += offset.try_into().unwrap_or(0u64);
922                                    // This will always be `Some` at this point.
923                                    if let Some(snapshot_total) = snapshot_total {
924                                        // We will eventually read past the snapshot total, so we need
925                                        // to bound it here.
926                                        snapshot_staged =
927                                            std::cmp::min(snapshot_staged, snapshot_total);
928                                    }
929                                }
930                            }
931                            Err(_) => {
932                                // If we can't downgrade, it means we have already seen this offset.
933                                // This is expected and we can safely ignore it.
934                                info!(
935                                    source_id = config.id.to_string(),
936                                    worker_id = config.worker_id,
937                                    num_workers = config.worker_count,
938                                    "kafka source frontier downgrade skipped due to already \
939                                     seen offset: {:?}",
940                                    upper
941                                );
942                            }
943                        };
944
945                    }
946                }
947
948                if let (Some(snapshot_total), true) =
949                    (snapshot_total, !snapshot_export_stats.is_empty())
950                {
951                    for export_stat in snapshot_export_stats.iter() {
952                        export_stat.set_snapshot_records_known(snapshot_total);
953                        export_stat.set_snapshot_records_staged(snapshot_staged);
954                    }
955                    if snapshot_total == snapshot_staged {
956                        snapshot_export_stats.clear();
957                    }
958                }
959            }
960        })
961    });
962
963    (
964        stream.as_collection(),
965        health_stream,
966        button.press_on_drop(),
967    )
968}
969
970impl KafkaResumeUpperProcessor {
971    /// Reports each export's `offset_committed` and commits the source upper's offsets upstream
972    /// when they differ from the last successful commit.
973    async fn process_frontier(
974        &mut self,
975        uppers: &ResumeUppers<KafkaTimestamp>,
976    ) -> Result<(), anyhow::Error> {
977        for (id, frontier) in &uppers.exports {
978            if let Some(stat) = self.config.statistics.get(id) {
979                // Note that we do not subtract 1 from the frontier. Imagine
980                // that frontier is 2 for this pid. That means we have
981                // full processed offset 0 and offset 1, which means we have
982                // processed _2_ offsets.
983                let offset_committed = self
984                    .responsible_offsets(frontier)
985                    .map(|(_, offset)| offset.offset)
986                    .sum();
987                stat.set_offset_committed(offset_committed);
988            }
989        }
990
991        let Some(frontier) = &uppers.source else {
992            return Ok(());
993        };
994        let offsets: Vec<_> = self.responsible_offsets(frontier).collect();
995        // `uppers` changes whenever any export's upper moves, usually leaving this worker's
996        // offsets unchanged, and each commit is a synchronous round trip to the group coordinator.
997        if offsets.is_empty() || offsets == self.committed_offsets {
998            return Ok(());
999        }
1000        // Without a consumer the offsets stay uncommitted, and a later upper retries them.
1001        let Some(consumer) = self.consumer.get() else {
1002            return Ok(());
1003        };
1004        self.commit(consumer, &offsets).await?;
1005        self.committed_offsets = offsets;
1006        Ok(())
1007    }
1008
1009    /// Recommits the offsets of the last successful commit. The consumer only ever `assign`s, so
1010    /// the broker treats its group as standalone and expires a partition's offset
1011    /// `offsets.retention.minutes` after that partition's last commit, current or not.
1012    async fn refresh(&self) -> Result<(), anyhow::Error> {
1013        // Offsets are only ever committed through a consumer.
1014        let Some(consumer) = self.consumer.get() else {
1015            return Ok(());
1016        };
1017        if self.committed_offsets.is_empty() {
1018            return Ok(());
1019        }
1020        self.commit(consumer, &self.committed_offsets).await
1021    }
1022
1023    async fn commit(
1024        &self,
1025        consumer: &Arc<ReaderConsumer>,
1026        offsets: &[(PartitionId, MzOffset)],
1027    ) -> Result<(), anyhow::Error> {
1028        use rdkafka::consumer::CommitMode;
1029
1030        let mut tpl = TopicPartitionList::new();
1031        for (pid, offset) in offsets {
1032            let offset_to_commit =
1033                Offset::Offset(offset.offset.try_into().expect("offset to be vald i64"));
1034            tpl.add_partition_offset(&self.topic_name, *pid, offset_to_commit)
1035                .expect("offset known to be valid");
1036        }
1037        let consumer = Arc::clone(consumer);
1038        mz_ore::task::spawn_blocking(
1039            || format!("source({}) kafka offset commit", self.config.id),
1040            move || consumer.commit(&tpl, CommitMode::Sync),
1041        )
1042        .await?;
1043        Ok(())
1044    }
1045
1046    /// The offsets of `frontier` in the partitions this worker is responsible for.
1047    fn responsible_offsets<'a>(
1048        &'a self,
1049        frontier: &'a Antichain<KafkaTimestamp>,
1050    ) -> impl Iterator<Item = (PartitionId, MzOffset)> + 'a {
1051        frontier.iter().filter_map(|ts| {
1052            let pid = *ts.interval().singleton()?.unwrap_exact();
1053            responsible_for_pid(&self.config, pid).then(|| (pid, *ts.timestamp()))
1054        })
1055    }
1056}
1057
1058impl KafkaSourceReader {
1059    /// Ensures that a partition queue for `pid` exists.
1060    fn ensure_partition(&mut self, consumer: &Arc<ReaderConsumer>, pid: PartitionId) {
1061        if self.last_offsets.is_empty() {
1062            tracing::info!(
1063                source_id = %self.id,
1064                worker_id = %self.worker_id,
1065                "kafka source does not have any outputs, not creating partition queue");
1066
1067            return;
1068        }
1069        for last_offsets in self.last_offsets.values() {
1070            // early exit if we've already inserted this partition
1071            if last_offsets.contains_key(&pid) {
1072                return;
1073            }
1074        }
1075
1076        let start_offset = self.start_offsets.get(&pid).copied().unwrap_or(0);
1077        let start_offset = i64::try_from(start_offset).expect("start offsets must fit into i64");
1078        self.create_partition_queue(consumer, pid, Offset::Offset(start_offset));
1079
1080        for last_offsets in self.last_offsets.values_mut() {
1081            let prev = last_offsets.insert(pid, start_offset - 1);
1082            assert_none!(prev);
1083        }
1084    }
1085
1086    /// Creates a new partition queue for `partition_id`.
1087    fn create_partition_queue(
1088        &mut self,
1089        consumer: &Arc<ReaderConsumer>,
1090        partition_id: PartitionId,
1091        initial_offset: Offset,
1092    ) {
1093        info!(
1094            source_id = self.id.to_string(),
1095            worker_id = self.worker_id,
1096            num_workers = self.worker_count,
1097            "activating Kafka queue for topic {}, partition {}",
1098            self.topic_name,
1099            partition_id,
1100        );
1101
1102        // Collect old partition assignments
1103        let tpl = consumer.assignment().unwrap();
1104        // Create list from assignments
1105        let mut partition_list = TopicPartitionList::new();
1106        for partition in tpl.elements_for_topic(&self.topic_name) {
1107            partition_list
1108                .add_partition_offset(partition.topic(), partition.partition(), partition.offset())
1109                .expect("offset known to be valid");
1110        }
1111        // Add new partition
1112        partition_list
1113            .add_partition_offset(&self.topic_name, partition_id, initial_offset)
1114            .expect("offset known to be valid");
1115        consumer
1116            .assign(&partition_list)
1117            .expect("assignment known to be valid");
1118
1119        // Since librdkafka v1.6.0, we need to recreate all partition queues
1120        // after every call to `consumer.assign`.
1121        let context = Arc::clone(consumer.context());
1122        for pc in &mut self.partition_consumers {
1123            pc.partition_queue = consumer
1124                .split_partition_queue(&self.topic_name, pc.pid)
1125                .expect("partition known to be valid");
1126            pc.partition_queue.set_nonempty_callback({
1127                let context = Arc::clone(&context);
1128                move || context.inner().activate()
1129            });
1130        }
1131
1132        let mut partition_queue = consumer
1133            .split_partition_queue(&self.topic_name, partition_id)
1134            .expect("partition known to be valid");
1135        partition_queue.set_nonempty_callback(move || context.inner().activate());
1136        self.partition_consumers
1137            .push(PartitionConsumer::new(partition_id, partition_queue));
1138        assert_eq!(
1139            consumer
1140                .assignment()
1141                .unwrap()
1142                .elements_for_topic(&self.topic_name)
1143                .len(),
1144            self.partition_consumers.len()
1145        );
1146    }
1147
1148    /// Read any statistics JSON blobs generated via the rdkafka statistics callback.
1149    fn update_stats(&mut self) {
1150        while let Ok(stats) = self.stats_rx.try_recv() {
1151            match serde_json::from_str::<Statistics>(&stats.to_string()) {
1152                Ok(statistics) => {
1153                    let topic = statistics.topics.get(&self.topic_name);
1154                    match topic {
1155                        Some(topic) => {
1156                            for (id, partition) in &topic.partitions {
1157                                self.partition_metrics
1158                                    .set_offset_max(*id, partition.hi_offset);
1159                            }
1160                        }
1161                        None => error!("No stats found for topic: {}", &self.topic_name),
1162                    }
1163                }
1164                Err(e) => {
1165                    error!("failed decoding librdkafka statistics JSON: {}", e);
1166                }
1167            }
1168        }
1169    }
1170
1171    /// Checks if the given message is viable for emission. This checks if the message offset is
1172    /// past the expected offset and returns None if it is not.
1173    fn handle_message(
1174        &mut self,
1175        message: Result<SourceMessage, KafkaHeaderParseError>,
1176        (partition, offset): (PartitionId, MzOffset),
1177        output_index: &usize,
1178    ) -> Option<(
1179        Result<SourceMessage, KafkaHeaderParseError>,
1180        KafkaTimestamp,
1181        Diff,
1182    )> {
1183        // Offsets are guaranteed to be 1) monotonically increasing *unless* there is
1184        // a network issue or a new partition added, at which point the consumer may
1185        // start processing the topic from the beginning, or we may see duplicate offsets
1186        // At all times, the guarantee : if we see offset x, we have seen all offsets [0,x-1]
1187        // that we are ever going to see holds.
1188        // Offsets are guaranteed to be contiguous when compaction is disabled. If compaction
1189        // is enabled, there may be gaps in the sequence.
1190        // If we see an "old" offset, we skip that message.
1191
1192        // Given the explicit consumer to partition assignment, we should never receive a message
1193        // for a partition for which we have no metadata
1194        assert!(
1195            self.last_offsets
1196                .get(output_index)
1197                .unwrap()
1198                .contains_key(&partition)
1199        );
1200
1201        let last_offset_ref = self
1202            .last_offsets
1203            .get_mut(output_index)
1204            .expect("output known to be installed")
1205            .get_mut(&partition)
1206            .expect("partition known to be installed");
1207
1208        let last_offset = *last_offset_ref;
1209        let offset_as_i64: i64 = offset.offset.try_into().expect("offset to be < i64::MAX");
1210        if offset_as_i64 <= last_offset {
1211            info!(
1212                source_id = self.id.to_string(),
1213                worker_id = self.worker_id,
1214                num_workers = self.worker_count,
1215                "kafka message before expected offset: \
1216                 source {} (reading topic {}, partition {}, output {}) \
1217                 received offset {} expected offset {:?}",
1218                self.source_name,
1219                self.topic_name,
1220                partition,
1221                output_index,
1222                offset.offset,
1223                last_offset + 1,
1224            );
1225            // We explicitly should not consume the message as we have already processed it.
1226            None
1227        } else {
1228            *last_offset_ref = offset_as_i64;
1229
1230            let ts = Partitioned::new_singleton(RangeBound::exact(partition), offset);
1231            Some((message, ts, Diff::ONE))
1232        }
1233    }
1234}
1235
1236fn construct_source_message(
1237    msg: &BorrowedMessage<'_>,
1238    metadata_columns: &[KafkaMetadataKind],
1239) -> (
1240    Result<SourceMessage, KafkaHeaderParseError>,
1241    (PartitionId, MzOffset),
1242) {
1243    let pid = msg.partition();
1244    let Ok(offset) = u64::try_from(msg.offset()) else {
1245        panic!(
1246            "got negative offset ({}) from otherwise non-error'd kafka message",
1247            msg.offset()
1248        );
1249    };
1250
1251    let mut metadata = Row::default();
1252    let mut packer = metadata.packer();
1253    for kind in metadata_columns {
1254        match kind {
1255            KafkaMetadataKind::Partition => packer.push(Datum::from(pid)),
1256            KafkaMetadataKind::Offset => packer.push(Datum::UInt64(offset)),
1257            KafkaMetadataKind::Timestamp => {
1258                let ts = msg
1259                    .timestamp()
1260                    .to_millis()
1261                    .expect("kafka sources always have upstream_time");
1262
1263                let d: Datum = DateTime::from_timestamp_millis(ts)
1264                    .and_then(|dt| {
1265                        let ct: Option<CheckedTimestamp<NaiveDateTime>> =
1266                            dt.naive_utc().try_into().ok();
1267                        ct
1268                    })
1269                    .into();
1270                packer.push(d)
1271            }
1272            KafkaMetadataKind::Header { key, use_bytes } => {
1273                match msg.headers() {
1274                    Some(headers) => {
1275                        let d = headers
1276                            .iter()
1277                            .filter(|header| header.key == key)
1278                            .last()
1279                            .map(|header| match header.value {
1280                                Some(v) => {
1281                                    if *use_bytes {
1282                                        Ok(Datum::Bytes(v))
1283                                    } else {
1284                                        match str::from_utf8(v) {
1285                                            Ok(str) => Ok(Datum::String(str)),
1286                                            Err(_) => Err(KafkaHeaderParseError::Utf8Error {
1287                                                key: key.clone(),
1288                                                raw: v.to_vec(),
1289                                            }),
1290                                        }
1291                                    }
1292                                }
1293                                None => Ok(Datum::Null),
1294                            })
1295                            .unwrap_or_else(|| {
1296                                Err(KafkaHeaderParseError::KeyNotFound { key: key.clone() })
1297                            });
1298                        match d {
1299                            Ok(d) => packer.push(d),
1300                            //abort with a definite error when the header is not found or cannot be parsed correctly
1301                            Err(err) => return (Err(err), (pid, offset.into())),
1302                        }
1303                    }
1304                    None => packer.push(Datum::Null),
1305                }
1306            }
1307            KafkaMetadataKind::Headers => {
1308                packer.push_list_with(|r| {
1309                    if let Some(headers) = msg.headers() {
1310                        for header in headers.iter() {
1311                            match header.value {
1312                                Some(v) => r.push_list_with(|record_row| {
1313                                    record_row.push(Datum::String(header.key));
1314                                    record_row.push(Datum::Bytes(v));
1315                                }),
1316                                None => r.push_list_with(|record_row| {
1317                                    record_row.push(Datum::String(header.key));
1318                                    record_row.push(Datum::Null);
1319                                }),
1320                            }
1321                        }
1322                    }
1323                });
1324            }
1325        }
1326    }
1327
1328    let key = match msg.key() {
1329        Some(bytes) => Row::pack([Datum::Bytes(bytes)]),
1330        None => Row::pack([Datum::Null]),
1331    };
1332    let value = match msg.payload() {
1333        Some(bytes) => Row::pack([Datum::Bytes(bytes)]),
1334        None => Row::pack([Datum::Null]),
1335    };
1336    (
1337        Ok(SourceMessage {
1338            key,
1339            value,
1340            metadata,
1341        }),
1342        (pid, offset.into()),
1343    )
1344}
1345
1346/// Wrapper around a partition containing the underlying consumer
1347struct PartitionConsumer {
1348    /// the partition id with which this consumer is associated
1349    pid: PartitionId,
1350    /// The underlying Kafka partition queue
1351    partition_queue: PartitionQueue<TunnelingClientContext<GlueConsumerContext>>,
1352}
1353
1354impl PartitionConsumer {
1355    /// Creates a new partition consumer from underlying Kafka consumer
1356    fn new(
1357        pid: PartitionId,
1358        partition_queue: PartitionQueue<TunnelingClientContext<GlueConsumerContext>>,
1359    ) -> Self {
1360        PartitionConsumer {
1361            pid,
1362            partition_queue,
1363        }
1364    }
1365
1366    /// Returns the next message to process for this partition (if any).
1367    ///
1368    /// The outer `Result` represents irrecoverable failures, the inner one can and will
1369    /// be transformed into empty values.
1370    ///
1371    /// The inner `Option` represents if there is a message to process.
1372    fn get_next_message(&self) -> Result<Option<(BorrowedMessage<'_>, PartitionId)>, KafkaError> {
1373        match self.partition_queue.poll(Duration::from_millis(0)) {
1374            Some(Ok(msg)) => Ok(Some((msg, self.pid))),
1375            Some(Err(err)) => Err(err),
1376            _ => Ok(None),
1377        }
1378    }
1379
1380    /// Return the partition id for this PartitionConsumer
1381    fn pid(&self) -> PartitionId {
1382        self.pid
1383    }
1384}
1385
1386/// An implementation of [`ConsumerContext`] that forwards statistics to the
1387/// worker
1388struct GlueConsumerContext {
1389    notificator: Arc<Notify>,
1390    stats_tx: crossbeam_channel::Sender<Jsonb>,
1391    inner: MzClientContext,
1392}
1393
1394impl ClientContext for GlueConsumerContext {
1395    fn stats_raw(&self, statistics: &[u8]) {
1396        match Jsonb::from_slice(statistics) {
1397            Ok(statistics) => {
1398                self.stats_tx
1399                    .send(statistics)
1400                    .expect("timely operator hung up while Kafka source active");
1401                self.activate();
1402            }
1403            Err(e) => error!("failed decoding librdkafka statistics JSON: {}", e),
1404        };
1405    }
1406
1407    // The shape of the rdkafka *Context traits require us to forward to the `MzClientContext`
1408    // implementation.
1409    fn log(&self, level: rdkafka::config::RDKafkaLogLevel, fac: &str, log_message: &str) {
1410        self.inner.log(level, fac, log_message)
1411    }
1412    fn error(&self, error: rdkafka::error::KafkaError, reason: &str) {
1413        self.inner.error(error, reason)
1414    }
1415}
1416
1417impl GlueConsumerContext {
1418    fn activate(&self) {
1419        self.notificator.notify_one();
1420    }
1421}
1422
1423impl ConsumerContext for GlueConsumerContext {}
1424
1425type DataOutput = AsyncOutputHandle<
1426    KafkaTimestamp,
1427    FueledBuilder<
1428        CapacityContainerBuilder<
1429            Vec<(
1430                (usize, Result<SourceMessage, DataflowError>),
1431                KafkaTimestamp,
1432                Diff,
1433            )>,
1434        >,
1435    >,
1436>;
1437type HealthOutput =
1438    AsyncOutputHandle<KafkaTimestamp, CapacityContainerBuilder<Vec<HealthStatusMessage>>>;
1439
1440/// The librdkafka default `fetch.max.bytes`, set explicitly because
1441/// [`RECEIVE_MESSAGE_MAX_BYTES_RANGE`] derives its minimum from it.
1442const FETCH_MAX_BYTES: usize = 52_428_800;
1443
1444/// The librdkafka default `queued.max.messages.kbytes`.
1445const QUEUED_MAX_MESSAGES_KBYTES: usize = 65_536;
1446
1447// NOTE: librdkafka caps `fetch.max.bytes` at `queued.max.messages.kbytes` only when
1448// `fetch.max.bytes` is unset, so that one fetch response fits in the pre-fetch queue. Setting
1449// `fetch.max.bytes` explicitly disables that cap, and this assertion takes its place.
1450const _: () = assert!(FETCH_MAX_BYTES <= QUEUED_MAX_MESSAGES_KBYTES * 1024);
1451
1452/// The `receive.message.max.bytes` values librdkafka accepts with [`FETCH_MAX_BYTES`]. The maximum
1453/// is librdkafka's `INT_MAX` bound on the property.
1454const RECEIVE_MESSAGE_MAX_BYTES_RANGE: RangeInclusive<usize> =
1455    FETCH_MAX_BYTES + 512..=2_147_483_647;
1456
1457/// The `fetch.message.max.bytes` values librdkafka accepts.
1458const FETCH_MESSAGE_MAX_BYTES_RANGE: RangeInclusive<usize> = 1..=1_000_000_000;
1459
1460/// Returns the value of `config` in `config_set`, clamped to `range`.
1461fn clamp_to_librdkafka_range(
1462    config: &Config<usize>,
1463    config_set: &ConfigSet,
1464    range: RangeInclusive<usize>,
1465) -> usize {
1466    // librdkafka rejects the client config outside the property's range, which would halt the
1467    // source.
1468    let configured = config.get(config_set);
1469    let (min, max) = range.into_inner();
1470    let clamped = configured.clamp(min, max);
1471    if clamped != configured {
1472        warn!(
1473            configured,
1474            clamped,
1475            "{} outside the range librdkafka accepts",
1476            config.name()
1477        );
1478    }
1479    clamped
1480}
1481
1482/// Creates a reader worker's consumer, possibly long after the operator started, and reports
1483/// failures to the operator's outputs.
1484struct ReaderConsumerSetup {
1485    config: RawSourceCreationConfig,
1486    connection: KafkaConnection,
1487    topic: String,
1488    topic_metadata_refresh_interval: Duration,
1489    group_id: String,
1490    client_id: String,
1491    notificator: Arc<Notify>,
1492    stats_tx: crossbeam_channel::Sender<Jsonb>,
1493    /// `(id, output_index)` of each source export.
1494    outputs: Vec<(GlobalId, usize)>,
1495    data_output: DataOutput,
1496    health_output: HealthOutput,
1497    health_cap: Capability<KafkaTimestamp>,
1498}
1499
1500impl ReaderConsumerSetup {
1501    /// Returns the consumer in `slot`, creating it first if needed.
1502    ///
1503    /// On creation, checks `start_offsets`, the start offsets of the partitions this worker is
1504    /// responsible for, against the topic's low watermarks, and adds the low watermark for
1505    /// responsible partitions without a start offset. Returns `Break` after emitting a definite
1506    /// error when a start offset has been compacted away, after which the reader must stop. Never
1507    /// returns if the consumer cannot be created.
1508    async fn get_or_create<'a>(
1509        &self,
1510        slot: &'a OnceCell<Arc<ReaderConsumer>>,
1511        start_offsets: &mut BTreeMap<PartitionId, u64>,
1512        data_cap: &Capability<KafkaTimestamp>,
1513    ) -> ControlFlow<(), &'a Arc<ReaderConsumer>> {
1514        if let Some(consumer) = slot.get() {
1515            return ControlFlow::Continue(consumer);
1516        }
1517        let consumer = match slot.get_or_try_init(|| self.create()).await {
1518            Ok(consumer) => consumer,
1519            Err(e) => {
1520                self.report_creation_failure(&e);
1521                // IMPORTANT: wedge forever until the `SuspendAndRestart` is processed.
1522                // Returning would incorrectly present to the remap operator as progress to the
1523                // empty frontier which would be incorrectly recorded to the remap shard.
1524                std::future::pending::<()>().await;
1525                unreachable!("pending future never returns");
1526            }
1527        };
1528        if mz_storage_types::dyncfgs::KAFKA_LOW_WATERMARK_CHECK.get(self.config.config.config_set())
1529        {
1530            self.check_low_watermarks(consumer, start_offsets, data_cap)
1531                .await?;
1532        }
1533        ControlFlow::Continue(consumer)
1534    }
1535
1536    async fn create(&self) -> Result<Arc<ReaderConsumer>, ContextCreationError> {
1537        let config_set = self.config.config.config_set();
1538        let consumer: ReaderConsumer = self
1539            .connection
1540            .create_with_context(
1541                &self.config.config,
1542                GlueConsumerContext {
1543                    notificator: Arc::clone(&self.notificator),
1544                    stats_tx: self.stats_tx.clone(),
1545                    inner: MzClientContext::default(),
1546                },
1547                &btreemap! {
1548                    // Disable Kafka auto commit. We manually commit offsets
1549                    // to Kafka once we have reclocked those offsets, so
1550                    // that users can use standard Kafka tools for progress
1551                    // tracking.
1552                    "enable.auto.commit" => "false".into(),
1553                    // Always begin ingest at 0 when restarted, even if Kafka
1554                    // contains committed consumer read offsets
1555                    "auto.offset.reset" => "earliest".into(),
1556                    // Use the user-configured topic metadata refresh
1557                    // interval.
1558                    "topic.metadata.refresh.interval.ms" =>
1559                        self.topic_metadata_refresh_interval
1560                        .as_millis()
1561                        .to_string(),
1562                    "fetch.message.max.bytes" => clamp_to_librdkafka_range(
1563                        &KAFKA_SOURCE_FETCH_MESSAGE_MAX_BYTES,
1564                        config_set,
1565                        FETCH_MESSAGE_MAX_BYTES_RANGE,
1566                    )
1567                    .to_string(),
1568                    "fetch.max.bytes" => FETCH_MAX_BYTES.to_string(),
1569                    "queued.max.messages.kbytes" => QUEUED_MAX_MESSAGES_KBYTES.to_string(),
1570                    "receive.message.max.bytes" => clamp_to_librdkafka_range(
1571                        &KAFKA_SOURCE_RECEIVE_MESSAGE_MAX_BYTES,
1572                        config_set,
1573                        RECEIVE_MESSAGE_MAX_BYTES_RANGE,
1574                    )
1575                    .to_string(),
1576                    // Consumer group ID, which may have been overridden by
1577                    // the user. librdkafka requires this, and we use offset
1578                    // committing to provide a way for users to monitor
1579                    // ingest progress, though we do not rely on the
1580                    // committed offsets for any functionality.
1581                    "group.id" => self.group_id.clone(),
1582                    // Allow Kafka monitoring tools to identify this
1583                    // consumer.
1584                    "client.id" => self.client_id.clone(),
1585                },
1586                InTask::Yes,
1587            )
1588            .await?;
1589        Ok(Arc::new(consumer))
1590    }
1591
1592    fn report_creation_failure(&self, e: &ContextCreationError) {
1593        let update = HealthStatusUpdate::halting(
1594            format!(
1595                "failed creating kafka reader consumer: {}",
1596                e.display_with_causes()
1597            ),
1598            None,
1599        );
1600        let namespace = if matches!(e, ContextCreationError::Ssh(_)) {
1601            StatusNamespace::Ssh
1602        } else {
1603            StatusNamespace::Kafka
1604        };
1605        self.report_health(namespace, update);
1606    }
1607
1608    /// Gives `update` for the source and each of its exports.
1609    fn report_health(&self, namespace: StatusNamespace, update: HealthStatusUpdate) {
1610        let ids = std::iter::once(None).chain(self.outputs.iter().map(|(id, _)| Some(*id)));
1611        for (id, update) in ids.repeat_clone(update) {
1612            self.health_output.give(
1613                &self.health_cap,
1614                HealthStatusMessage {
1615                    id,
1616                    namespace,
1617                    update,
1618                },
1619            );
1620        }
1621    }
1622
1623    /// Gives `error` to each export at the time of `data_cap`.
1624    async fn emit_definite_error(
1625        &self,
1626        data_cap: &Capability<KafkaTimestamp>,
1627        error: SourceErrorDetails,
1628    ) {
1629        let error: Result<SourceMessage, DataflowError> =
1630            Err(SourceError { error, hint: None }.into());
1631        let time = data_cap.time().clone();
1632        for (output, error) in self
1633            .outputs
1634            .iter()
1635            .map(|(_, output_index)| *output_index)
1636            .repeat_clone(error)
1637        {
1638            let update = ((output, error), time.clone(), Diff::ONE);
1639            let size = update.fuel_size();
1640            self.data_output.give_fueled(data_cap, update, size).await;
1641        }
1642    }
1643
1644    async fn check_low_watermarks(
1645        &self,
1646        consumer: &ReaderConsumer,
1647        start_offsets: &mut BTreeMap<PartitionId, u64>,
1648        data_cap: &Capability<KafkaTimestamp>,
1649    ) -> ControlFlow<()> {
1650        let config = &self.config;
1651        let topic = &self.topic;
1652        let low_watermarks = match fetch_partition_info(
1653            consumer,
1654            topic,
1655            config
1656                .config
1657                .parameters
1658                .kafka_timeout_config
1659                .fetch_metadata_timeout,
1660            Offset::Beginning, // fetch the low watermark
1661        ) {
1662            Ok(low_watermarks) => low_watermarks,
1663            Err(e) => {
1664                tracing::warn!(
1665                    source_id = config.id.to_string(),
1666                    worker_id = config.worker_id,
1667                    num_workers = config.worker_count,
1668                    "Failed to fetch watermarks for topic {topic}: {e}"
1669                );
1670                self.report_health(
1671                    StatusNamespace::Kafka,
1672                    HealthStatusUpdate::stalled(
1673                        format!("Failed to fetch watermarks for topic {topic}: {e}"),
1674                        None,
1675                    ),
1676                );
1677                let ssh_update = match consumer.client().context().tunnel_status() {
1678                    SshTunnelStatus::Running => HealthStatusUpdate::running(),
1679                    SshTunnelStatus::Errored(e) => HealthStatusUpdate::stalled(e, None),
1680                };
1681                self.report_health(StatusNamespace::Ssh, ssh_update);
1682                if let GetPartitionsError::TopicDoesNotExist = e {
1683                    // If the topic doesn't exist, that is a definite error
1684                    self.emit_definite_error(
1685                        data_cap,
1686                        SourceErrorDetails::Initialization(e.to_string().into()),
1687                    )
1688                    .await;
1689                }
1690                return ControlFlow::Continue(());
1691            }
1692        };
1693        for (pid, lwm) in &low_watermarks {
1694            if !responsible_for_pid(config, *pid) {
1695                continue;
1696            }
1697            // If a start offset exists for this partition, then either the user specified it
1698            // or we restored it from the resume upper. In either case, if the low watermark is
1699            // greater than the start offset, we know for certain that the offset we need to
1700            // start at has been compacted away or dropped from retention by Kafka. If there
1701            // is no start offset, then we set it to the low watermark and start consuming from
1702            // there, assuming the user doesn't care about the messages that have been compacted away.
1703            if let Some(start_offset) = start_offsets.get_mut(pid) {
1704                tracing::info!(
1705                    source_id = config.id.to_string(),
1706                    worker_id = config.worker_id,
1707                    num_workers = config.worker_count,
1708                    "restored offset {start_offset} for topic {topic} partition {pid} with low watermark {lwm}"
1709                );
1710                if lwm > start_offset {
1711                    tracing::error!(
1712                        source_id = config.id.to_string(),
1713                        worker_id = config.worker_id,
1714                        num_workers = config.worker_count,
1715                        "start offset and resume upper {start_offset} for topic {topic} \
1716                        partition {pid} is behind the low watermark {lwm}. This likely \
1717                        means that the offsets have been compacted away by Kafka."
1718                    );
1719                    let err_str = format!(
1720                        "Low watermark {lwm} of kafka topic {topic} partition {pid} \
1721                        is past the start offset/resume upper: {start_offset} \
1722                        This likely means that the offsets have been compacted away \
1723                        by Kafka. Please consider setting a higher start offset or \
1724                        adjusting your retention policies to prevent this.",
1725                    );
1726                    self.health_output.give(
1727                        &self.health_cap,
1728                        HealthStatusMessage {
1729                            id: None,
1730                            namespace: StatusNamespace::Kafka,
1731                            update: HealthStatusUpdate::stalled(err_str.clone(), None),
1732                        },
1733                    );
1734                    self.emit_definite_error(
1735                        data_cap,
1736                        SourceErrorDetails::Initialization(err_str.into()),
1737                    )
1738                    .await;
1739                    return ControlFlow::Break(());
1740                }
1741            } else {
1742                tracing::warn!(
1743                    source_id = config.id.to_string(),
1744                    worker_id = config.worker_id,
1745                    num_workers = config.worker_count,
1746                    "partition {pid} has a non-zero low watermark {lwm}, but no start offset or \
1747                    resume upper was found for this partition. Setting start offset to low watermark"
1748                );
1749                start_offsets.insert(*pid, *lwm);
1750            }
1751        }
1752        ControlFlow::Continue(())
1753    }
1754}
1755
1756#[cfg(test)]
1757mod tests {
1758    use std::sync::Arc;
1759    use std::time::Duration;
1760
1761    use mz_kafka_util::client::create_new_client_config_simple;
1762    use rdkafka::consumer::{BaseConsumer, Consumer};
1763    use rdkafka::{Message, Offset, TopicPartitionList};
1764    use uuid::Uuid;
1765
1766    use mz_dyncfg::{ConfigSet, ConfigUpdates};
1767    use mz_storage_types::dyncfgs::{
1768        KAFKA_SOURCE_FETCH_MESSAGE_MAX_BYTES, KAFKA_SOURCE_RECEIVE_MESSAGE_MAX_BYTES,
1769    };
1770
1771    use super::{
1772        FETCH_MAX_BYTES, FETCH_MESSAGE_MAX_BYTES_RANGE, QUEUED_MAX_MESSAGES_KBYTES,
1773        RECEIVE_MESSAGE_MAX_BYTES_RANGE, clamp_to_librdkafka_range,
1774    };
1775
1776    #[mz_ore::test]
1777    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function
1778    fn librdkafka_accepts_clamped_dyncfgs() {
1779        let config_set = ConfigSet::default()
1780            .add(&KAFKA_SOURCE_FETCH_MESSAGE_MAX_BYTES)
1781            .add(&KAFKA_SOURCE_RECEIVE_MESSAGE_MAX_BYTES);
1782        for configured in [0, usize::MAX] {
1783            let mut updates = ConfigUpdates::default();
1784            updates.add(&KAFKA_SOURCE_FETCH_MESSAGE_MAX_BYTES, configured);
1785            updates.add(&KAFKA_SOURCE_RECEIVE_MESSAGE_MAX_BYTES, configured);
1786            updates.apply(&config_set);
1787
1788            let mut config = create_new_client_config_simple();
1789            config.set(
1790                "fetch.message.max.bytes",
1791                clamp_to_librdkafka_range(
1792                    &KAFKA_SOURCE_FETCH_MESSAGE_MAX_BYTES,
1793                    &config_set,
1794                    FETCH_MESSAGE_MAX_BYTES_RANGE,
1795                )
1796                .to_string(),
1797            );
1798            config.set("fetch.max.bytes", FETCH_MAX_BYTES.to_string());
1799            config.set(
1800                "queued.max.messages.kbytes",
1801                QUEUED_MAX_MESSAGES_KBYTES.to_string(),
1802            );
1803            config.set(
1804                "receive.message.max.bytes",
1805                clamp_to_librdkafka_range(
1806                    &KAFKA_SOURCE_RECEIVE_MESSAGE_MAX_BYTES,
1807                    &config_set,
1808                    RECEIVE_MESSAGE_MAX_BYTES_RANGE,
1809                )
1810                .to_string(),
1811            );
1812            let _consumer: BaseConsumer<_> =
1813                mz_kafka_util::client::create(&config).unwrap_or_else(|e| {
1814                    panic!("librdkafka rejected the clamped value of {configured}: {e}")
1815                });
1816        }
1817    }
1818
1819    // Splitting off a partition queue with an `Offset` that is not `Offset::Beginning` seems to
1820    // lead to a race condition where sometimes we receive messages from polling the main consumer
1821    // instead of on the partition queue. This can be surfaced by running the test in a loop (in
1822    // the dataflow directory) using:
1823    //
1824    // cargo stress --lib --release source::kafka::tests::reproduce_kafka_queue_issue
1825    //
1826    // cargo-stress can be installed via `cargo install cargo-stress`
1827    //
1828    // You need to set up a topic "queue-test" with 1000 "hello" messages in it. Obviously, running
1829    // this test requires a running Kafka instance at localhost:9092.
1830    #[mz_ore::test]
1831    #[ignore]
1832    fn demonstrate_kafka_queue_race_condition() -> Result<(), anyhow::Error> {
1833        let topic_name = "queue-test";
1834        let pid = 0;
1835
1836        let mut kafka_config = create_new_client_config_simple();
1837        kafka_config.set("bootstrap.servers", "localhost:9092".to_string());
1838        kafka_config.set("enable.auto.commit", "false");
1839        kafka_config.set("group.id", Uuid::new_v4().to_string());
1840        kafka_config.set("fetch.message.max.bytes", "100");
1841        let consumer: BaseConsumer<_> = mz_kafka_util::client::create(&kafka_config)?;
1842
1843        let consumer = Arc::new(consumer);
1844
1845        let mut partition_list = TopicPartitionList::new();
1846        // Using Offset:Beginning here will work fine, only Offset:Offset(0) leads to the race
1847        // condition.
1848        partition_list.add_partition_offset(topic_name, pid, Offset::Offset(0))?;
1849
1850        consumer.assign(&partition_list)?;
1851
1852        let partition_queue = consumer
1853            .split_partition_queue(topic_name, pid)
1854            .expect("missing partition queue");
1855
1856        let expected_messages = 1_000;
1857
1858        let mut common_queue_count = 0;
1859        let mut partition_queue_count = 0;
1860
1861        loop {
1862            if let Some(msg) = consumer.poll(Duration::from_millis(0)) {
1863                match msg {
1864                    Ok(msg) => {
1865                        let _payload =
1866                            std::str::from_utf8(msg.payload().expect("missing payload"))?;
1867                        if partition_queue_count > 0 {
1868                            anyhow::bail!(
1869                                "Got message from common queue after we internally switched to partition queue."
1870                            );
1871                        }
1872
1873                        common_queue_count += 1;
1874                    }
1875                    Err(err) => anyhow::bail!("{}", err),
1876                }
1877            }
1878
1879            match partition_queue.poll(Duration::from_millis(0)) {
1880                Some(Ok(msg)) => {
1881                    let _payload = std::str::from_utf8(msg.payload().expect("missing payload"))?;
1882                    partition_queue_count += 1;
1883                }
1884                Some(Err(err)) => anyhow::bail!("{}", err),
1885                _ => (),
1886            }
1887
1888            if (common_queue_count + partition_queue_count) == expected_messages {
1889                break;
1890            }
1891        }
1892
1893        assert!(
1894            common_queue_count == 0,
1895            "Got {} out of {} messages from common queue. Partition queue: {}",
1896            common_queue_count,
1897            expected_messages,
1898            partition_queue_count
1899        );
1900
1901        Ok(())
1902    }
1903}
1904
1905/// Fetches the list of partitions and their corresponding high watermark.
1906fn fetch_partition_info<C: ConsumerContext>(
1907    consumer: &BaseConsumer<C>,
1908    topic: &str,
1909    fetch_timeout: Duration,
1910    offset_requested: Offset,
1911) -> Result<BTreeMap<PartitionId, PartitionWatermark>, GetPartitionsError> {
1912    let pids = get_partitions(consumer.client(), topic, fetch_timeout)?;
1913
1914    let mut offset_requests = TopicPartitionList::with_capacity(pids.len());
1915    for pid in pids {
1916        offset_requests.add_partition_offset(topic, pid, offset_requested)?;
1917    }
1918
1919    let offset_responses = consumer.offsets_for_times(offset_requests, fetch_timeout)?;
1920
1921    let mut result = BTreeMap::new();
1922    for entry in offset_responses.elements() {
1923        let offset = match entry.offset() {
1924            Offset::Offset(offset) => offset,
1925            offset => Err(anyhow!("unexpected high watermark offset: {offset:?}"))?,
1926        };
1927
1928        let pid = entry.partition();
1929        let watermark = offset.try_into().expect("invalid negative offset");
1930        result.insert(pid, watermark);
1931    }
1932
1933    Ok(result)
1934}
1935
1936/// An update produced by the metadata fetcher.
1937#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1938enum MetadataUpdate {
1939    /// The current IDs and high watermarks of all topic partitions.
1940    Partitions(BTreeMap<PartitionId, PartitionWatermark>),
1941    /// A transient error.
1942    ///
1943    /// Transient errors stall the source until their cause has been resolved.
1944    TransientError(HealthStatus),
1945    /// A definite error.
1946    ///
1947    /// Definite errors cannot be recovered from. They poison the source until the end of time.
1948    DefiniteError(SourceError),
1949}
1950
1951impl MetadataUpdate {
1952    /// Return the upstream frontier resulting from the metadata update, if any.
1953    fn upstream_frontier(&self) -> Option<Antichain<KafkaTimestamp>> {
1954        match self {
1955            Self::Partitions(partitions) => {
1956                let max_pid = partitions.keys().last().copied();
1957                let lower = max_pid
1958                    .map(RangeBound::after)
1959                    .unwrap_or(RangeBound::NegInfinity);
1960                let future_ts =
1961                    Partitioned::new_range(lower, RangeBound::PosInfinity, MzOffset::from(0));
1962
1963                let mut frontier = Antichain::from_elem(future_ts);
1964                for (pid, high_watermark) in partitions {
1965                    frontier.insert(Partitioned::new_singleton(
1966                        RangeBound::exact(*pid),
1967                        MzOffset::from(*high_watermark),
1968                    ));
1969                }
1970
1971                Some(frontier)
1972            }
1973            Self::DefiniteError(_) => Some(Antichain::new()),
1974            Self::TransientError(_) => None,
1975        }
1976    }
1977}
1978
1979#[derive(Debug, thiserror::Error)]
1980pub enum KafkaHeaderParseError {
1981    #[error("A header with key '{key}' was not found in the message headers")]
1982    KeyNotFound { key: String },
1983    #[error(
1984        "Found ill-formed byte sequence in header '{key}' that cannot be decoded as valid utf-8 (original bytes: {raw:x?})"
1985    )]
1986    Utf8Error { key: String, raw: Vec<u8> },
1987}
1988
1989/// Render the metadata fetcher of a Kafka source.
1990///
1991/// The metadata fetcher is a single-worker operator that is responsible for periodically fetching
1992/// the Kafka topic metadata (partition IDs and high watermarks) and making it available as a
1993/// Timely stream.
1994fn render_metadata_fetcher<'scope>(
1995    scope: Scope<'scope, KafkaTimestamp>,
1996    connection: KafkaSourceConnection,
1997    config: RawSourceCreationConfig,
1998) -> (
1999    StreamVec<'scope, KafkaTimestamp, (mz_repr::Timestamp, MetadataUpdate)>,
2000    StreamVec<'scope, KafkaTimestamp, Probe<KafkaTimestamp>>,
2001    PressOnDropButton,
2002) {
2003    let active_worker_id = usize::cast_from(config.id.hashed());
2004    let is_active_worker = active_worker_id % scope.peers() == scope.index();
2005
2006    let resume_upper = Antichain::from_iter(
2007        config
2008            .source_resume_uppers
2009            .values()
2010            .map(|uppers| uppers.iter().map(KafkaTimestamp::decode_row))
2011            .flatten(),
2012    );
2013
2014    let name = format!("KafkaMetadataFetcher({})", config.id);
2015    let mut builder = AsyncOperatorBuilder::new(name, scope.clone());
2016
2017    let (metadata_output, metadata_stream) =
2018        builder.new_output::<CapacityContainerBuilder<Vec<_>>>();
2019    let (probe_output, probe_stream) = builder.new_output::<CapacityContainerBuilder<Vec<_>>>();
2020
2021    let button = builder.build(move |caps| async move {
2022        if !is_active_worker {
2023            return;
2024        }
2025
2026        let [metadata_cap, probe_cap] = caps.try_into().unwrap();
2027
2028        let client_id = connection.client_id(
2029            config.config.config_set(),
2030            &config.config.connection_context,
2031            config.id,
2032        );
2033        let KafkaSourceConnection {
2034            connection,
2035            topic,
2036            topic_metadata_refresh_interval,
2037            ..
2038        } = connection;
2039
2040        let consumer: Result<BaseConsumer<_>, _> = connection
2041            .create_with_context(
2042                &config.config,
2043                MzClientContext::default(),
2044                &btreemap! {
2045                    // Use the user-configured topic metadata refresh
2046                    // interval.
2047                    "topic.metadata.refresh.interval.ms" =>
2048                        topic_metadata_refresh_interval
2049                        .as_millis()
2050                        .to_string(),
2051                    // Allow Kafka monitoring tools to identify this
2052                    // consumer.
2053                    "client.id" => format!("{client_id}-metadata"),
2054                },
2055                InTask::Yes,
2056            )
2057            .await;
2058
2059        let consumer = match consumer {
2060            Ok(consumer) => consumer,
2061            Err(e) => {
2062                let msg = format!(
2063                    "failed creating kafka metadata consumer: {}",
2064                    e.display_with_causes()
2065                );
2066                let status_update = HealthStatusUpdate::halting(msg, None);
2067                let status = match e {
2068                    ContextCreationError::Ssh(_) => HealthStatus::ssh(status_update),
2069                    _ => HealthStatus::kafka(status_update),
2070                };
2071                let error = MetadataUpdate::TransientError(status);
2072                let timestamp = (config.now_fn)().into();
2073                metadata_output.give(&metadata_cap, (timestamp, error));
2074
2075                // IMPORTANT: wedge forever until the `SuspendAndRestart` is processed.
2076                // Returning would incorrectly present to the remap operator as progress to the
2077                // empty frontier which would be incorrectly recorded to the remap shard.
2078                std::future::pending::<()>().await;
2079                unreachable!("pending future never returns");
2080            }
2081        };
2082
2083        let (tx, mut rx) = mpsc::unbounded_channel();
2084        spawn_metadata_thread(config, consumer, topic, tx);
2085
2086        let mut prev_upstream_frontier = resume_upper;
2087
2088        while let Some((timestamp, mut update)) = rx.recv().await {
2089            if prev_upstream_frontier.is_empty() {
2090                return;
2091            }
2092
2093            if let Some(upstream_frontier) = update.upstream_frontier() {
2094                // Topics are identified by name but it's possible that a user recreates a topic
2095                // with the same name. Ideally we'd want to catch all of these cases and
2096                // immediately error out the source, since the data is effectively gone.
2097                // Unfortunately this is not possible without something like KIP-516.
2098                //
2099                // The best we can do is check whether the upstream frontier regressed. This tells
2100                // us that the topic was recreated and now contains fewer offsets and/or fewer
2101                // partitions. Note that we are not able to detect topic recreation if neither of
2102                // the two are true.
2103                if !PartialOrder::less_equal(&prev_upstream_frontier, &upstream_frontier) {
2104                    let error = SourceError {
2105                        error: SourceErrorDetails::Other("topic was recreated".into()),
2106                        hint: None,
2107                    };
2108                    update = MetadataUpdate::DefiniteError(error);
2109                }
2110            }
2111
2112            if let Some(upstream_frontier) = update.upstream_frontier() {
2113                prev_upstream_frontier = upstream_frontier.clone();
2114
2115                let probe = Probe {
2116                    probe_ts: timestamp,
2117                    upstream_frontier,
2118                };
2119                probe_output.give(&probe_cap, probe);
2120            }
2121
2122            metadata_output.give(&metadata_cap, (timestamp, update));
2123        }
2124    });
2125
2126    (metadata_stream, probe_stream, button.press_on_drop())
2127}
2128
2129fn spawn_metadata_thread<C: ConsumerContext>(
2130    config: RawSourceCreationConfig,
2131    consumer: BaseConsumer<TunnelingClientContext<C>>,
2132    topic: String,
2133    tx: mpsc::UnboundedSender<(mz_repr::Timestamp, MetadataUpdate)>,
2134) {
2135    // Linux thread names are limited to 15 characters. Use a truncated ID to fit the name.
2136    thread::Builder::new()
2137        .name(format!("kfk-mtdt-{}", config.id))
2138        .spawn(move || {
2139            trace!(
2140                source_id = config.id.to_string(),
2141                worker_id = config.worker_id,
2142                num_workers = config.worker_count,
2143                "kafka metadata thread: starting..."
2144            );
2145
2146            let timestamp_interval = config.timestamp_interval;
2147            let mut ticker = probe::Ticker::new(move || timestamp_interval, config.now_fn);
2148
2149            loop {
2150                let probe_ts = ticker.tick_blocking();
2151                let result = fetch_partition_info(
2152                    &consumer,
2153                    &topic,
2154                    config
2155                        .config
2156                        .parameters
2157                        .kafka_timeout_config
2158                        .fetch_metadata_timeout,
2159                    Offset::End,
2160                );
2161                trace!(
2162                    source_id = config.id.to_string(),
2163                    worker_id = config.worker_id,
2164                    num_workers = config.worker_count,
2165                    "kafka metadata thread: metadata fetch result: {:?}",
2166                    result
2167                );
2168                let update = match result {
2169                    Ok(partitions) => {
2170                        trace!(
2171                            source_id = config.id.to_string(),
2172                            worker_id = config.worker_id,
2173                            num_workers = config.worker_count,
2174                            "kafka metadata thread: fetched partition metadata info",
2175                        );
2176
2177                        MetadataUpdate::Partitions(partitions)
2178                    }
2179                    Err(GetPartitionsError::TopicDoesNotExist) => {
2180                        let error = SourceError {
2181                            error: SourceErrorDetails::Other("topic was deleted".into()),
2182                            hint: None,
2183                        };
2184                        MetadataUpdate::DefiniteError(error)
2185                    }
2186                    Err(e) => {
2187                        let kafka_status = Some(HealthStatusUpdate::stalled(
2188                            format!("{}", e.display_with_causes()),
2189                            None,
2190                        ));
2191
2192                        let ssh_status = consumer.client().context().tunnel_status();
2193                        let ssh_status = match ssh_status {
2194                            SshTunnelStatus::Running => Some(HealthStatusUpdate::running()),
2195                            SshTunnelStatus::Errored(e) => {
2196                                Some(HealthStatusUpdate::stalled(e, None))
2197                            }
2198                        };
2199
2200                        MetadataUpdate::TransientError(HealthStatus {
2201                            kafka: kafka_status,
2202                            ssh: ssh_status,
2203                        })
2204                    }
2205                };
2206
2207                if tx.send((probe_ts, update)).is_err() {
2208                    break;
2209                }
2210            }
2211
2212            info!(
2213                source_id = config.id.to_string(),
2214                worker_id = config.worker_id,
2215                num_workers = config.worker_count,
2216                "kafka metadata thread: receiver has gone away; shutting down."
2217            )
2218        })
2219        .unwrap();
2220}