tansu_storage/service/list_groups.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, ErrorCode, ListGroupsRequest, ListGroupsResponse};
17use tracing::instrument;
18
19use crate::{Error, Result, Storage};
20
21/// A [`Service`] using [`Storage`] as [`Context`] taking [`ListGroupsRequest`] returning [`ListGroupsResponse`].
22/// ```
23/// use rama::{Context, Layer as _, Service, layer::MapStateLayer};
24/// use tansu_sans_io::{ErrorCode, ListGroupsRequest};
25/// use tansu_storage::{Error, ListGroupsService, StorageContainer};
26/// use url::Url;
27///
28/// # #[tokio::main]
29/// # async fn main() -> Result<(), Error> {
30/// const HOST: &str = "localhost";
31/// const PORT: i32 = 9092;
32/// const NODE_ID: i32 = 111;
33///
34/// let storage = StorageContainer::builder()
35/// .cluster_id("tansu")
36/// .node_id(NODE_ID)
37/// .advertised_listener(Url::parse(&format!("tcp://{HOST}:{PORT}"))?)
38/// .storage(Url::parse("memory://tansu/")?)
39/// .build()
40/// .await?;
41///
42/// let service = MapStateLayer::new(|_| storage).into_layer(ListGroupsService);
43///
44/// let response = service
45/// .serve(
46/// Context::default(),
47/// ListGroupsRequest::default().states_filter(Some(["Empty".into()].into())),
48/// )
49/// .await?;
50///
51/// assert_eq!(ErrorCode::None, ErrorCode::try_from(response.error_code)?);
52/// assert_eq!(Some([].into()), response.groups);
53/// # Ok(())
54/// # }
55/// ```
56#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
57pub struct ListGroupsService;
58
59impl ApiKey for ListGroupsService {
60 const KEY: i16 = ListGroupsRequest::KEY;
61}
62
63impl<G> Service<G, ListGroupsRequest> for ListGroupsService
64where
65 G: Storage,
66{
67 type Response = ListGroupsResponse;
68 type Error = Error;
69
70 #[instrument(skip(ctx, req))]
71 async fn serve(
72 &self,
73 ctx: Context<G>,
74 req: ListGroupsRequest,
75 ) -> Result<Self::Response, Self::Error> {
76 ctx.state()
77 .list_groups(req.states_filter.as_deref())
78 .await
79 .map(Some)
80 .map(|groups| {
81 ListGroupsResponse::default()
82 .throttle_time_ms(Some(0))
83 .error_code(ErrorCode::None.into())
84 .groups(groups)
85 })
86 }
87}