willow-data-model 0.2.0

The datatypes of Willow, an eventually consistent data store with improved distributed deletion.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use compact_u64::{CompactU64, EncodingWidth, Tag, TagWidth};
use ufotofu::{BulkConsumer, BulkProducer};
use ufotofu_codec::{
    Blame, DecodableCanonic, DecodeError, Encodable, EncodableKnownSize, EncodableSync,
    RelativeDecodable, RelativeDecodableCanonic, RelativeDecodableSync, RelativeEncodable,
    RelativeEncodableKnownSize, RelativeEncodableSync,
};
use willow_encoding::is_bitflagged;

use crate::{
    grouping::{Area, AreaSubspace, Range, RangeEnd},
    Path, SubspaceId,
};

impl<const MCL: usize, const MCC: usize, const MPL: usize, S>
    RelativeEncodable<Area<MCL, MCC, MPL, S>> for Area<MCL, MCC, MPL, S>
where
    S: SubspaceId + Encodable,
{
    /// Encodes this [`Area`] relative to another [`Area`] which [includes](https://willowprotocol.org/specs/grouping-entries/index.html#area_include_area) it.
    ///
    /// [Definition](https://willowprotocol.org/specs/encodings/index.html#enc_area_in_area).
    async fn relative_encode<C>(
        &self,
        consumer: &mut C,
        r: &Area<MCL, MCC, MPL, S>,
    ) -> Result<(), C::Error>
    where
        C: BulkConsumer<Item = u8>,
    {
        if !r.includes_area(self) {
            panic!("Tried to encode an area relative to a area it is not included by")
        }

        let start_diff = core::cmp::min(
            self.times().start - r.times().start,
            u64::from(&r.times().end) - self.times().start,
        );

        let end_diff = core::cmp::min(
            u64::from(&self.times().end) - r.times().start,
            u64::from(&r.times().end) - u64::from(&self.times().end),
        );

        let mut header = 0;

        if self.subspace() != r.subspace() {
            header |= 0b1000_0000;
        }

        if self.times().end == RangeEnd::Open {
            header |= 0b0100_0000;
        }

        if start_diff == self.times().start - r.times().start {
            header |= 0b0010_0000;
        }

        if self.times().end != RangeEnd::Open
            && end_diff == u64::from(&self.times().end) - r.times().start
        {
            header |= 0b0001_0000;
        }

        let start_diff_tag = Tag::min_tag(start_diff, TagWidth::two());
        let end_diff_tag = Tag::min_tag(end_diff, TagWidth::two());

        header |= start_diff_tag.data_at_offset(4);
        header |= end_diff_tag.data_at_offset(6);

        consumer.consume(header).await?;

        match (&self.subspace(), &r.subspace()) {
            (AreaSubspace::Any, AreaSubspace::Any) => {} // Same subspace
            (AreaSubspace::Id(_), AreaSubspace::Id(_)) => {} // Same subspace
            (AreaSubspace::Id(subspace), AreaSubspace::Any) => {
                subspace.encode(consumer).await?;
            }
            (AreaSubspace::Any, AreaSubspace::Id(_)) => {
                unreachable!(
                    "We should have already rejected an area not included by another area!"
                )
            }
        }

        self.path().relative_encode(consumer, r.path()).await?;

        CompactU64(start_diff)
            .relative_encode(consumer, &start_diff_tag.encoding_width())
            .await?;

        if self.times().end != RangeEnd::Open {
            CompactU64(end_diff)
                .relative_encode(consumer, &end_diff_tag.encoding_width())
                .await?;
        }

        Ok(())
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize, S>
    RelativeDecodable<Area<MCL, MCC, MPL, S>, Blame> for Area<MCL, MCC, MPL, S>
where
    S: SubspaceId + DecodableCanonic,
    Blame: From<S::ErrorReason> + From<S::ErrorCanonic>,
{
    /// Decodes an [`Area`] relative to another [`Area`] which [includes](https://willowprotocol.org/specs/grouping-entries/index.html#area_include_area) it.
    ///
    /// Will return an error if the encoding has not been produced by the corresponding encoding function.
    ///
    /// [Definition](https://willowprotocol.org/specs/encodings/index.html#enc_area_in_area).
    async fn relative_decode<P>(
        producer: &mut P,
        r: &Area<MCL, MCC, MPL, S>,
    ) -> Result<Self, DecodeError<P::Final, P::Error, Blame>>
    where
        P: BulkProducer<Item = u8>,
        Self: Sized,
    {
        relative_decode_maybe_canonic::<false, MCL, MCC, MPL, S, P>(producer, r).await
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize, S>
    RelativeDecodableCanonic<Area<MCL, MCC, MPL, S>, Blame, Blame> for Area<MCL, MCC, MPL, S>
where
    S: SubspaceId + DecodableCanonic,
    Blame: From<S::ErrorReason> + From<S::ErrorCanonic>,
{
    async fn relative_decode_canonic<P>(
        producer: &mut P,
        r: &Area<MCL, MCC, MPL, S>,
    ) -> Result<Self, DecodeError<P::Final, P::Error, Blame>>
    where
        P: BulkProducer<Item = u8>,
        Self: Sized,
    {
        relative_decode_maybe_canonic::<true, MCL, MCC, MPL, S, P>(producer, r).await
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize, S>
    RelativeEncodableKnownSize<Area<MCL, MCC, MPL, S>> for Area<MCL, MCC, MPL, S>
where
    S: SubspaceId + EncodableKnownSize,
{
    fn relative_len_of_encoding(&self, r: &Area<MCL, MCC, MPL, S>) -> usize {
        if !r.includes_area(self) {
            panic!("Tried to encode an area relative to a area it is not included by")
        }

        let start_diff = core::cmp::min(
            self.times().start - r.times().start,
            u64::from(&r.times().end) - self.times().start,
        );

        let end_diff = core::cmp::min(
            u64::from(&self.times().end) - r.times().start,
            u64::from(&r.times().end) - u64::from(&self.times().end),
        );

        let start_diff_tag = Tag::min_tag(start_diff, TagWidth::two());
        let end_diff_tag = Tag::min_tag(end_diff, TagWidth::two());

        let subspace_len = match (&self.subspace(), &r.subspace()) {
            (AreaSubspace::Any, AreaSubspace::Any) => 0, // Same subspace
            (AreaSubspace::Id(_), AreaSubspace::Id(_)) => 0, // Same subspace
            (AreaSubspace::Id(subspace), AreaSubspace::Any) => subspace.len_of_encoding(),
            (AreaSubspace::Any, AreaSubspace::Id(_)) => {
                unreachable!(
                    "We should have already rejected an area not included by another area!"
                )
            }
        };

        let path_len = self.path().relative_len_of_encoding(r.path());

        let start_diff_len =
            CompactU64(start_diff).relative_len_of_encoding(&start_diff_tag.encoding_width());

        let end_diff_len = if self.times().end != RangeEnd::Open {
            CompactU64(end_diff).relative_len_of_encoding(&end_diff_tag.encoding_width())
        } else {
            0
        };

        1 + subspace_len + path_len + start_diff_len + end_diff_len
    }
}

impl<const MCL: usize, const MCC: usize, const MPL: usize, S>
    RelativeEncodableSync<Area<MCL, MCC, MPL, S>> for Area<MCL, MCC, MPL, S>
where
    S: SubspaceId + EncodableSync,
{
}

impl<const MCL: usize, const MCC: usize, const MPL: usize, S>
    RelativeDecodableSync<Area<MCL, MCC, MPL, S>, Blame> for Area<MCL, MCC, MPL, S>
where
    S: SubspaceId + DecodableCanonic,
    Blame: From<S::ErrorReason> + From<S::ErrorCanonic>,
{
}

async fn relative_decode_maybe_canonic<
    const CANONIC: bool,
    const MCL: usize,
    const MCC: usize,
    const MPL: usize,
    S,
    P,
>(
    producer: &mut P,
    r: &Area<MCL, MCC, MPL, S>,
) -> Result<Area<MCL, MCC, MPL, S>, DecodeError<P::Final, P::Error, Blame>>
where
    P: BulkProducer<Item = u8>,
    S: SubspaceId + DecodableCanonic,
    Blame: From<S::ErrorReason> + From<S::ErrorCanonic>,
{
    let header = producer.produce_item().await?;

    // Decode subspace?
    let is_subspace_encoded = is_bitflagged(header, 0);

    // Decode end value of times?
    let is_times_end_open = is_bitflagged(header, 1);

    // Add start_diff to out.get_times().start, or subtract from out.get_times().end?
    let add_start_diff = is_bitflagged(header, 2);

    // Add end_diff to out.get_times().start, or subtract from out.get_times().end?
    let add_end_diff = is_bitflagged(header, 3);

    // === Necessary to produce canonic encodings. ===
    // Verify that we don't add_end_diff when open...
    if CANONIC && add_end_diff && is_times_end_open {
        return Err(DecodeError::Other(Blame::TheirFault));
    }
    // ===============================================

    let start_time_diff_tag = Tag::from_raw(header, TagWidth::two(), 4);
    let end_time_diff_tag = Tag::from_raw(header, TagWidth::two(), 6);

    // === Necessary to produce canonic encodings. ===
    // Verify the last two bits are zero if is_times_end_open
    if CANONIC && is_times_end_open && (end_time_diff_tag.encoding_width() != EncodingWidth::one())
    {
        return Err(DecodeError::Other(Blame::TheirFault));
    }
    // ===============================================

    let subspace = if is_subspace_encoded {
        let id = if CANONIC {
            S::decode_canonic(producer)
                .await
                .map_err(DecodeError::map_other_from)?
        } else {
            S::decode(producer)
                .await
                .map_err(DecodeError::map_other_from)?
        };
        let sub = AreaSubspace::Id(id);

        // === Necessary to produce canonic encodings. ===
        // Verify that subspace wasn't needlessly encoded
        if CANONIC && &sub == r.subspace() {
            return Err(DecodeError::Other(Blame::TheirFault));
        }
        // ===============================================

        sub
    } else {
        r.subspace().clone()
    };

    // Verify that the decoded subspace is included by the reference subspace
    match (&r.subspace(), &subspace) {
        (AreaSubspace::Any, AreaSubspace::Any) => {}
        (AreaSubspace::Any, AreaSubspace::Id(_)) => {}
        (AreaSubspace::Id(_), AreaSubspace::Any) => {
            return Err(DecodeError::Other(Blame::TheirFault));
        }
        (AreaSubspace::Id(a), AreaSubspace::Id(b)) => {
            if a != b {
                return Err(DecodeError::Other(Blame::TheirFault));
            }
        }
    }

    let path = if CANONIC {
        Path::relative_decode_canonic(producer, r.path())
            .await
            .map_err(DecodeError::map_other_from)?
    } else {
        Path::relative_decode(producer, r.path())
            .await
            .map_err(DecodeError::map_other_from)?
    };

    // Verify the decoded path is prefixed by the reference path
    if !path.is_prefixed_by(r.path()) {
        return Err(DecodeError::Other(Blame::TheirFault));
    }

    let start_diff = if CANONIC {
        CompactU64::relative_decode_canonic(producer, &start_time_diff_tag)
            .await
            .map_err(DecodeError::map_other_from)?
            .0
    } else {
        CompactU64::relative_decode(producer, &start_time_diff_tag)
            .await
            .map_err(DecodeError::map_other_from)?
            .0
    };

    let start = if add_start_diff {
        r.times().start.checked_add(start_diff)
    } else {
        u64::from(&r.times().end).checked_sub(start_diff)
    }
    .ok_or(DecodeError::Other(Blame::TheirFault))?;

    // TODO: DOES THE BELOW NEED TO BE PART OF CANONIC CHECK?
    // Verify they sent correct start diff
    let expected_start_diff = core::cmp::min(
        start.checked_sub(r.times().start),
        u64::from(&r.times().end).checked_sub(start),
    )
    .ok_or(DecodeError::Other(Blame::TheirFault))?;

    if expected_start_diff != start_diff {
        return Err(DecodeError::Other(Blame::TheirFault));
    }

    if CANONIC {
        // === Necessary to produce canonic encodings. ===
        // Verify that bit 2 of the header was set correctly
        let should_add_start_diff = start_diff
            == start
                .checked_sub(r.times().start)
                .ok_or(DecodeError::Other(Blame::TheirFault))?;

        if add_start_diff != should_add_start_diff {
            return Err(DecodeError::Other(Blame::TheirFault));
        }
        // ===============================================
    }

    let end = if is_times_end_open {
        if add_end_diff {
            return Err(DecodeError::Other(Blame::TheirFault));
        }

        RangeEnd::Open
    } else {
        let end_diff = if CANONIC {
            CompactU64::relative_decode_canonic(producer, &end_time_diff_tag)
                .await
                .map_err(DecodeError::map_other_from)?
                .0
        } else {
            CompactU64::relative_decode(producer, &end_time_diff_tag)
                .await
                .map_err(DecodeError::map_other_from)?
                .0
        };

        let end = if add_end_diff {
            r.times().start.checked_add(end_diff)
        } else {
            u64::from(&r.times().end).checked_sub(end_diff)
        }
        .ok_or(DecodeError::Other(Blame::TheirFault))?;

        // Verify they sent correct end diff
        let expected_end_diff = core::cmp::min(
            end.checked_sub(r.times().start),
            u64::from(&r.times().end).checked_sub(end),
        )
        .ok_or(DecodeError::Other(Blame::TheirFault))?;

        if end_diff != expected_end_diff {
            return Err(DecodeError::Other(Blame::TheirFault));
        }

        // === Necessary to produce canonic encodings. ===
        if CANONIC {
            let should_add_end_diff = end_diff
                == end
                    .checked_sub(r.times().start)
                    .ok_or(DecodeError::Other(Blame::TheirFault))?;

            if add_end_diff != should_add_end_diff {
                return Err(DecodeError::Other(Blame::TheirFault));
            }
        }
        // ============================================

        RangeEnd::Closed(end)
    };

    let times = Range { start, end };

    // Verify the decoded time range is included by the reference time range
    if !r.times().includes_range(&times) {
        return Err(DecodeError::Other(Blame::TheirFault));
    }

    Ok(Area::new(subspace, path, times))
}