Skip to main content

nisshi_storage/service/
metadata.rs

1// Copyright ⓒ 2024-2025 Peter Morgan <peter.james.morgan@gmail.com>
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use nisshi_sans_io::{
16    ApiKey, ErrorCode, MetadataRequest, MetadataResponse, create_topics_request::CreatableTopic,
17};
18use rama::{Context, Service};
19use tracing::{debug, error, instrument};
20
21use crate::{Error, Result, Storage, TopicId};
22
23/// A [`Service`] using [`Storage`] as [`Context`] taking [`MetadataRequest`] returning [`MetadataRequest`].
24/// ```
25/// use rama::{Context, Layer as _, Service, layer::MapStateLayer};
26/// use nisshi_sans_io::MetadataRequest;
27/// use nisshi_storage::{Error, MetadataService, StorageContainer};
28/// use url::Url;
29///
30/// # #[tokio::main]
31/// # async fn main() -> Result<(), Error> {
32/// const HOST: &str = "localhost";
33/// const PORT: i32 = 9092;
34/// const NODE_ID: i32 = 111;
35///
36/// let storage = StorageContainer::builder()
37///     .cluster_id("nisshi")
38///     .node_id(NODE_ID)
39///     .advertised_listener(Url::parse(&format!("tcp://{HOST}:{PORT}"))?)
40///     .storage(Url::parse("memory://nisshi/")?)
41///     .build()
42///     .await?;
43///
44/// let service = MapStateLayer::new(|_| storage).into_layer(MetadataService);
45///
46/// let response = service
47///     .serve(
48///         Context::default(),
49///         MetadataRequest::default()
50///             .allow_auto_topic_creation(Some(false))
51///             .include_cluster_authorized_operations(Some(false))
52///             .include_topic_authorized_operations(Some(false))
53///             .topics(Some([].into())),
54///     )
55///     .await?;
56///
57/// let brokers = response.brokers.as_deref().unwrap_or_default();
58/// assert_eq!(1, brokers.len());
59/// assert_eq!(HOST, brokers[0].host);
60/// assert_eq!(PORT, brokers[0].port);
61/// assert_eq!(NODE_ID, brokers[0].node_id);
62/// assert!(brokers[0].rack.is_none());
63/// # Ok(())
64/// # }
65/// ```
66#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
67pub struct MetadataService;
68
69/// Defaults for topics created via auto creation: four partitions is the
70/// `num.partitions` that the Apache Kafka client test suites assume.
71const AUTO_CREATE_NUM_PARTITIONS: i32 = 4;
72const AUTO_CREATE_REPLICATION_FACTOR: i16 = 1;
73
74/// The Apache Kafka topic name rules: 1 to 249 characters from
75/// `[a-zA-Z0-9._-]`, and not "." or "..".
76fn is_valid_topic_name(name: &str) -> bool {
77    !name.is_empty()
78        && name != "."
79        && name != ".."
80        && name.len() <= 249
81        && name
82            .bytes()
83            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
84}
85
86impl ApiKey for MetadataService {
87    const KEY: i16 = MetadataRequest::KEY;
88}
89
90impl<G> Service<G, MetadataRequest> for MetadataService
91where
92    G: Storage,
93{
94    type Response = MetadataResponse;
95    type Error = Error;
96
97    #[instrument(skip(ctx, req))]
98    async fn serve(
99        &self,
100        ctx: Context<G>,
101        req: MetadataRequest,
102    ) -> Result<Self::Response, Self::Error> {
103        let topics = req
104            .topics
105            .map(|topics| topics.iter().map(TopicId::from).collect::<Vec<_>>());
106
107        let mut response = ctx
108            .state()
109            .metadata(topics.as_deref())
110            .await
111            .inspect_err(|err| error!(?err))?;
112
113        // versions prior to 4 do not have allow_auto_topic_creation,
114        // and behave as if it were true
115        if req.allow_auto_topic_creation.unwrap_or(true) {
116            let unknown = response
117                .topics()
118                .iter()
119                .filter(|topic| topic.error_code == i16::from(ErrorCode::UnknownTopicOrPartition))
120                .filter_map(|topic| topic.name.clone())
121                .filter(|name| is_valid_topic_name(name))
122                .collect::<Vec<_>>();
123
124            let mut created = false;
125
126            for name in unknown {
127                match ctx
128                    .state()
129                    .create_topic(
130                        CreatableTopic::default()
131                            .name(name)
132                            .num_partitions(AUTO_CREATE_NUM_PARTITIONS)
133                            .replication_factor(AUTO_CREATE_REPLICATION_FACTOR)
134                            .assignments(Some([].into()))
135                            .configs(Some([].into())),
136                        false,
137                    )
138                    .await
139                {
140                    Ok(topic_id) => {
141                        debug!(?topic_id);
142                        created = true;
143                    }
144
145                    // concurrent metadata requests can race to create
146                    Err(Error::Api(ErrorCode::TopicAlreadyExists)) => created = true,
147
148                    Err(err) => error!(?err),
149                }
150            }
151
152            if created {
153                response = ctx
154                    .state()
155                    .metadata(topics.as_deref())
156                    .await
157                    .inspect_err(|err| error!(?err))?;
158            }
159        }
160        let brokers = Some(response.brokers().to_owned());
161        let cluster_id = response.cluster().map(|s| s.into());
162        let controller_id = response.controller();
163        let topics = Some(
164            response
165                .topics()
166                .iter()
167                .map(|topic| {
168                    if topic.error_code == i16::from(ErrorCode::UnknownTopicOrPartition)
169                        && topic
170                            .name
171                            .as_deref()
172                            .is_some_and(|name| !is_valid_topic_name(name))
173                    {
174                        topic
175                            .clone()
176                            .error_code(ErrorCode::InvalidTopicException.into())
177                    } else {
178                        topic.clone()
179                    }
180                })
181                .collect::<Vec<_>>(),
182        );
183        let cluster_authorized_operations = Some(-1);
184
185        let throttle_time_ms = Some(0);
186
187        Ok(MetadataResponse::default()
188            .throttle_time_ms(throttle_time_ms)
189            .brokers(brokers)
190            .cluster_id(cluster_id)
191            .controller_id(controller_id)
192            .topics(topics)
193            .cluster_authorized_operations(cluster_authorized_operations))
194    }
195}