1use crate::{
2 prelude::*,
3 repl::cid::Cid,
4 schema::SchemaAttribute,
5 valueset::{DbValueSetV2, ScimResolveStatus, ValueSet},
6};
7use kanidm_proto::scim_v1::server::ScimAuditString;
8use std::collections::BTreeMap;
9use time::OffsetDateTime;
10
11type AuditLogStringType = (Cid, String);
12
13pub const AUDIT_LOG_STRING_CAPACITY: usize = 9;
14
15#[derive(Debug, Clone)]
16pub struct ValueSetAuditLogString {
17 map: BTreeMap<Cid, String>,
18}
19
20impl ValueSetAuditLogString {
21 fn remove_oldest(&mut self) {
22 while self.map.len() > AUDIT_LOG_STRING_CAPACITY {
24 self.map.pop_first();
25 }
26 }
27
28 pub fn new((c, s): AuditLogStringType) -> Box<Self> {
29 let mut map = BTreeMap::new();
30 map.insert(c, s);
31 Box::new(ValueSetAuditLogString { map })
32 }
33
34 pub fn from_dbvs2(data: Vec<AuditLogStringType>) -> Result<ValueSet, OperationError> {
35 let map = data.into_iter().collect();
36 Ok(Box::new(ValueSetAuditLogString { map }))
37 }
38}
39
40impl ValueSetT for ValueSetAuditLogString {
41 fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
42 match value {
43 Value::AuditLogString(c, s) => {
44 let r = self.map.insert(c, s);
45 self.remove_oldest();
46 Ok(r.is_none())
48 }
49 _ => {
50 debug_assert!(false);
51 Err(OperationError::InvalidValueState)
52 }
53 }
54 }
55
56 fn clear(&mut self) {
57 self.map.clear();
58 }
59
60 fn remove(&mut self, _pv: &PartialValue, _cid: &Cid) -> bool {
61 self.map.is_empty()
62 }
63
64 fn contains(&self, pv: &PartialValue) -> bool {
65 match pv {
66 PartialValue::Utf8(s) => self.map.values().any(|current| s.eq(current)),
67 PartialValue::Cid(c) => self.map.contains_key(c),
68 _ => {
69 debug_assert!(false);
70 true
71 }
72 }
73 }
74
75 fn substring(&self, _pv: &PartialValue) -> bool {
76 false
77 }
78
79 fn startswith(&self, _pv: &PartialValue) -> bool {
80 false
81 }
82
83 fn endswith(&self, _pv: &PartialValue) -> bool {
84 false
85 }
86
87 fn lessthan(&self, _pv: &PartialValue) -> bool {
88 false
89 }
90
91 fn len(&self) -> usize {
92 self.map.len()
93 }
94
95 fn generate_idx_eq_keys(&self) -> Vec<String> {
96 self.map.iter().map(|(d, s)| format!("{d}-{s}")).collect()
97 }
98
99 fn syntax(&self) -> SyntaxType {
100 SyntaxType::AuditLogString
101 }
102
103 fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
104 self.map
105 .iter()
106 .all(|(_, s)| Value::validate_str_escapes(s) && Value::validate_singleline(s))
107 && self.map.len() <= AUDIT_LOG_STRING_CAPACITY
108 }
109
110 fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
111 Box::new(self.map.iter().map(|(d, s)| format!("{d}-{s}")))
112 }
113
114 fn to_scim_value(&self) -> Option<ScimResolveStatus> {
115 Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
116 self.map
117 .iter()
118 .map(|(cid, strdata)| {
119 let odt: OffsetDateTime = cid.into();
120 ScimAuditString {
121 date_time: odt,
122 value: strdata.clone(),
123 }
124 })
125 .collect::<Vec<_>>(),
126 )))
127 }
128
129 fn to_db_valueset_v2(&self) -> DbValueSetV2 {
130 DbValueSetV2::AuditLogString(
131 self.map
132 .iter()
133 .map(|(c, s)| (c.clone(), s.clone()))
134 .collect(),
135 )
136 }
137
138 fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
139 Box::new(self.map.keys().map(|c| PartialValue::Cid(c.clone())))
140 }
141
142 fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
143 Box::new(
144 self.map
145 .iter()
146 .map(|(c, s)| Value::AuditLogString(c.clone(), s.clone())),
147 )
148 }
149
150 fn equal(&self, other: &ValueSet) -> bool {
151 if let Some(other) = other.as_audit_log_string() {
152 &self.map == other
153 } else {
154 debug_assert!(false);
155 false
156 }
157 }
158
159 fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
160 if let Some(b) = other.as_audit_log_string() {
161 mergemaps!(self.map, b)?;
162 self.remove_oldest();
163 Ok(())
164 } else {
165 debug_assert!(false);
166 Err(OperationError::InvalidValueState)
167 }
168 }
169
170 #[allow(clippy::todo)]
171 fn repl_merge_valueset(&self, older: &ValueSet, _trim_cid: &Cid) -> Option<ValueSet> {
172 if let Some(mut map) = older.as_audit_log_string().cloned() {
173 mergemaps!(map, self.map)
176 .map_err(|_: OperationError| ())
177 .ok()?;
178 let mut new_vs = Box::new(ValueSetAuditLogString { map });
179 new_vs.remove_oldest();
180 Some(new_vs)
181 } else {
182 debug_assert!(false);
183 None
184 }
185 }
186
187 fn as_audit_log_string(&self) -> Option<&BTreeMap<Cid, String>> {
188 Some(&self.map)
189 }
190}
191
192#[cfg(test)]
193mod tests {
194 use super::{ValueSetAuditLogString, AUDIT_LOG_STRING_CAPACITY};
195 use crate::{repl::cid::Cid, value::Value, valueset::ValueSet};
196 use std::time::Duration;
197
198 #[test]
199 fn test_valueset_auditlogstring_merge() {
200 let mut vs: ValueSet = ValueSetAuditLogString::new((Cid::new_count(0), "A".to_string()));
201 assert_eq!(vs.len(), 1);
202
203 for i in 1..AUDIT_LOG_STRING_CAPACITY {
204 vs.insert_checked(Value::AuditLogString(
205 Cid::new_count(i as u64),
206 "A".to_string(),
207 ))
208 .unwrap();
209 }
210
211 assert_eq!(vs.len(), AUDIT_LOG_STRING_CAPACITY);
212
213 vs.insert_checked(Value::AuditLogString(
215 Cid::new_count(AUDIT_LOG_STRING_CAPACITY as u64),
216 "A".to_string(),
217 ))
218 .unwrap();
219
220 assert_eq!(vs.len(), AUDIT_LOG_STRING_CAPACITY);
221
222 let mut v_iter = vs.to_value_iter();
223 let Some(Value::AuditLogString(c, _s)) = v_iter.next() else {
224 unreachable!();
225 };
226 assert_eq!(c.ts, Duration::from_secs(1));
228 println!("{c:?}");
229 drop(v_iter);
230
231 let other_vs: ValueSet = ValueSetAuditLogString::new(
233 (Cid::new_count(0), "A".to_string()),
235 );
236 assert_eq!(other_vs.len(), 1);
237
238 vs.merge(&other_vs)
240 .expect("Failed to merge, incorrect types");
241
242 assert_eq!(vs.len(), AUDIT_LOG_STRING_CAPACITY);
244 let mut v_iter = vs.to_value_iter();
245 let Some(Value::AuditLogString(c, _s)) = v_iter.next() else {
246 unreachable!();
247 };
248 assert_eq!(c.ts, Duration::from_secs(1));
250 println!("{c:?}");
251 drop(v_iter);
252
253 #[allow(clippy::bool_assert_comparison, clippy::assertions_on_constants)]
256 {
257 assert!(100 > AUDIT_LOG_STRING_CAPACITY);
258 }
259
260 let other_vs: ValueSet = ValueSetAuditLogString::new(
261 (Cid::new_count(100), "A".to_string()),
263 );
264 assert_eq!(other_vs.len(), 1);
265
266 vs.merge(&other_vs)
267 .expect("Failed to merge, incorrect types");
268
269 assert_eq!(vs.len(), AUDIT_LOG_STRING_CAPACITY);
271 let mut v_iter = vs.to_value_iter();
272 let Some(Value::AuditLogString(c, _s)) = v_iter.next() else {
273 unreachable!();
274 };
275 println!("{c:?}");
277 assert_eq!(c.ts, Duration::from_secs(2));
278 drop(v_iter);
279 }
280
281 #[test]
282 fn test_valueset_auditlogstring_repl_merge() {
283 let zero_cid = Cid::new_zero();
284 let mut vs: ValueSet = ValueSetAuditLogString::new((Cid::new_count(1), "A".to_string()));
285 assert_eq!(vs.len(), 1);
286
287 for i in 2..(AUDIT_LOG_STRING_CAPACITY + 1) {
288 vs.insert_checked(Value::AuditLogString(
289 Cid::new_count(i as u64),
290 "A".to_string(),
291 ))
292 .unwrap();
293 }
294
295 assert_eq!(vs.len(), AUDIT_LOG_STRING_CAPACITY);
296
297 let other_vs: ValueSet = ValueSetAuditLogString::new(
299 (Cid::new_count(0), "A".to_string()),
301 );
302 assert_eq!(other_vs.len(), 1);
303
304 let r_vs = vs
306 .repl_merge_valueset(&other_vs, &zero_cid)
307 .expect("merge did not occur");
308
309 assert_eq!(r_vs.len(), AUDIT_LOG_STRING_CAPACITY);
311 let mut v_iter = r_vs.to_value_iter();
312 let Some(Value::AuditLogString(c, _s)) = v_iter.next() else {
313 unreachable!();
314 };
315 assert_eq!(c.ts, Duration::from_secs(1));
317 println!("{c:?}");
318 drop(v_iter);
319
320 #[allow(clippy::bool_assert_comparison, clippy::assertions_on_constants)]
323 {
324 assert!(100 > AUDIT_LOG_STRING_CAPACITY);
325 }
326
327 let other_vs: ValueSet = ValueSetAuditLogString::new(
328 (Cid::new_count(100), "A".to_string()),
330 );
331 assert_eq!(other_vs.len(), 1);
332
333 let r_vs = vs
334 .repl_merge_valueset(&other_vs, &zero_cid)
335 .expect("merge did not occur");
336
337 assert_eq!(r_vs.len(), AUDIT_LOG_STRING_CAPACITY);
339 let mut v_iter = r_vs.to_value_iter();
340 let Some(Value::AuditLogString(c, _s)) = v_iter.next() else {
341 unreachable!();
342 };
343 println!("{c:?}");
345 assert_eq!(c.ts, Duration::from_secs(2));
346 drop(v_iter);
347 }
348
349 #[test]
350 fn test_scim_auditlog_string() {
351 let mut vs: ValueSet = ValueSetAuditLogString::new((Cid::new_count(0), "A".to_string()));
352 assert!(vs.len() == 1);
353
354 for i in 1..AUDIT_LOG_STRING_CAPACITY {
355 vs.insert_checked(Value::AuditLogString(
356 Cid::new_count(i as u64),
357 "A".to_string(),
358 ))
359 .unwrap();
360 }
361
362 let data = r#"
363[
364 {
365 "dateTime": "1970-01-01T00:00:00Z",
366 "value": "A"
367 },
368 {
369 "dateTime": "1970-01-01T00:00:01Z",
370 "value": "A"
371 },
372 {
373 "dateTime": "1970-01-01T00:00:02Z",
374 "value": "A"
375 },
376 {
377 "dateTime": "1970-01-01T00:00:03Z",
378 "value": "A"
379 },
380 {
381 "dateTime": "1970-01-01T00:00:04Z",
382 "value": "A"
383 },
384 {
385 "dateTime": "1970-01-01T00:00:05Z",
386 "value": "A"
387 },
388 {
389 "dateTime": "1970-01-01T00:00:06Z",
390 "value": "A"
391 },
392 {
393 "dateTime": "1970-01-01T00:00:07Z",
394 "value": "A"
395 },
396 {
397 "dateTime": "1970-01-01T00:00:08Z",
398 "value": "A"
399 }
400]
401"#;
402 crate::valueset::scim_json_reflexive(&vs, data);
403 }
404}