Skip to main content

coven_format/
loss.rs

1//! One loss record for displaced cells, removed rows and excluded writes.
2
3use crate::error::{require, Error, Rule as FormatRule};
4use crate::value::{name, positive, row, Value};
5use crate::wire::{Decoder, Encoder, Wire};
6use crate::write_sources::ChangeId;
7use coven_foundation::id_source::MemberId;
8use coven_merge::{Cell, LostKey, LostValue, RowId, Rule, WriteId};
9use std::collections::{BTreeMap, BTreeSet};
10
11/// A loss independent of local SQLite identities. Active losses follow merge;
12/// frozen losses keep their values and cause after their merge history is gone.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Loss {
15    /// Original table, key and audience.
16    pub row: RowId,
17    /// Cell incarnation, removed-row generation, or excluded change's generation.
18    pub generation: u64,
19    /// Whether this loss is frozen outside merge.
20    pub frozen: bool,
21    /// Values as written, with each value's setter.
22    pub values: LossValues,
23    /// What displaced these values.
24    pub cause: LossCause,
25}
26impl Wire for Loss {
27    fn put(&self, out: &mut Encoder) -> Result<(), Error> {
28        self.row.put(out)?;
29        self.generation.put(out)?;
30        u8::from(self.frozen).put(out)?;
31        self.values.put(out)?;
32        self.cause.put(out)
33    }
34    fn get(input: &mut Decoder<'_>) -> Result<Self, Error> {
35        let row = Wire::get(input)?;
36        let generation = Wire::get(input)?;
37        let frozen = match u8::get(input)? {
38            0 => false,
39            1 => true,
40            tag => return Err(Error::UnknownTag { field: "loss retirement", tag }),
41        };
42        Ok(Self { row, generation, frozen, values: Wire::get(input)?, cause: Wire::get(input)? })
43    }
44}
45
46/// The cell or whole row retained by a loss.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub enum LossValues {
49    /// One concurrently displaced cell.
50    Cell {
51        /// The displaced column.
52        column: String,
53        /// Its written value and setter.
54        cell: Cell<Value>,
55    },
56    /// Every retained column of a removed or excluded row.
57    Row(BTreeMap<String, Cell<Value>>),
58}
59impl Wire for LossValues {
60    fn put(&self, out: &mut Encoder) -> Result<(), Error> {
61        match self {
62            Self::Cell { column, cell } => {
63                0u8.put(out)?;
64                column.put(out)?;
65                cell.put(out)
66            }
67            Self::Row(cells) => {
68                1u8.put(out)?;
69                cells.put(out)
70            }
71        }
72    }
73    fn get(input: &mut Decoder<'_>) -> Result<Self, Error> {
74        match u8::get(input)? {
75            0 => Ok(Self::Cell { column: crate::wire::get_name(input)?, cell: Wire::get(input)? }),
76            1 => Ok(Self::Row(crate::wire::get_name_map(input)?)),
77            tag => Err(Error::UnknownTag { field: "loss values", tag }),
78        }
79    }
80}
81
82/// The replacing write, removal rules, or boundary that excluded a write.
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub enum LossCause {
85    /// A replacing write that had not read the lost setter.
86    Write(WriteId),
87    /// Every rule holding when the row was removed.
88    Rules(BTreeSet<Rule>),
89    /// A breaking schema change that excluded the write, or whose migration
90    /// write deleted a hidden row. Resets create no losses (§19.4).
91    Excluded {
92        /// The excluded write, including deletions with no retained cells.
93        write: WriteId,
94        /// The schema version reached by the breaking change.
95        version: u32,
96    },
97    /// An admitted row change that used data which does not survive (§9.5):
98    /// its generation source, a cell setter it replaced, a source its
99    /// operations used, or a foreign-key cause in its own write.
100    Dependency {
101        /// The write whose row change this is, even for an empty delete.
102        write: WriteId,
103        /// Failed sources in role order, with repeats: generation, replaced
104        /// setters, additional execution sources, then foreign-key causes.
105        sources: Vec<ChangeId>,
106    },
107    /// A member's row change without permission: a direct change of another
108    /// member's owned row, a non-admin's direct change of an admin table's
109    /// row, or a foreign-key effect the receiver could not derive exactly
110    /// from an authorized direct change (§9.6).
111    NotAuthorized {
112        /// The write whose row change this is, even for an empty delete.
113        write: WriteId,
114        /// Why the change was refused.
115        reason: AuthorizationFailure,
116    },
117}
118
119/// Why a row change lacked permission (§9.6).
120#[derive(Clone, Debug, PartialEq, Eq)]
121pub enum AuthorizationFailure {
122    /// The row belongs to this member, and the change was not an exact
123    /// foreign-key effect of an authorized change.
124    NotOwner {
125        /// The member whose write created the row.
126        owner: MemberId,
127    },
128    /// The row's table is limited to admins, its author was no admin in the
129    /// state just before the write's slot, and the change was not an exact
130    /// foreign-key effect of an authorized change.
131    NotAdmin,
132    /// A derived change differs from the schema's effect of authorized
133    /// direct changes in its write, or has no authorized root.
134    InvalidForeignKeyEffect,
135}
136impl Wire for AuthorizationFailure {
137    fn put(&self, out: &mut Encoder) -> Result<(), Error> {
138        match self {
139            Self::NotOwner { owner } => {
140                0u8.put(out)?;
141                owner.put(out)
142            }
143            Self::InvalidForeignKeyEffect => 1u8.put(out),
144            Self::NotAdmin => 2u8.put(out),
145        }
146    }
147    fn get(input: &mut Decoder<'_>) -> Result<Self, Error> {
148        match u8::get(input)? {
149            0 => Ok(Self::NotOwner { owner: Wire::get(input)? }),
150            1 => Ok(Self::InvalidForeignKeyEffect),
151            2 => Ok(Self::NotAdmin),
152            tag => Err(Error::UnknownTag { field: "authorization failure", tag }),
153        }
154    }
155}
156impl Wire for LossCause {
157    fn put(&self, out: &mut Encoder) -> Result<(), Error> {
158        match self {
159            Self::Write(write) => {
160                0u8.put(out)?;
161                write.put(out)
162            }
163            Self::Rules(rules) => {
164                1u8.put(out)?;
165                rules.put(out)
166            }
167            Self::Excluded { write, version } => {
168                2u8.put(out)?;
169                write.put(out)?;
170                version.put(out)
171            }
172            Self::Dependency { write, sources } => {
173                3u8.put(out)?;
174                write.put(out)?;
175                sources.put(out)
176            }
177            Self::NotAuthorized { write, reason } => {
178                4u8.put(out)?;
179                write.put(out)?;
180                reason.put(out)
181            }
182        }
183    }
184    fn get(input: &mut Decoder<'_>) -> Result<Self, Error> {
185        match u8::get(input)? {
186            0 => Ok(Self::Write(Wire::get(input)?)),
187            1 => Ok(Self::Rules(Wire::get(input)?)),
188            2 => Ok(Self::Excluded { write: Wire::get(input)?, version: Wire::get(input)? }),
189            3 => Ok(Self::Dependency { write: Wire::get(input)?, sources: Wire::get(input)? }),
190            4 => Ok(Self::NotAuthorized { write: Wire::get(input)?, reason: Wire::get(input)? }),
191            tag => Err(Error::UnknownTag { field: "loss cause", tag }),
192        }
193    }
194}
195
196/// Stable identity within a row and generation; values and causes may change.
197#[derive(PartialEq, Eq, PartialOrd, Ord)]
198pub(crate) enum LossIdentity {
199    Cell(LostKey),
200    Row(BTreeMap<String, WriteId>),
201}
202impl LossCause {
203    /// The original change's own write, for a frozen change loss.
204    pub fn change_write(&self) -> Option<WriteId> {
205        match self {
206            Self::Excluded { write, .. }
207            | Self::Dependency { write, .. }
208            | Self::NotAuthorized { write, .. } => Some(*write),
209            Self::Write(_) | Self::Rules(_) => None,
210        }
211    }
212
213    pub(crate) fn tag(&self) -> u8 {
214        match self {
215            Self::Write(_) => 0,
216            Self::Rules(_) => 1,
217            Self::Excluded { .. } => 2,
218            Self::Dependency { .. } => 3,
219            Self::NotAuthorized { .. } => 4,
220        }
221    }
222
223    /// A frozen original row change: excluded, dependent or unauthorized.
224    pub fn freezes_change(&self) -> bool {
225        self.change_write().is_some()
226    }
227}
228
229impl Loss {
230    /// Project a concurrent merge loss into the common record.
231    pub fn cell(row: RowId, key: LostKey, value: LostValue<Value>) -> Self {
232        Self {
233            row,
234            generation: value.incarnation,
235            frozen: false,
236            values: LossValues::Cell {
237                column: key.column,
238                cell: Cell { write: key.write, value: value.value },
239            },
240            cause: LossCause::Write(value.replaced_by),
241        }
242    }
243
244    /// This loss frozen outside merge: it keeps its written values, setters,
245    /// names and cause, without live parent links (D7).
246    pub fn freeze(mut self) -> Self {
247        self.frozen = true;
248        match &mut self.values {
249            LossValues::Cell { cell, .. } => cell.value.parents.clear(),
250            LossValues::Row(cells) => {
251                for cell in cells.values_mut() {
252                    cell.value.parents.clear();
253                }
254            }
255        }
256        self
257    }
258
259    /// Project a row removed by rules into the common record.
260    pub fn removed(state: &coven_merge::RowState<Value>, rules: BTreeSet<Rule>) -> Self {
261        Self {
262            row: state.row().clone(),
263            generation: state.generation(),
264            frozen: false,
265            values: LossValues::Row(state.cells().clone()),
266            cause: LossCause::Rules(rules),
267        }
268    }
269
270    pub(crate) fn key(&self) -> (RowId, u64, LossIdentity, bool, u8, Option<WriteId>) {
271        let identity = match &self.values {
272            LossValues::Cell { column, cell } => {
273                LossIdentity::Cell(LostKey { column: column.clone(), write: cell.write })
274            }
275            LossValues::Row(cells) => {
276                LossIdentity::Row(cells.iter().map(|(n, c)| (n.clone(), c.write)).collect())
277            }
278        };
279        (
280            self.row.clone(),
281            self.generation,
282            identity,
283            self.frozen,
284            self.cause.tag(),
285            self.cause.change_write(),
286        )
287    }
288
289    pub(crate) fn validate(&self) -> Result<(), Error> {
290        row(&self.row)?;
291        match (&self.values, &self.cause) {
292            (LossValues::Cell { .. }, LossCause::Write(write)) => positive(write.number)?,
293            (LossValues::Row(cells), LossCause::Rules(rules)) => {
294                require(
295                    !cells.is_empty() && !rules.is_empty(),
296                    "removed loss",
297                    FormatRule::Required,
298                )?;
299                crate::merge_wire::rules(rules)?;
300                for rule in rules {
301                    if matches!(rule, Rule::DeletedCircle(_) | Rule::OtherAudience) {
302                        require(
303                            matches!(self.row.audience, coven_merge::Audience::Circle(_)),
304                            "loss audience",
305                            FormatRule::Audience,
306                        )?;
307                    }
308                }
309            }
310            (LossValues::Row(cells), LossCause::Excluded { write, version }) => {
311                positive(write.number)?;
312                // An excluded write names itself as setter; a row a migration
313                // write deleted through its generation keeps each original
314                // setter (D7).
315                for cell in cells.values() {
316                    positive(cell.write.number)?;
317                }
318                require(self.frozen, "excluded loss", FormatRule::Required)?;
319                require(*version > 0, "breaking schema version", FormatRule::Required)?;
320            }
321            (LossValues::Row(cells), LossCause::Dependency { write, sources }) => {
322                positive(write.number)?;
323                require(
324                    cells.values().all(|cell| cell.write == *write),
325                    "dependent setters",
326                    FormatRule::Required,
327                )?;
328                require(self.frozen, "dependent loss", FormatRule::Required)?;
329                require(!sources.is_empty(), "dependency sources", FormatRule::Required)?;
330                for source in sources {
331                    positive(source.write.number)?;
332                    require(
333                        dependency_source(&self.row, *write, source),
334                        "dependency source row",
335                        FormatRule::Required,
336                    )?;
337                }
338            }
339            (LossValues::Row(cells), LossCause::NotAuthorized { write, .. }) => {
340                positive(write.number)?;
341                require(
342                    cells.values().all(|cell| cell.write == *write),
343                    "unauthorized setters",
344                    FormatRule::Required,
345                )?;
346                require(self.frozen, "unauthorized loss", FormatRule::Required)?;
347            }
348            _ => {
349                return Err(Error::Invalid {
350                    field: "loss cause",
351                    rule: FormatRule::ColumnOperation,
352                })
353            }
354        }
355        if !self.cause.freezes_change() {
356            require(
357                coven_merge::generation_present(self.generation),
358                "loss incarnation",
359                FormatRule::Generation,
360            )?;
361        }
362        let cell = |n: &str, cell: &Cell<Value>| {
363            name(n)?;
364            positive(cell.write.number)?;
365            crate::merge_wire::column(&cell.value)?;
366            if self.frozen {
367                require(cell.value.parents.is_empty(), "frozen references", FormatRule::Required)?;
368            } else {
369                for parent in cell.value.parents.values() {
370                    parent.validate_written(&self.row).map_err(Error::Merge)?;
371                }
372            }
373            Ok(())
374        };
375        match &self.values {
376            LossValues::Cell { column, cell: value } => cell(column, value),
377            LossValues::Row(cells) => cells.iter().try_for_each(|(n, c)| cell(n, c)),
378        }
379    }
380
381    /// The writes this loss names, which a snapshot carrying it must cover.
382    pub(crate) fn named_writes(&self) -> Vec<WriteId> {
383        let mut writes: Vec<WriteId> = match &self.values {
384            LossValues::Cell { cell, .. } => vec![cell.write],
385            LossValues::Row(cells) => cells.values().map(|cell| cell.write).collect(),
386        };
387        match self.cause {
388            LossCause::Write(write)
389            | LossCause::Excluded { write, .. }
390            | LossCause::NotAuthorized { write, .. } => writes.push(write),
391            LossCause::Dependency { write, ref sources } => {
392                writes.push(write);
393                writes.extend(sources.iter().map(|s| s.write));
394            }
395            _ => {}
396        }
397        writes
398    }
399}
400
401/// A dependent change's source: a change at the same row (its generation,
402/// setters and execution sources), or a foreign-key cause in its own write.
403pub(crate) fn dependency_source(row: &RowId, write: WriteId, source: &ChangeId) -> bool {
404    source.write == write || (source.row.key == row.key && source.row.audience == row.audience)
405}
406
407#[cfg(test)]
408#[path = "loss_tests.rs"]
409mod tests;