Skip to main content

tansu_storage/service/
incremental_alter_configs.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 rama::{Context, Service};
16use tansu_sans_io::{ApiKey, IncrementalAlterConfigsRequest, IncrementalAlterConfigsResponse};
17use tracing::instrument;
18
19use crate::{Error, Result, Storage};
20
21/// A [`Service`] using [`Storage`] as [`Context`] taking [`IncrementalAlterConfigsRequest`] returning [`IncrementalAlterConfigsResponse`].
22/// ```
23/// use rama::{Context, Layer as _, Service, layer::MapStateLayer};
24/// use tansu_sans_io::{
25///     ConfigResource, CreateTopicsRequest, DescribeConfigsRequest, ErrorCode,
26///     IncrementalAlterConfigsRequest, OpType,
27///     create_topics_request::CreatableTopic,
28///     describe_configs_request::DescribeConfigsResource,
29///     incremental_alter_configs_request::{AlterConfigsResource, AlterableConfig},
30/// };
31/// use tansu_storage::{
32///     CreateTopicsService, DescribeConfigsService, Error,
33///     IncrementalAlterConfigsService, StorageContainer,
34/// };
35/// use url::Url;
36///
37/// # #[tokio::main]
38/// # async fn main() -> Result<(), Error> {
39/// const HOST: &str = "localhost";
40/// const PORT: i32 = 9092;
41/// const NODE_ID: i32 = 111;
42///
43/// let storage = StorageContainer::builder()
44///     .cluster_id("tansu")
45///     .node_id(NODE_ID)
46///     .advertised_listener(Url::parse(&format!("tcp://{HOST}:{PORT}"))?)
47///     .storage(Url::parse("memory://tansu/")?)
48///     .build()
49///     .await?;
50///
51/// let resource_name = "abcba";
52///
53/// let create_topic = {
54///     let storage = storage.clone();
55///     MapStateLayer::new(|_| storage).into_layer(CreateTopicsService)
56/// };
57///
58/// let response = create_topic
59///     .serve(
60///         Context::default(),
61///         CreateTopicsRequest::default().topics(Some(
62///             [CreatableTopic::default()
63///                 .name(resource_name.into())
64///                 .num_partitions(3)
65///                 .replication_factor(1)]
66///             .into(),
67///         )),
68///     )
69///     .await?;
70///
71/// assert_eq!(
72///     ErrorCode::None,
73///     ErrorCode::try_from(response.topics.unwrap_or_default()[0].error_code)?
74/// );
75///
76/// let config_name = "x.y.z";
77/// let config_value = "pqr";
78///
79/// let describe_configs = {
80///     let storage = storage.clone();
81///     MapStateLayer::new(|_| storage).into_layer(DescribeConfigsService)
82/// };
83///
84/// let response = describe_configs
85///     .serve(
86///         Context::default(),
87///         DescribeConfigsRequest::default()
88///             .include_documentation(Some(false))
89///             .include_synonyms(Some(false))
90///             .resources(Some(
91///                 [DescribeConfigsResource::default()
92///                     .resource_name(resource_name.into())
93///                     .resource_type(ConfigResource::Topic.into())
94///                     .configuration_keys(Some([config_name.into()].into()))]
95///                 .into(),
96///             )),
97///     )
98///     .await?;
99///
100/// assert!(response.results.unwrap_or_default()[0].configs.is_none());
101///
102/// let alter_configs = {
103///     let storage = storage.clone();
104///     MapStateLayer::new(|_| storage).into_layer(IncrementalAlterConfigsService)
105/// };
106///
107/// let _response = alter_configs
108///     .serve(
109///         Context::default(),
110///         IncrementalAlterConfigsRequest::default().resources(Some(
111///             [AlterConfigsResource::default()
112///                 .resource_name(resource_name.into())
113///                 .resource_type(ConfigResource::Topic.into())
114///                 .configs(Some(
115///                     [AlterableConfig::default()
116///                         .config_operation(OpType::Set.into())
117///                         .name(config_name.into())
118///                         .value(Some(config_value.into()))]
119///                     .into(),
120///                 ))]
121///             .into(),
122///         )),
123///     )
124///     .await?;
125///
126/// let response = describe_configs
127///     .serve(
128///         Context::default(),
129///         DescribeConfigsRequest::default()
130///             .include_documentation(Some(false))
131///             .include_synonyms(Some(false))
132///             .resources(Some(
133///                 [DescribeConfigsResource::default()
134///                     .resource_name(resource_name.into())
135///                     .resource_type(ConfigResource::Topic.into())
136///                     .configuration_keys(Some([config_name.into()].into()))]
137///                 .into(),
138///             )),
139///     )
140///     .await?;
141///
142/// let results = response.results.as_deref().unwrap_or(&[]);
143/// assert_eq!(1, results.len());
144/// assert_eq!(resource_name, results[0].resource_name.as_str());
145///
146/// let configs = results[0].configs.as_deref().unwrap_or(&[]);
147/// assert_eq!(1, configs.len());
148/// assert_eq!(Some(config_value), configs[0].value.as_deref());
149/// # Ok(())
150/// # }
151/// ```
152#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
153pub struct IncrementalAlterConfigsService;
154
155impl ApiKey for IncrementalAlterConfigsService {
156    const KEY: i16 = IncrementalAlterConfigsRequest::KEY;
157}
158
159impl<G> Service<G, IncrementalAlterConfigsRequest> for IncrementalAlterConfigsService
160where
161    G: Storage,
162{
163    type Response = IncrementalAlterConfigsResponse;
164    type Error = Error;
165
166    #[instrument(skip(ctx, req))]
167    async fn serve(
168        &self,
169        ctx: Context<G>,
170        req: IncrementalAlterConfigsRequest,
171    ) -> Result<Self::Response, Self::Error> {
172        let mut responses = vec![];
173
174        for resource in req.resources.unwrap_or_default() {
175            responses.push(ctx.state().incremental_alter_resource(resource).await?);
176        }
177
178        Ok(IncrementalAlterConfigsResponse::default()
179            .throttle_time_ms(0)
180            .responses(Some(responses)))
181    }
182}