1use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7use crate::error::{RagError, Result};
8
9#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
35#[serde(try_from = "String", into = "String")]
36pub struct Scope(String);
37
38impl Scope {
39 pub const MAX_LEN: usize = 256;
41
42 pub const SINGLE_TENANT_KEY: &'static str = ":single-tenant";
45
46 pub fn new(key: impl Into<String>) -> Result<Self> {
53 let key = key.into();
54 if key.is_empty() || key.len() > Self::MAX_LEN {
55 return Err(RagError::InvalidScope(format!(
56 "a scope key is 1 to {} bytes, got {}",
57 Self::MAX_LEN,
58 key.len()
59 )));
60 }
61 if key.chars().any(char::is_control) {
62 return Err(RagError::InvalidScope(
63 "a scope key contains no control characters".to_string(),
64 ));
65 }
66 Ok(Self(key))
67 }
68
69 pub fn from_parts<I, S>(parts: I) -> Result<Self>
91 where
92 I: IntoIterator<Item = S>,
93 S: AsRef<str>,
94 {
95 let mut key = String::new();
96 for (index, part) in parts.into_iter().enumerate() {
97 let part = part.as_ref();
98 if part.is_empty() {
99 return Err(RagError::InvalidScope(format!("scope part {index} is empty")));
100 }
101 if index > 0 {
102 key.push('/');
103 }
104 for byte in part.bytes() {
105 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
106 key.push(char::from(byte));
107 } else {
108 key.push_str(&format!("%{byte:02X}"));
109 }
110 }
111 }
112 if key.is_empty() {
113 return Err(RagError::InvalidScope("a scope needs at least one part".to_string()));
114 }
115 Self::new(key)
116 }
117
118 pub fn single_tenant() -> Self {
123 Self(Self::SINGLE_TENANT_KEY.to_string())
124 }
125
126 pub fn as_str(&self) -> &str {
128 &self.0
129 }
130
131 #[cfg(any(feature = "qdrant", feature = "agent-retrieval"))]
137 pub(crate) fn record_key(&self, chunk_id: &str) -> String {
138 format!("{}:{}{chunk_id}", self.0.len(), self.0)
139 }
140}
141
142impl fmt::Display for Scope {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 f.write_str(&self.0)
145 }
146}
147
148impl TryFrom<String> for Scope {
149 type Error = RagError;
150
151 fn try_from(key: String) -> Result<Self> {
152 Self::new(key)
153 }
154}
155
156impl From<Scope> for String {
157 fn from(scope: Scope) -> Self {
158 scope.0
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 #[test]
167 fn new_rejects_empty_long_and_control_keys() {
168 for key in [String::new(), "x".repeat(Scope::MAX_LEN + 1), "a\nb".into(), "a\0b".into()] {
169 assert!(
170 matches!(Scope::new(key.clone()), Err(RagError::InvalidScope(_))),
171 "{key:?} is accepted"
172 );
173 }
174 assert_eq!(
175 Scope::new("x".repeat(Scope::MAX_LEN)).map(|s| s.as_str().len()).ok(),
176 Some(256)
177 );
178 }
179
180 #[test]
181 fn from_parts_is_injective_and_never_yields_the_single_tenant_key() {
182 let lists: [&[&str]; 6] =
183 [&["a", "b"], &["a/b"], &["a%2Fb"], &["a", "b", "c"], &[":single-tenant"], &["a b"]];
184 let keys: Vec<String> = lists
185 .iter()
186 .map(|parts| Scope::from_parts(parts.iter()).expect("valid parts").0)
187 .collect();
188 assert_eq!(
189 keys,
190 ["a/b", "a%2Fb", "a%252Fb", "a/b/c", "%3Asingle-tenant", "a%20b"].map(String::from)
191 );
192 assert!(Scope::from_parts(Vec::<&str>::new()).is_err());
193 assert!(Scope::from_parts(["app", ""]).is_err());
194 }
195
196 #[cfg(any(feature = "qdrant", feature = "agent-retrieval"))]
197 #[test]
198 fn record_keys_of_distinct_pairs_differ() {
199 let ab = Scope::new("ab").unwrap();
200 let a = Scope::new("a").unwrap();
201 assert_ne!(ab.record_key("c"), a.record_key("bc"));
202 assert_eq!(ab.record_key("c"), "2:abc");
203 }
204
205 #[test]
206 fn serde_round_trips_and_validates() {
207 let scope = Scope::from_parts(["app", "t1"]).unwrap();
208 let json = serde_json::to_string(&scope).unwrap();
209 assert_eq!(json, "\"app/t1\"");
210 assert_eq!(serde_json::from_str::<Scope>(&json).unwrap(), scope);
211 assert!(serde_json::from_str::<Scope>("\"\"").is_err());
212 }
213}