Skip to main content

confluent_kafka/common/resource/
resource_pattern.rs

1// Copyright 2025 Confluent Inc.
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
15//! ACL resource patterns.
16//!
17//! Corresponds to `org.apache.kafka.common.resource.ResourcePattern`.
18
19use crate::common::Error;
20
21use super::{PatternType, ResourcePatternFilter, ResourceType};
22
23/// Represents a pattern that is used by ACLs to match zero or more
24/// [`Resource`](super::Resource)s.
25#[derive(Clone, Debug, PartialEq, Eq, Hash)]
26#[doc(alias = "org.apache.kafka.common.resource.ResourcePattern")]
27pub struct ResourcePattern {
28    resource_type: ResourceType,
29    name: String,
30    pattern_type: PatternType,
31}
32
33impl ResourcePattern {
34    /// A special literal resource name that corresponds to 'all resources of a
35    /// certain type'.
36    #[doc(alias = "org.apache.kafka.common.resource.ResourcePattern#WILDCARD_RESOURCE")]
37    pub const WILDCARD_RESOURCE: &str = "*";
38
39    /// Create a pattern using the supplied parameters.
40    ///
41    /// # Arguments
42    /// * `resource_type` - specific resource type
43    /// * `name` - resource name, which can be the [`Self::WILDCARD_RESOURCE`]
44    /// * `pattern_type` - specific resource pattern type, which controls how the
45    ///   pattern will match resource names
46    ///
47    /// # Errors
48    ///
49    /// - [`Error::is_local_illegal_argument_error`] if `resource_type` is
50    ///   [`ResourceType::Any`], or `pattern_type` is [`PatternType::Match`] or
51    ///   [`PatternType::Any`].
52    #[doc(alias = "org.apache.kafka.common.resource.ResourcePattern#ResourcePattern")]
53    pub fn new(
54        resource_type: ResourceType,
55        name: impl Into<String>,
56        pattern_type: PatternType,
57    ) -> Result<ResourcePattern, Error> {
58        if resource_type == ResourceType::Any {
59            return Err(Error::local_illegal_argument("resourceType must not be ANY"));
60        }
61        if pattern_type == PatternType::Match || pattern_type == PatternType::Any {
62            return Err(Error::local_illegal_argument(format!("patternType must not be {pattern_type}")));
63        }
64        Ok(ResourcePattern { resource_type, name: name.into(), pattern_type })
65    }
66
67    /// Returns the specific resource type this pattern matches.
68    #[doc(alias = "org.apache.kafka.common.resource.ResourcePattern#resourceType")]
69    pub fn resource_type(&self) -> ResourceType {
70        self.resource_type
71    }
72
73    /// Returns the resource name.
74    #[doc(alias = "org.apache.kafka.common.resource.ResourcePattern#name")]
75    pub fn name(&self) -> &str {
76        &self.name
77    }
78
79    /// Returns the resource pattern type.
80    #[doc(alias = "org.apache.kafka.common.resource.ResourcePattern#patternType")]
81    pub fn pattern_type(&self) -> PatternType {
82        self.pattern_type
83    }
84
85    /// Returns a filter which matches only this pattern.
86    #[doc(alias = "org.apache.kafka.common.resource.ResourcePattern#toFilter")]
87    pub fn to_filter(&self) -> ResourcePatternFilter {
88        ResourcePatternFilter::new(self.resource_type, Some(self.name.clone()), self.pattern_type)
89    }
90
91    /// Returns `true` if this pattern has any UNKNOWN components.
92    #[doc(alias = "org.apache.kafka.common.resource.ResourcePattern#isUnknown")]
93    pub fn is_unknown(&self) -> bool {
94        self.resource_type.is_unknown() || self.pattern_type.is_unknown()
95    }
96}
97
98impl std::fmt::Display for ResourcePattern {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        write!(
101            f,
102            "ResourcePattern(resourceType={}, name={}, patternType={})",
103            self.resource_type, self.name, self.pattern_type
104        )
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    // Java's `ResourcePatternTest.shouldThrowIfResourceNameIsNull` is not
113    // representable: the Rust `name` parameter is a non-nullable `String`, so
114    // there is no null to reject (Java's `Objects.requireNonNull(name)`).
115
116    #[test]
117    fn should_throw_if_resource_type_is_any() {
118        let err = ResourcePattern::new(ResourceType::Any, "name", PatternType::Literal);
119        assert!(matches!(err, Err(Error::LocalIllegalArgument(_))));
120    }
121
122    #[test]
123    fn should_throw_if_pattern_type_is_match() {
124        let err = ResourcePattern::new(ResourceType::Topic, "name", PatternType::Match);
125        assert!(matches!(err, Err(Error::LocalIllegalArgument(_))));
126    }
127
128    #[test]
129    fn should_throw_if_pattern_type_is_any() {
130        let err = ResourcePattern::new(ResourceType::Topic, "name", PatternType::Any);
131        assert!(matches!(err, Err(Error::LocalIllegalArgument(_))));
132    }
133
134    #[test]
135    fn accessors_and_to_filter() {
136        let pattern = ResourcePattern::new(ResourceType::Topic, "foo", PatternType::Literal).unwrap();
137        assert_eq!(pattern.resource_type(), ResourceType::Topic);
138        assert_eq!(pattern.name(), "foo");
139        assert_eq!(pattern.pattern_type(), PatternType::Literal);
140        assert!(!pattern.is_unknown());
141        let filter = pattern.to_filter();
142        assert!(filter.matches(&pattern));
143    }
144
145    #[test]
146    fn is_unknown_for_unknown_components() {
147        let pattern = ResourcePattern::new(ResourceType::Unknown, "foo", PatternType::Literal).unwrap();
148        assert!(pattern.is_unknown());
149        let pattern = ResourcePattern::new(ResourceType::Topic, "foo", PatternType::Unknown).unwrap();
150        assert!(pattern.is_unknown());
151    }
152}