Skip to main content

kanidmd_lib/repl/
proto.rs

1use super::{
2    cid::Cid,
3    entry::{EntryChangeState, State},
4};
5use crate::{
6    be::dbvalue::DbValueSetV2,
7    entry::Eattrs,
8    prelude::*,
9    schema::{SchemaReadTransaction, SchemaTransaction},
10    valueset,
11};
12use serde::{Deserialize, Serialize};
13use std::{collections::BTreeMap, fmt};
14
15pub enum ConsumerState {
16    Ok,
17    RefreshRequired,
18}
19
20#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
21pub struct ReplCidV1 {
22    #[serde(rename = "t")]
23    pub ts: Duration,
24    #[serde(rename = "s")]
25    pub s_uuid: Uuid,
26}
27
28// From / Into CID
29impl From<&Cid> for ReplCidV1 {
30    fn from(cid: &Cid) -> Self {
31        ReplCidV1 {
32            ts: cid.ts,
33            s_uuid: cid.s_uuid,
34        }
35    }
36}
37
38impl From<ReplCidV1> for Cid {
39    fn from(cid: ReplCidV1) -> Self {
40        Cid {
41            ts: cid.ts,
42            s_uuid: cid.s_uuid,
43        }
44    }
45}
46
47impl From<&ReplCidV1> for Cid {
48    fn from(cid: &ReplCidV1) -> Self {
49        Cid {
50            ts: cid.ts,
51            s_uuid: cid.s_uuid,
52        }
53    }
54}
55
56/// An anchored CID range. This contains a minimum and maximum range of CID times for a server,
57/// and also includes the list of all CIDs that occur between those two points. This allows these
58/// extra change "anchors" to be injected into the consumer RUV during an incremental. Once
59/// inserted, these anchors prevent RUV trimming from creating "jumps" due to idle servers.
60#[derive(Serialize, Deserialize, PartialEq, Eq)]
61pub struct ReplAnchoredCidRange {
62    #[serde(rename = "m")]
63    pub ts_min: Duration,
64    #[serde(rename = "a", default)]
65    pub anchors: Vec<Duration>,
66    #[serde(rename = "x")]
67    pub ts_max: Duration,
68}
69
70impl fmt::Debug for ReplAnchoredCidRange {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        write!(
73            f,
74            "{:032} --{}-> {:032}",
75            self.ts_min.as_nanos(),
76            self.anchors.len(),
77            self.ts_max.as_nanos()
78        )
79    }
80}
81
82/// A CID range. This contains the minimum and maximum values of a range. This is used for
83/// querying the RUV to select all elements in this range.
84#[derive(Serialize, Deserialize, PartialEq, Eq)]
85pub struct ReplCidRange {
86    #[serde(rename = "m")]
87    pub ts_min: Duration,
88    #[serde(rename = "x")]
89    pub ts_max: Duration,
90}
91
92impl fmt::Debug for ReplCidRange {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        write!(
95            f,
96            "{:032} -> {:032}",
97            self.ts_min.as_nanos(),
98            self.ts_max.as_nanos()
99        )
100    }
101}
102
103#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
104pub enum ReplRuvRange {
105    V1 {
106        domain_uuid: Uuid,
107        ranges: BTreeMap<Uuid, ReplCidRange>,
108    },
109}
110
111impl ReplRuvRange {
112    pub fn is_empty(&self) -> bool {
113        match self {
114            ReplRuvRange::V1 { ranges, .. } => ranges.is_empty(),
115        }
116    }
117}
118
119#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
120pub struct ReplAttrStateV1 {
121    cid: ReplCidV1,
122    attr: Option<DbValueSetV2>,
123}
124
125#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
126pub enum ReplStateV1 {
127    Live {
128        at: ReplCidV1,
129        // Also add AT here for breaking entry origin on conflict.
130        attrs: BTreeMap<Attribute, ReplAttrStateV1>,
131    },
132    Tombstone {
133        at: ReplCidV1,
134    },
135}
136
137#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
138#[serde(rename_all = "lowercase")]
139// I think partial entries should be separate? This clearly implies a refresh.
140pub struct ReplEntryV1 {
141    uuid: Uuid,
142    // Change State
143    st: ReplStateV1,
144}
145
146impl ReplEntryV1 {
147    pub fn new(entry: &EntrySealedCommitted, schema: &SchemaReadTransaction) -> ReplEntryV1 {
148        let cs = entry.get_changestate();
149        let uuid = entry.get_uuid();
150
151        let st = match cs.current() {
152            State::Live { at, changes } => {
153                let live_attrs = entry.get_ava();
154
155                let attrs = changes
156                    .iter()
157                    .filter_map(|(attr_name, cid)| {
158                        if schema.is_replicated(attr_name) {
159                            let live_attr = live_attrs.get(attr_name);
160
161                            let cid = cid.into();
162                            let attr = live_attr.and_then(|maybe|
163                                // There is a quirk in the way we currently handle certain
164                                // types of adds/deletes that it may be possible to have an
165                                // empty value set still in memory on a supplier. In the future
166                                // we may make it so in memory valuesets can be empty and sent
167                                // but for now, if it's an empty set in any capacity, we map
168                                // to None and just send the Cid since they have the same result
169                                // on how the entry/attr state looks at each end.
170                                if maybe.is_empty() {
171                                    None
172                                } else {
173                                    Some(maybe.to_db_valueset_v2())
174                                }
175                            );
176
177                            Some((attr_name.clone(), ReplAttrStateV1 { cid, attr }))
178                        } else {
179                            None
180                        }
181                    })
182                    .collect();
183
184                ReplStateV1::Live {
185                    at: at.into(),
186                    attrs,
187                }
188            }
189            State::Tombstone { at } => ReplStateV1::Tombstone { at: at.into() },
190        };
191
192        ReplEntryV1 { uuid, st }
193    }
194
195    pub fn rehydrate(self) -> Result<(EntryChangeState, Eattrs), OperationError> {
196        match self.st {
197            ReplStateV1::Live { at, attrs } => {
198                trace!("{:?} {:#?}", at, attrs);
199                // We need to build two sets, one for the Entry Change States, and one for the
200                // Eattrs.
201                let mut changes = BTreeMap::default();
202                let mut eattrs = Eattrs::default();
203
204                for (attr_name, ReplAttrStateV1 { cid, attr }) in attrs.into_iter() {
205                    let cid: Cid = cid.into();
206
207                    if let Some(attr_value) = attr {
208                        let v = valueset::from_db_valueset_v2(attr_value).inspect_err(|err| {
209                            error!(?err, "Unable to restore valueset for {}", attr_name);
210                        })?;
211                        if eattrs.insert(attr_name.clone(), v).is_some() {
212                            error!(
213                                "Impossible eattrs state, attribute {} appears to be duplicated!",
214                                attr_name
215                            );
216                            return Err(OperationError::InvalidEntryState);
217                        }
218                    }
219
220                    if changes.insert(attr_name.clone(), cid).is_some() {
221                        error!(
222                            "Impossible changes state, attribute {} appears to be duplicated!",
223                            attr_name
224                        );
225                        return Err(OperationError::InvalidEntryState);
226                    }
227                }
228
229                let at: Cid = at.into();
230
231                let ecstate = EntryChangeState {
232                    st: State::Live { at, changes },
233                };
234                Ok((ecstate, eattrs))
235            }
236            ReplStateV1::Tombstone { at } => {
237                let at: Cid = at.into();
238
239                let mut eattrs = Eattrs::default();
240
241                let class_ava = vs_iutf8n![EntryClass::Object.into(), EntryClass::Tombstone.into()];
242                let last_mod_ava = vs_cid![at.clone()];
243
244                eattrs.insert(Attribute::Uuid, vs_uuid![self.uuid]);
245                eattrs.insert(Attribute::Class, class_ava);
246                eattrs.insert(Attribute::LastModifiedCid, last_mod_ava);
247
248                let ecstate = EntryChangeState {
249                    st: State::Tombstone { at },
250                };
251
252                Ok((ecstate, eattrs))
253            }
254        }
255    }
256}
257
258#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
259#[serde(rename_all = "lowercase")]
260// I think partial entries should be separate? This clearly implies a refresh.
261pub struct ReplIncrementalEntryV1 {
262    pub(crate) uuid: Uuid,
263    // Change State
264    pub(crate) st: ReplStateV1,
265}
266
267impl ReplIncrementalEntryV1 {
268    pub fn new(
269        entry: &EntrySealedCommitted,
270        schema: &SchemaReadTransaction,
271        ctx_range: &BTreeMap<Uuid, ReplCidRange>,
272    ) -> ReplIncrementalEntryV1 {
273        let cs = entry.get_changestate();
274        let uuid = entry.get_uuid();
275
276        let st = match cs.current() {
277            State::Live { at, changes } => {
278                // Only put attributes into the change state that were changed within the range that was
279                // requested.
280                let live_attrs = entry.get_ava();
281
282                let attrs = changes
283                    .iter()
284                    .filter_map(|(attr_name, cid)| {
285                        // If the cid is within the ctx range
286                        let within = schema.is_replicated(attr_name)
287                            && ctx_range
288                                .get(&cid.s_uuid)
289                                .map(|repl_range| {
290                                    // Supply anything up to and including.
291                                    cid.ts <= repl_range.ts_max &&
292                                    // ts_min is always what the consumer already has.
293                                    cid.ts > repl_range.ts_min
294                                })
295                                // If not present in the range, assume it's not needed.
296                                .unwrap_or(false);
297
298                        // Then setup to supply it.
299                        if within {
300                            let live_attr = live_attrs.get(attr_name);
301                            let cid = cid.into();
302                            let attr = live_attr.and_then(|maybe| {
303                                if maybe.is_empty() {
304                                    None
305                                } else {
306                                    Some(maybe.to_db_valueset_v2())
307                                }
308                            });
309
310                            Some((attr_name.clone(), ReplAttrStateV1 { cid, attr }))
311                        } else {
312                            None
313                        }
314                    })
315                    .collect();
316
317                ReplStateV1::Live {
318                    at: at.into(),
319                    attrs,
320                }
321            }
322            // Don't care what the at is - send the tombstone.
323            State::Tombstone { at } => ReplStateV1::Tombstone { at: at.into() },
324        };
325
326        ReplIncrementalEntryV1 { uuid, st }
327    }
328
329    pub fn rehydrate(self) -> Result<(Uuid, EntryChangeState, Eattrs), OperationError> {
330        match self.st {
331            ReplStateV1::Live { at, attrs } => {
332                trace!("{:?} {:#?}", at, attrs);
333                let mut changes = BTreeMap::default();
334                let mut eattrs = Eattrs::default();
335
336                for (attr_name, ReplAttrStateV1 { cid, attr }) in attrs.into_iter() {
337                    let cid: Cid = cid.into();
338
339                    if let Some(attr_value) = attr {
340                        let v = valueset::from_db_valueset_v2(attr_value).inspect_err(|err| {
341                            error!(?err, "Unable to restore valueset for {}", attr_name);
342                        })?;
343                        if eattrs.insert(attr_name.clone(), v).is_some() {
344                            error!(
345                                "Impossible eattrs state, attribute {} appears to be duplicated!",
346                                attr_name
347                            );
348                            return Err(OperationError::InvalidEntryState);
349                        }
350                    }
351
352                    if changes.insert(attr_name.clone(), cid).is_some() {
353                        error!(
354                            "Impossible changes state, attribute {} appears to be duplicated!",
355                            attr_name
356                        );
357                        return Err(OperationError::InvalidEntryState);
358                    }
359                }
360
361                let at: Cid = at.into();
362
363                let ecstate = EntryChangeState {
364                    st: State::Live { at, changes },
365                };
366                Ok((self.uuid, ecstate, eattrs))
367            }
368            ReplStateV1::Tombstone { at } => {
369                let at: Cid = at.into();
370                let eattrs = Eattrs::default();
371                let ecstate = EntryChangeState {
372                    st: State::Tombstone { at },
373                };
374                Ok((self.uuid, ecstate, eattrs))
375            }
376        }
377    }
378}
379
380// From / Into Entry
381
382#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
383#[serde(rename_all = "lowercase")]
384pub enum ReplRefreshContext {
385    V1 {
386        domain_version: DomainVersion,
387        domain_devel: bool,
388        domain_uuid: Uuid,
389        // We need to send the current state of the ranges to populate into
390        // the ranges so that lookups and ranges work properly.
391        ranges: BTreeMap<Uuid, ReplAnchoredCidRange>,
392        schema_entries: Vec<ReplEntryV1>,
393        meta_entries: Vec<ReplEntryV1>,
394        entries: Vec<ReplEntryV1>,
395    },
396}
397
398#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
399#[serde(rename_all = "lowercase")]
400pub enum ReplIncrementalContext {
401    DomainMismatch,
402    NoChangesAvailable,
403    RefreshRequired,
404    UnwillingToSupply,
405    V1 {
406        domain_version: DomainVersion,
407        #[serde(default)]
408        domain_patch_level: u32,
409        domain_uuid: Uuid,
410        // We need to send the current state of the ranges to populate into
411        // the ranges so that lookups and ranges work properly, and the
412        // consumer ends with the same state as we have (or at least merges)
413        // it with this.
414        ranges: BTreeMap<Uuid, ReplAnchoredCidRange>,
415        schema_entries: Vec<ReplIncrementalEntryV1>,
416        meta_entries: Vec<ReplIncrementalEntryV1>,
417        entries: Vec<ReplIncrementalEntryV1>,
418    },
419}