Skip to main content

kafka_client_engine/admin/
model.rs

1//! Engine-owned public request values translated once into deterministic policy facts.
2
3use kafka_client_core::{
4    CreateTopicConfig as CoreConfig, CreateTopicReplicaAssignment as CoreAssignment,
5    CreateTopicSpecification, CreateTopicsPlan, CreateTopicsPlanError,
6};
7
8/// One nullable topic configuration entry.
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct CreateTopicConfig {
11    name: String,
12    value: Option<String>,
13}
14
15impl CreateTopicConfig {
16    /// Creates a configuration entry.
17    pub fn new(name: impl Into<String>, value: Option<String>) -> Self {
18        Self {
19            name: name.into(),
20            value,
21        }
22    }
23}
24
25/// One generated-free manual partition placement.
26#[derive(Clone, Debug, Eq, PartialEq)]
27pub struct CreateTopicReplicaAssignment {
28    partition_index: i32,
29    broker_ids: Vec<i32>,
30}
31
32impl CreateTopicReplicaAssignment {
33    /// Creates one unvalidated caller-ordered placement entry.
34    pub const fn new(partition_index: i32, broker_ids: Vec<i32>) -> Self {
35        Self {
36            partition_index,
37            broker_ids,
38        }
39    }
40
41    fn into_core(self) -> CoreAssignment {
42        CoreAssignment::new(self.partition_index, self.broker_ids)
43    }
44}
45
46#[derive(Clone, Debug, Eq, PartialEq)]
47enum CreateTopicPlacement {
48    Automatic {
49        partitions: i32,
50        replication_factor: i16,
51    },
52    Manual {
53        assignments: Vec<CreateTopicReplicaAssignment>,
54        conflicting_replication_factor: Option<i16>,
55    },
56}
57
58/// One topic in a batched creation request.
59#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct CreateTopic {
61    name: String,
62    placement: CreateTopicPlacement,
63    configs: Vec<CreateTopicConfig>,
64}
65
66impl CreateTopic {
67    /// Creates a topic using Kafka's default replication factor.
68    pub fn new(name: impl Into<String>, partitions: i32) -> Self {
69        Self {
70            name: name.into(),
71            placement: CreateTopicPlacement::Automatic {
72                partitions,
73                replication_factor: -1,
74            },
75            configs: Vec::new(),
76        }
77    }
78
79    /// Creates a topic with exact manual replica assignments.
80    pub fn with_replica_assignments(
81        name: impl Into<String>,
82        assignments: Vec<CreateTopicReplicaAssignment>,
83        conflicting_replication_factor: Option<i16>,
84    ) -> Self {
85        Self {
86            name: name.into(),
87            placement: CreateTopicPlacement::Manual {
88                assignments,
89                conflicting_replication_factor,
90            },
91            configs: Vec::new(),
92        }
93    }
94
95    /// Sets an explicit replication factor.
96    #[must_use]
97    pub const fn with_replication_factor(mut self, replication_factor: i16) -> Self {
98        match &mut self.placement {
99            CreateTopicPlacement::Automatic {
100                replication_factor: requested,
101                ..
102            } => *requested = replication_factor,
103            CreateTopicPlacement::Manual {
104                conflicting_replication_factor,
105                ..
106            } => *conflicting_replication_factor = Some(replication_factor),
107        }
108        self
109    }
110
111    /// Appends one topic configuration.
112    #[must_use]
113    pub fn with_config(mut self, config: CreateTopicConfig) -> Self {
114        self.configs.push(config);
115        self
116    }
117}
118
119/// One ordered, batch-native `CreateTopics` request.
120#[derive(Clone, Debug, Eq, PartialEq)]
121pub struct CreateTopicsRequest {
122    topics: Vec<CreateTopic>,
123    validate_only: bool,
124}
125
126impl CreateTopicsRequest {
127    /// Creates one ordered batch.
128    pub fn new(topics: Vec<CreateTopic>) -> Self {
129        Self {
130            topics,
131            validate_only: false,
132        }
133    }
134
135    /// Selects broker-side validation without mutation.
136    #[must_use]
137    pub const fn with_validate_only(mut self, validate_only: bool) -> Self {
138        self.validate_only = validate_only;
139        self
140    }
141
142    pub(crate) fn into_plan(self) -> Result<CreateTopicsPlan, CreateTopicsPlanError> {
143        let topics = self
144            .topics
145            .into_iter()
146            .map(|topic| {
147                let configs = topic
148                    .configs
149                    .into_iter()
150                    .map(|config| CoreConfig::new(config.name, config.value))
151                    .collect();
152                match topic.placement {
153                    CreateTopicPlacement::Automatic {
154                        partitions,
155                        replication_factor,
156                    } => CreateTopicSpecification::new(
157                        topic.name,
158                        partitions,
159                        replication_factor,
160                        configs,
161                    ),
162                    CreateTopicPlacement::Manual {
163                        assignments,
164                        conflicting_replication_factor,
165                    } => CreateTopicSpecification::manual(
166                        topic.name,
167                        assignments
168                            .into_iter()
169                            .map(CreateTopicReplicaAssignment::into_core)
170                            .collect(),
171                        conflicting_replication_factor,
172                        configs,
173                    ),
174                }
175            })
176            .collect();
177        CreateTopicsPlan::new(topics, self.validate_only)
178    }
179
180    pub(crate) fn canonicalize(mut self) -> Self {
181        for topic in &mut self.topics {
182            topic.name = canonical_string(std::mem::take(&mut topic.name));
183            for config in &mut topic.configs {
184                config.name = canonical_string(std::mem::take(&mut config.name));
185                config.value = config.value.take().map(canonical_string);
186            }
187            topic.configs = canonical_vec(std::mem::take(&mut topic.configs));
188            if let CreateTopicPlacement::Manual { assignments, .. } = &mut topic.placement {
189                for assignment in assignments.iter_mut() {
190                    assignment.broker_ids =
191                        canonical_vec(std::mem::take(&mut assignment.broker_ids));
192                }
193                *assignments = canonical_vec(std::mem::take(assignments));
194            }
195        }
196        self.topics = canonical_vec(self.topics);
197        self
198    }
199
200    pub(crate) fn retained_charge(&self) -> Option<usize> {
201        let mut text_bytes = 0usize;
202        let mut config_count = 0usize;
203        let mut assignment_count = 0usize;
204        let mut broker_id_count = 0usize;
205        for topic in &self.topics {
206            text_bytes = text_bytes.checked_add(topic.name.len())?;
207            config_count = config_count.checked_add(topic.configs.len())?;
208            for config in &topic.configs {
209                text_bytes = text_bytes.checked_add(config.name.len())?;
210                text_bytes =
211                    text_bytes.checked_add(config.value.as_ref().map_or(0, String::len))?;
212            }
213            if let CreateTopicPlacement::Manual { assignments, .. } = &topic.placement {
214                assignment_count = assignment_count.checked_add(assignments.len())?;
215                for assignment in assignments {
216                    broker_id_count = broker_id_count.checked_add(assignment.broker_ids.len())?;
217                }
218            }
219        }
220        super::retention::request_with_assignments_charge(
221            self.topics.len(),
222            config_count,
223            assignment_count,
224            broker_id_count,
225            text_bytes,
226        )
227    }
228
229    #[cfg(test)]
230    pub(super) fn storage_is_canonical(&self) -> bool {
231        self.topics.capacity() == self.topics.len()
232            && self.topics.iter().all(|topic| {
233                topic.name.capacity() == topic.name.len()
234                    && topic.configs.capacity() == topic.configs.len()
235                    && match &topic.placement {
236                        CreateTopicPlacement::Automatic { .. } => true,
237                        CreateTopicPlacement::Manual { assignments, .. } => {
238                            assignments.capacity() == assignments.len()
239                                && assignments.iter().all(|assignment| {
240                                    assignment.broker_ids.capacity() == assignment.broker_ids.len()
241                                })
242                        }
243                    }
244                    && topic.configs.iter().all(|config| {
245                        config.name.capacity() == config.name.len()
246                            && config
247                                .value
248                                .as_ref()
249                                .is_none_or(|value| value.capacity() == value.len())
250                    })
251            })
252    }
253}
254
255fn canonical_string(value: String) -> String {
256    value.into_boxed_str().into_string()
257}
258
259fn canonical_vec<T>(value: Vec<T>) -> Vec<T> {
260    value.into_boxed_slice().into_vec()
261}