1use std::collections::BTreeMap;
11use std::time::Duration;
12
13use anyhow::{Context, anyhow, bail};
14use mz_aws_glue_schema_registry::{
15 Client as GlueClient, Compatibility as GlueCompatibility, CreateSchemaError, DataFormat,
16 GetSchemaByDefinitionError, GetSchemaVersionError, RegisterSchemaVersionError,
17 RegisteredSchemaVersion, SchemaVersionLifecycleStatus,
18};
19use mz_ccsr::GetSubjectConfigError;
20use mz_kafka_util::admin::EnsureTopicConfig;
21use mz_kafka_util::client::MzClientContext;
22use mz_ore::collections::CollectionExt;
23use mz_ore::future::{InTask, OreFutureExt};
24use mz_ore::retry::{Retry, RetryResult};
25use mz_storage_types::configuration::StorageConfiguration;
26use mz_storage_types::connections::KafkaTopicOptions;
27use mz_storage_types::errors::ContextCreationErrorExt;
28use mz_storage_types::sinks::KafkaSinkConnection;
29use rdkafka::ClientContext;
30use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, ResourceSpecifier, TopicReplication};
31use tracing::warn;
32use uuid::Uuid;
33
34pub mod progress_key {
35 use std::fmt;
36
37 use mz_repr::GlobalId;
38 use rdkafka::message::ToBytes;
39
40 #[derive(Debug, Clone)]
42 pub struct ProgressKey(String);
43
44 impl ProgressKey {
45 pub fn new(sink_id: GlobalId) -> ProgressKey {
47 ProgressKey(format!("mz-sink-{sink_id}"))
48 }
49 }
50
51 impl ToBytes for ProgressKey {
52 fn to_bytes(&self) -> &[u8] {
53 self.0.as_bytes()
54 }
55 }
56
57 impl fmt::Display for ProgressKey {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59 self.0.fmt(f)
60 }
61 }
62}
63
64struct TopicConfigs {
65 partition_count: i32,
66 replication_factor: i32,
67}
68
69async fn discover_topic_configs<C: ClientContext>(
70 client: &AdminClient<C>,
71 topic: &str,
72 fetch_timeout: Duration,
73) -> Result<TopicConfigs, anyhow::Error> {
74 let mut partition_count = -1;
75 let mut replication_factor = -1;
76
77 let metadata = client
78 .inner()
79 .fetch_metadata(None, fetch_timeout)
80 .with_context(|| {
81 format!(
82 "error fetching metadata when creating new topic {} for sink",
83 topic
84 )
85 })?;
86
87 if metadata.brokers().len() == 0 {
88 Err(anyhow!("zero brokers discovered in metadata request"))?;
89 }
90
91 let broker = metadata.brokers()[0].id();
92 let configs = client
93 .describe_configs(
94 &[ResourceSpecifier::Broker(broker)],
95 &AdminOptions::new().request_timeout(Some(Duration::from_secs(5))),
96 )
97 .await
98 .with_context(|| {
99 format!(
100 "error fetching configuration from broker {} when creating new topic {} for sink",
101 broker, topic
102 )
103 })?;
104
105 if configs.len() != 1 {
106 Err(anyhow!(
107 "error creating topic {} for sink: broker {} returned {} config results, but one was expected",
108 topic,
109 broker,
110 configs.len()
111 ))?;
112 }
113
114 let config = configs.into_element().map_err(|e| {
115 anyhow!(
116 "error reading broker configuration when creating topic {} for sink: {}",
117 topic,
118 e
119 )
120 })?;
121
122 if config.entries.is_empty() {
123 bail!("read empty cluster configuration; do we have DescribeConfigs permissions?")
124 }
125
126 for entry in config.entries {
127 if entry.name == "num.partitions" && partition_count == -1 {
128 if let Some(s) = entry.value {
129 partition_count = s.parse::<i32>().with_context(|| {
130 format!(
131 "default partition count {} cannot be parsed into an integer",
132 s
133 )
134 })?;
135 }
136 } else if entry.name == "default.replication.factor" && replication_factor == -1 {
137 if let Some(s) = entry.value {
138 replication_factor = s.parse::<i32>().with_context(|| {
139 format!(
140 "default replication factor {} cannot be parsed into an integer",
141 s
142 )
143 })?;
144 }
145 }
146 }
147
148 Ok(TopicConfigs {
149 partition_count,
150 replication_factor,
151 })
152}
153
154pub async fn ensure_kafka_topic(
162 connection: &KafkaSinkConnection,
163 storage_configuration: &StorageConfiguration,
164 topic: &str,
165 KafkaTopicOptions {
166 partition_count,
167 replication_factor,
168 topic_config,
169 }: &KafkaTopicOptions,
170 ensure_topic_config: EnsureTopicConfig,
171) -> Result<bool, anyhow::Error> {
172 let client: AdminClient<_> = connection
173 .connection
174 .create_with_context(
175 storage_configuration,
176 MzClientContext::default(),
177 &BTreeMap::new(),
178 InTask::Yes,
180 )
181 .await
182 .add_context("creating admin client failed")?;
183 let mut partition_count = partition_count.map(|f| *f);
184 let mut replication_factor = replication_factor.map(|f| *f);
185 if partition_count.is_none() || replication_factor.is_none() {
190 let fetch_timeout = storage_configuration
191 .parameters
192 .kafka_timeout_config
193 .fetch_metadata_timeout;
194 match discover_topic_configs(&client, topic, fetch_timeout).await {
195 Ok(configs) => {
196 if partition_count.is_none() {
197 partition_count = Some(configs.partition_count);
198 }
199 if replication_factor.is_none() {
200 replication_factor = Some(configs.replication_factor);
201 }
202 }
203 Err(e) => {
204 warn!("Failed to discover default values for topic configs: {e}");
207 if partition_count.is_none() {
208 partition_count = Some(-1);
209 }
210 if replication_factor.is_none() {
211 replication_factor = Some(-1);
212 }
213 }
214 };
215 }
216
217 let mut kafka_topic = NewTopic::new(
218 topic,
219 partition_count.expect("always set above"),
220 TopicReplication::Fixed(replication_factor.expect("always set above")),
221 );
222
223 for (key, value) in topic_config {
224 kafka_topic = kafka_topic.set(key, value);
225 }
226
227 mz_kafka_util::admin::ensure_topic(
228 &client,
229 &AdminOptions::new().request_timeout(Some(Duration::from_secs(5))),
230 &kafka_topic,
231 ensure_topic_config,
232 )
233 .await
234 .with_context(|| format!("Error creating topic {} for sink", topic))
235}
236
237pub async fn publish_kafka_schema(
243 ccsr: mz_ccsr::Client,
244 subject: String,
245 schema: String,
246 schema_type: mz_ccsr::SchemaType,
247 compatibility_level: Option<mz_ccsr::CompatibilityLevel>,
248) -> Result<i32, anyhow::Error> {
249 if let Some(compatibility_level) = compatibility_level {
250 let ccsr = ccsr.clone();
251 let subject = subject.clone();
252 async move {
253 match ccsr.get_subject_config(&subject).await {
255 Ok(config) => {
256 if config.compatibility_level != compatibility_level {
257 tracing::debug!(
258 "compatibility level '{}' does not match intended '{}'",
259 config.compatibility_level,
260 compatibility_level
261 );
262 }
263 Ok(())
264 }
265 Err(GetSubjectConfigError::SubjectCompatibilityLevelNotSet)
266 | Err(GetSubjectConfigError::SubjectNotFound) => ccsr
267 .set_subject_compatibility_level(&subject, compatibility_level)
268 .await
269 .map_err(anyhow::Error::from),
270 Err(e) => Err(e.into()),
271 }
272 }
273 .run_in_task(|| "set_compatibility_level".to_string())
274 .await
275 .context("unable to update schema compatibility level in kafka sink")?;
276 }
277
278 let schema_id = async move {
279 ccsr.publish_schema(&subject, &schema, schema_type, &[])
280 .await
281 }
282 .run_in_task(|| "publish_kafka_schema".to_string())
283 .await
284 .context("unable to publish schema to registry in kafka sink")?;
285
286 Ok(schema_id)
287}
288
289pub fn glue_compatibility_from_csr(level: mz_ccsr::CompatibilityLevel) -> GlueCompatibility {
297 match level {
298 mz_ccsr::CompatibilityLevel::Backward => GlueCompatibility::Backward,
299 mz_ccsr::CompatibilityLevel::BackwardTransitive => GlueCompatibility::BackwardAll,
300 mz_ccsr::CompatibilityLevel::Forward => GlueCompatibility::Forward,
301 mz_ccsr::CompatibilityLevel::ForwardTransitive => GlueCompatibility::ForwardAll,
302 mz_ccsr::CompatibilityLevel::Full => GlueCompatibility::Full,
303 mz_ccsr::CompatibilityLevel::FullTransitive => GlueCompatibility::FullAll,
304 mz_ccsr::CompatibilityLevel::None => GlueCompatibility::None,
305 }
306}
307
308pub async fn publish_glue_schema(
319 client: GlueClient,
320 registry_name: String,
321 schema_name: String,
322 schema: String,
323 compatibility: Option<GlueCompatibility>,
324) -> Result<Uuid, anyhow::Error> {
325 async move {
326 match client
328 .get_schema_by_definition(®istry_name, &schema_name, &schema)
329 .await
330 {
331 Ok(RegisteredSchemaVersion {
336 lifecycle_status:
337 Some(
338 SchemaVersionLifecycleStatus::Failure
339 | SchemaVersionLifecycleStatus::Deleting,
340 ),
341 ..
342 }) => {}
343 Ok(registered) => {
344 warn_on_glue_compatibility_mismatch(
345 &client,
346 ®istry_name,
347 &schema_name,
348 compatibility.as_ref(),
349 )
350 .await;
351 return await_glue_schema_version_available(&client, registered).await;
352 }
353 Err(GetSchemaByDefinitionError::NotFound) => {}
354 Err(e) => return Err(e).context("looking up Glue schema by definition"),
355 }
356
357 let registered = match client
359 .register_schema_version(®istry_name, &schema_name, &schema)
360 .await
361 {
362 Ok(registered) => {
363 warn_on_glue_compatibility_mismatch(
364 &client,
365 ®istry_name,
366 &schema_name,
367 compatibility.as_ref(),
368 )
369 .await;
370 registered
371 }
372 Err(RegisterSchemaVersionError::SchemaNotFound) => {
373 let compatibility = compatibility.unwrap_or(GlueCompatibility::Backward);
375 match client
376 .create_schema(
377 ®istry_name,
378 &schema_name,
379 DataFormat::Avro,
380 compatibility,
381 &schema,
382 )
383 .await
384 {
385 Ok(registered) => registered,
386 Err(CreateSchemaError::AlreadyExists) => client
389 .register_schema_version(®istry_name, &schema_name, &schema)
390 .await
391 .context("registering Glue schema version after create race")?,
392 Err(e) => return Err(e).context("creating Glue schema"),
393 }
394 }
395 Err(e) => return Err(e).context("registering Glue schema version"),
396 };
397 await_glue_schema_version_available(&client, registered).await
398 }
399 .run_in_task(|| "publish_glue_schema".to_string())
400 .await
401 .context("unable to publish schema to registry in kafka sink")
402}
403
404#[derive(Debug, thiserror::Error)]
406#[error("Glue schema version {version_id} failed its compatibility check")]
407pub struct GlueSchemaIncompatibleError {
408 pub version_id: Uuid,
409}
410
411async fn await_glue_schema_version_available(
421 client: &GlueClient,
422 registered: RegisteredSchemaVersion,
423) -> Result<Uuid, anyhow::Error> {
424 let id = registered.id;
425 let mut write_status = registered.lifecycle_status;
428
429 Retry::default()
431 .initial_backoff(Duration::from_millis(200))
432 .clamp_backoff(Duration::from_secs(2))
433 .max_duration(Duration::from_secs(30))
434 .retry_async(|_| {
435 let known = write_status.take();
436 async move {
437 let status = match known {
438 Some(status) => Some(status),
439 None => match client.get_schema_version_by_id(id).await {
440 Ok(version) => version.lifecycle_status,
441 Err(GetSchemaVersionError::NotFound) => {
442 return RetryResult::FatalErr(anyhow!(
443 "Glue schema version {id} disappeared while waiting for it \
444 to become available"
445 ));
446 }
447 Err(e) => {
448 return RetryResult::RetryableErr(
449 anyhow::Error::new(e)
450 .context(format!("polling status of Glue schema version {id}")),
451 );
452 }
453 },
454 };
455 match status {
456 Some(SchemaVersionLifecycleStatus::Available) => RetryResult::Ok(id),
457 Some(SchemaVersionLifecycleStatus::Failure) => {
458 RetryResult::FatalErr(GlueSchemaIncompatibleError { version_id: id }.into())
459 }
460 Some(SchemaVersionLifecycleStatus::Deleting) => {
461 RetryResult::FatalErr(anyhow!("Glue schema version {id} is being deleted"))
462 }
463 status @ (Some(
464 SchemaVersionLifecycleStatus::Pending
465 | SchemaVersionLifecycleStatus::Unknown(_),
466 )
467 | None) => RetryResult::RetryableErr(anyhow!(
468 "Glue schema version {id} is not yet available (status: {status:?})"
469 )),
470 }
471 }
472 })
473 .await
474}
475
476async fn warn_on_glue_compatibility_mismatch(
482 client: &GlueClient,
483 registry_name: &str,
484 schema_name: &str,
485 desired: Option<&GlueCompatibility>,
486) {
487 let Some(desired) = desired else { return };
488 match client.get_schema(registry_name, schema_name).await {
489 Ok(schema) => {
490 if schema.compatibility.as_ref() != Some(desired) {
491 warn!(
492 "Glue schema {schema_name:?} has compatibility {:?}, which does not match \
493 the intended {desired:?}; leaving it unchanged",
494 schema.compatibility
495 );
496 }
497 }
498 Err(e) => warn!(
499 "unable to read Glue schema {schema_name:?} compatibility to check for a mismatch: {e}"
500 ),
501 }
502}
503
504#[cfg(test)]
505mod tests {
506 use aws_sdk_glue::operation::get_schema_by_definition::{
507 GetSchemaByDefinitionError as SdkGetSchemaByDefinitionError, GetSchemaByDefinitionOutput,
508 };
509 use aws_sdk_glue::operation::get_schema_version::GetSchemaVersionOutput;
510 use aws_sdk_glue::operation::register_schema_version::RegisterSchemaVersionOutput;
511 use aws_sdk_glue::types::SchemaVersionStatus;
512 use aws_sdk_glue::types::error::EntityNotFoundException;
513 use aws_smithy_mocks::{Rule, RuleMode, mock, mock_client};
514
515 use super::*;
516
517 const PUBLISHED_ID: &str = "12345678-1234-5678-1234-567812345678";
518 const REUSED_ID: &str = "87654321-4321-8765-4321-876543218765";
519
520 fn glue_client(rules: &[&Rule]) -> GlueClient {
523 GlueClient::from_sdk_client(mock_client!(aws_sdk_glue, RuleMode::MatchAny, rules))
524 }
525
526 async fn publish(client: GlueClient) -> Result<Uuid, anyhow::Error> {
527 publish_glue_schema(
528 client,
529 "registry".to_string(),
530 "schema".to_string(),
531 "{}".to_string(),
532 None,
533 )
534 .await
535 }
536
537 fn definition_not_found() -> Rule {
538 mock!(aws_sdk_glue::Client::get_schema_by_definition).then_error(|| {
539 SdkGetSchemaByDefinitionError::EntityNotFoundException(
540 EntityNotFoundException::builder().build(),
541 )
542 })
543 }
544
545 fn register_returns(status: SchemaVersionStatus) -> Rule {
546 mock!(aws_sdk_glue::Client::register_schema_version).then_output(move || {
547 RegisterSchemaVersionOutput::builder()
548 .schema_version_id(PUBLISHED_ID)
549 .status(status.clone())
550 .build()
551 })
552 }
553
554 #[mz_ore::test(tokio::test)]
557 #[cfg_attr(miri, ignore)] async fn publish_glue_schema_waits_for_pending_version() {
559 let lookup = definition_not_found();
560 let register = register_returns(SchemaVersionStatus::Pending);
561 let poll = mock!(aws_sdk_glue::Client::get_schema_version)
562 .sequence()
563 .output(|| {
564 GetSchemaVersionOutput::builder()
565 .schema_version_id(PUBLISHED_ID)
566 .status(SchemaVersionStatus::Pending)
567 .build()
568 })
569 .output(|| {
570 GetSchemaVersionOutput::builder()
571 .schema_version_id(PUBLISHED_ID)
572 .status(SchemaVersionStatus::Available)
573 .build()
574 })
575 .build();
576
577 let id = publish(glue_client(&[&lookup, ®ister, &poll]))
578 .await
579 .expect("pending version becomes available");
580 assert_eq!(id.to_string(), PUBLISHED_ID);
581 assert_eq!(poll.num_calls(), 2);
582 }
583
584 #[mz_ore::test(tokio::test)]
587 #[cfg_attr(miri, ignore)] async fn publish_glue_schema_errors_on_failed_compatibility_check() {
589 let lookup = definition_not_found();
590 let register = register_returns(SchemaVersionStatus::Pending);
591 let poll = mock!(aws_sdk_glue::Client::get_schema_version).then_output(|| {
592 GetSchemaVersionOutput::builder()
593 .schema_version_id(PUBLISHED_ID)
594 .status(SchemaVersionStatus::Failure)
595 .build()
596 });
597
598 let err = publish(glue_client(&[&lookup, ®ister, &poll]))
599 .await
600 .expect_err("failed version must not publish");
601 assert!(
602 format!("{err:#}").contains("failed its compatibility check"),
603 "unexpected error: {err:#}"
604 );
605 assert!(
606 err.is::<GlueSchemaIncompatibleError>(),
607 "error lost its type: {err:#}"
608 );
609 }
610
611 #[mz_ore::test(tokio::test)]
614 #[cfg_attr(miri, ignore)] async fn publish_glue_schema_reuses_available_definition_match() {
616 let lookup = mock!(aws_sdk_glue::Client::get_schema_by_definition).then_output(|| {
617 GetSchemaByDefinitionOutput::builder()
618 .schema_version_id(REUSED_ID)
619 .status(SchemaVersionStatus::Available)
620 .build()
621 });
622
623 let id = publish(glue_client(&[&lookup]))
624 .await
625 .expect("available version is reused");
626 assert_eq!(id.to_string(), REUSED_ID);
627 }
628
629 #[mz_ore::test(tokio::test)]
632 #[cfg_attr(miri, ignore)] async fn publish_glue_schema_skips_failed_definition_match() {
634 let lookup = mock!(aws_sdk_glue::Client::get_schema_by_definition).then_output(|| {
635 GetSchemaByDefinitionOutput::builder()
636 .schema_version_id(REUSED_ID)
637 .status(SchemaVersionStatus::Failure)
638 .build()
639 });
640 let register = register_returns(SchemaVersionStatus::Available);
641
642 let id = publish(glue_client(&[&lookup, ®ister]))
643 .await
644 .expect("failed match falls through to registration");
645 assert_eq!(id.to_string(), PUBLISHED_ID);
646 assert_eq!(register.num_calls(), 1);
647 }
648
649 #[mz_ore::test]
650 fn glue_compatibility_mapping_is_total() {
651 use mz_ccsr::CompatibilityLevel::*;
654 let cases = [
655 (Backward, GlueCompatibility::Backward),
656 (BackwardTransitive, GlueCompatibility::BackwardAll),
657 (Forward, GlueCompatibility::Forward),
658 (ForwardTransitive, GlueCompatibility::ForwardAll),
659 (Full, GlueCompatibility::Full),
660 (FullTransitive, GlueCompatibility::FullAll),
661 (None, GlueCompatibility::None),
662 ];
663 for (csr, glue) in cases {
664 assert_eq!(glue_compatibility_from_csr(csr), glue);
665 }
666 }
667}