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
28impl 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#[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#[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 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")]
139pub struct ReplEntryV1 {
141 uuid: Uuid,
142 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 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 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")]
260pub struct ReplIncrementalEntryV1 {
262 pub(crate) uuid: Uuid,
263 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 let live_attrs = entry.get_ava();
281
282 let attrs = changes
283 .iter()
284 .filter_map(|(attr_name, cid)| {
285 let within = schema.is_replicated(attr_name)
287 && ctx_range
288 .get(&cid.s_uuid)
289 .map(|repl_range| {
290 cid.ts <= repl_range.ts_max &&
292 cid.ts > repl_range.ts_min
294 })
295 .unwrap_or(false);
297
298 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 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#[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 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 ranges: BTreeMap<Uuid, ReplAnchoredCidRange>,
415 schema_entries: Vec<ReplIncrementalEntryV1>,
416 meta_entries: Vec<ReplIncrementalEntryV1>,
417 entries: Vec<ReplIncrementalEntryV1>,
418 },
419}