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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::sync::Arc;

use bitflags::bitflags;
use spacetimedb_sats::buffer::{BufReader, BufWriter, DecodeError};
use thiserror::Error;

use crate::{
    error,
    varint::{decode_varint, encode_varint},
    Encode, Varchar,
};

// Re-export so we get a hyperlink in rustdocs by default
pub use spacetimedb_primitives::TableId;

/// A visitor useful to implement stateful [`Decoder`]s of [`Txdata`] payloads.
pub trait Visitor {
    type Error: From<DecodeError>;
    /// The type corresponding to one element in [`Ops::rowdata`].
    type Row;

    /// Called for each row in each [`Ops`] of a [`Mutations`]' `inserts`.
    ///
    /// The implementation is expected to determine the appropriate schema based
    /// on the supplied [`TableId`], and to decode the row data from the
    /// supplied [`BufReader`].
    ///
    /// The reader's position is assumed to be at the start of the next row
    /// after the method returns.
    fn visit_insert<'a, R: BufReader<'a>>(
        &mut self,
        table_id: TableId,
        reader: &mut R,
    ) -> Result<Self::Row, Self::Error>;

    /// Called for each row in each [`Ops`] of a [`Mutations`]' `deletes`.
    ///
    /// Similar to [`Self::visit_insert`], but allows the visitor to determine
    /// the start of the next section in a [`Mutations`] payload.
    fn visit_delete<'a, R: BufReader<'a>>(
        &mut self,
        table_id: TableId,
        reader: &mut R,
    ) -> Result<Self::Row, Self::Error>;

    /// Called for each [`TableId`] encountered in the `truncates` section of
    /// a [`Mutations`].
    ///
    /// The default implementation does nothing.
    fn visit_truncate(&mut self, _table_id: TableId) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Called for each [`Txdata`] record in a [`crate::Commit`].
    ///
    /// The default implementation does nothing.
    fn visit_tx_start(&mut self, _offset: u64) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Called after each successful decode of a [`Txdata`] payload.
    ///
    /// The default implementation does nothing.
    fn visit_tx_end(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Called for each [`Inputs`] encountered in a [`Txdata`] payload.
    ///
    /// The default implementation does nothing.
    fn visit_inputs(&mut self, _inputs: &Inputs) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Called for each [`Outputs`] encountered in a [`Txdata`] payload.
    ///
    /// The default implementation does nothing.
    fn visit_outputs(&mut self, _outputs: &Outputs) -> Result<(), Self::Error> {
        Ok(())
    }
}

bitflags! {
    #[derive(Clone, Copy)]
    pub struct Flags: u8 {
        const HAVE_INPUTS    = 0b10000000;
        const HAVE_OUTPUTS   = 0b01000000;
        const HAVE_MUTATIONS = 0b00100000;
    }
}

/// The canonical payload format of a [`crate::Commitlog`].
///
/// This type may eventually be defined in the core datastore crate.
#[derive(Clone, Debug, PartialEq)]
pub struct Txdata<T> {
    pub inputs: Option<Inputs>,
    pub outputs: Option<Outputs>,
    pub mutations: Option<Mutations<T>>,
}

impl<T> Txdata<T> {
    /// `true` if `self` contains neither inputs, outputs nor mutations.
    pub fn is_empty(&self) -> bool {
        self.inputs.is_none()
            && self.outputs.is_none()
            && self.mutations.as_ref().map(Mutations::is_empty).unwrap_or(true)
    }
}

impl<T: Encode> Txdata<T> {
    pub const VERSION: u8 = 0;

    pub fn encode(&self, buf: &mut impl BufWriter) {
        let mut flags = Flags::empty();
        flags.set(Flags::HAVE_INPUTS, self.inputs.is_some());
        flags.set(Flags::HAVE_OUTPUTS, self.outputs.is_some());
        flags.set(Flags::HAVE_MUTATIONS, self.mutations.is_some());

        buf.put_u8(flags.bits());
        if let Some(inputs) = &self.inputs {
            inputs.encode(buf);
        }
        if let Some(outputs) = &self.outputs {
            outputs.encode(buf);
        }
        if let Some(mutations) = &self.mutations {
            mutations.encode(buf)
        }
    }

    pub fn decode<'a, V, R>(visitor: &mut V, reader: &mut R) -> Result<Self, V::Error>
    where
        V: Visitor<Row = T>,
        R: BufReader<'a>,
    {
        let flags = Flags::from_bits_retain(reader.get_u8()?);
        let inputs = flags
            .contains(Flags::HAVE_INPUTS)
            .then(|| Inputs::decode(reader))
            .transpose()?;
        if let Some(inputs) = &inputs {
            visitor.visit_inputs(inputs)?;
        }

        let outputs = flags
            .contains(Flags::HAVE_OUTPUTS)
            .then(|| Outputs::decode(reader))
            .transpose()?;
        if let Some(outputs) = &outputs {
            visitor.visit_outputs(outputs)?;
        }

        let mutations = flags
            .contains(Flags::HAVE_MUTATIONS)
            .then(|| Mutations::decode(visitor, reader))
            .transpose()?;

        Ok(Self {
            inputs,
            outputs,
            mutations,
        })
    }
}

/// The inputs of a transaction, i.e. the name and arguments of a reducer call.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
pub struct Inputs {
    pub reducer_name: Arc<Varchar<255>>,
    pub reducer_args: Arc<[u8]>,
    // TODO: `reducer_args` should be a `ProductValue`, which
    // requires `Decoder` to be able to resolve the argument
    // type by `reducer_name`.
    //
    // We can do that once modules are stored in the database
    // itself, or the database is otherwise able to load the
    // module info.
    //
    // At that point, we can also remove the length prefix of
    // `Inputs`.
}

impl Inputs {
    pub fn encode(&self, buf: &mut impl BufWriter) {
        let slen = self.reducer_name.len() as u8;
        let len = /* slen */ 1 + slen as usize + self.reducer_args.len();
        buf.put_u32(len as u32);
        buf.put_u8(slen);
        buf.put_slice(self.reducer_name.as_bytes());
        buf.put_slice(&self.reducer_args);
    }

    pub fn decode<'a, R: BufReader<'a>>(reader: &mut R) -> Result<Self, DecodeError> {
        let len = reader.get_u32()?;
        let slen = reader.get_u8()?;
        let reducer_name = {
            let bytes = reader.get_slice(slen as usize)?;
            Varchar::from_str(std::str::from_utf8(bytes)?)
                .expect("slice len cannot be > 255")
                .into()
        };
        let reducer_args = reader.get_slice(len as usize - /* slen */ 1 - slen as usize)?.into();

        Ok(Self {
            reducer_name,
            reducer_args,
        })
    }
}

/// The outputs of a transaction.
///
/// The only currently possible output of a transaction is a string
/// representation of an `Err` return value of a reducer.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
pub struct Outputs {
    // TODO: We may want a `Cow`-backed variant of `Varchar` for this.
    pub reducer_output: Arc<Varchar<255>>,
}

impl Outputs {
    pub fn encode(&self, buf: &mut impl BufWriter) {
        let slen = self.reducer_output.len() as u8;
        buf.put_u8(slen);
        buf.put_slice(self.reducer_output.as_bytes());
    }

    pub fn decode<'a, R: BufReader<'a>>(reader: &mut R) -> Result<Self, DecodeError> {
        let slen = reader.get_u8()?;
        let reducer_output = {
            let bytes = reader.get_slice(slen as usize)?;
            Varchar::from_str(std::str::from_utf8(bytes)?).unwrap().into()
        };

        Ok(Self { reducer_output })
    }
}

/// Mutations of the data store performed by a transaction.
///
/// All operations are supposed to be **mutually exclusive**.
///
/// Even though not enforced, each kind of mutation should not contain duplicate
/// [`TableId`]s.
#[derive(Clone, Debug, PartialEq)]
pub struct Mutations<T> {
    /// Rows inserted.
    pub inserts: Box<[Ops<T>]>,
    /// Rows deleted.
    pub deletes: Box<[Ops<T>]>,
    /// Truncated tables.
    pub truncates: Box<[TableId]>,
}

impl<T> Mutations<T> {
    /// `true` if `self` contains no mutations at all.
    pub fn is_empty(&self) -> bool {
        self.inserts.is_empty() && self.deletes.is_empty() && self.truncates.is_empty()
    }
}

impl<T: Encode> Mutations<T> {
    /// Encode `self` in the canonical format to the given buffer.
    pub fn encode(&self, buf: &mut impl BufWriter) {
        encode_varint(self.inserts.len(), buf);
        for ops in self.inserts.iter() {
            ops.encode(buf);
        }
        encode_varint(self.deletes.len(), buf);
        for ops in self.deletes.iter() {
            ops.encode(buf);
        }
        encode_varint(self.truncates.len(), buf);
        for TableId(table_id) in self.truncates.iter() {
            buf.put_u32(*table_id);
        }
    }

    /// Decode `Self` from the given buffer.
    pub fn decode<'a, V, R>(visitor: &mut V, reader: &mut R) -> Result<Self, V::Error>
    where
        V: Visitor<Row = T>,
        R: BufReader<'a>,
    {
        let n = decode_varint(reader)?;
        let mut inserts = Vec::with_capacity(n);
        for _ in 0..n {
            let table_id = reader.get_u32().map(TableId)?;
            let m = decode_varint(reader)?;
            let mut rowdata = Vec::with_capacity(m);
            for _ in 0..m {
                let row = visitor.visit_insert(table_id, reader)?;
                rowdata.push(row);
            }
            inserts.push(Ops {
                table_id,
                rowdata: rowdata.into(),
            });
        }

        let n = decode_varint(reader)?;
        let mut deletes = Vec::with_capacity(n);
        for _ in 0..n {
            let table_id = reader.get_u32().map(TableId)?;
            let m = decode_varint(reader)?;
            let mut rowdata = Vec::with_capacity(m);
            for _ in 0..m {
                let row = visitor.visit_delete(table_id, reader)?;
                rowdata.push(row);
            }
            deletes.push(Ops {
                table_id,
                rowdata: rowdata.into(),
            });
        }

        let n = decode_varint(reader)?;
        let mut truncates = Vec::with_capacity(n);
        for _ in 0..n {
            let table_id = reader.get_u32().map(TableId)?;
            visitor.visit_truncate(table_id)?;
            truncates.push(table_id);
        }

        Ok(Self {
            inserts: inserts.into(),
            deletes: deletes.into(),
            truncates: truncates.into(),
        })
    }
}

impl<T: Encode> Encode for Txdata<T> {
    fn encode_record<W: BufWriter>(&self, writer: &mut W) {
        self.encode(writer)
    }
}

/// An operation (insert or delete) on a given table.
#[derive(Clone, Debug, PartialEq)]
pub struct Ops<T> {
    /// The table this operation applies to.
    pub table_id: TableId,
    /// The list of full rows inserted or deleted.
    pub rowdata: Arc<[T]>,
}

impl<T: Encode> Ops<T> {
    /// Encode `self` in the canonical format to the given buffer.
    pub fn encode(&self, buf: &mut impl BufWriter) {
        buf.put_u32(self.table_id.0);
        encode_varint(self.rowdata.len(), buf);
        for row in self.rowdata.iter() {
            Encode::encode_record(row, buf);
        }
    }
}

#[derive(Debug, Error)]
pub enum DecoderError<V> {
    #[error("unsupported version: {given} supported={supported}")]
    UnsupportedVersion { supported: u8, given: u8 },
    #[error(transparent)]
    Decode(#[from] DecodeError),
    #[error(transparent)]
    Visitor(V),
    #[error(transparent)]
    Traverse(#[from] error::Traversal),
}

/// A free standing implementation of [`crate::Decoder::decode_record`], which
/// drives the supplied [`Visitor`].
///
/// Simplifies decoder implementations operating on [`Txdata`], as the
/// implementation only needs to care about managing the [`Visitor`] (which may
/// be behind a lock).
pub fn decode_record_fn<'a, V, R>(
    visitor: &mut V,
    version: u8,
    tx_offset: u64,
    reader: &mut R,
) -> Result<Txdata<V::Row>, DecoderError<V::Error>>
where
    V: Visitor,
    V::Row: Encode,
    R: BufReader<'a>,
{
    if version > Txdata::<V::Row>::VERSION {
        return Err(DecoderError::UnsupportedVersion {
            supported: Txdata::<V::Row>::VERSION,
            given: version,
        });
    }
    visitor.visit_tx_start(tx_offset).map_err(DecoderError::Visitor)?;
    let record = Txdata::decode(visitor, reader).map_err(DecoderError::Visitor)?;
    visitor.visit_tx_end().map_err(DecoderError::Visitor)?;

    Ok(record)
}

#[cfg(test)]
mod tests {
    use super::*;
    use once_cell::sync::Lazy;
    use proptest::prelude::*;
    use spacetimedb_sats::{product, AlgebraicType, ProductType, ProductValue};

    fn gen_table_id() -> impl Strategy<Value = TableId> {
        any::<u32>().prop_map(TableId)
    }

    fn gen_ops(pv: ProductValue) -> impl Strategy<Value = Ops<ProductValue>> {
        (gen_table_id(), prop::collection::vec(Just(pv), 1..10)).prop_map(|(table_id, rowdata)| Ops {
            table_id,
            rowdata: rowdata.into(),
        })
    }

    fn gen_mutations(pv: ProductValue) -> impl Strategy<Value = Mutations<ProductValue>> {
        (
            prop::collection::vec(gen_ops(pv.clone()), 0..10),
            prop::collection::vec(gen_ops(pv.clone()), 0..10),
            prop::collection::vec(gen_table_id(), 0..10),
        )
            .prop_map(|(inserts, deletes, truncates)| Mutations {
                inserts: inserts.into(),
                deletes: deletes.into(),
                truncates: truncates.into(),
            })
    }

    fn gen_txdata(pv: ProductValue) -> impl Strategy<Value = Txdata<ProductValue>> {
        (
            prop::option::of(any::<Inputs>()),
            prop::option::of(any::<Outputs>()),
            prop::option::of(gen_mutations(pv)),
        )
            .prop_map(|(inputs, outputs, mutations)| Txdata {
                inputs,
                outputs,
                mutations,
            })
    }

    static SOME_PV: Lazy<ProductValue> = Lazy::new(|| product![42u64, "kermit", 4u32, 2u32, 18u32]);
    static SOME_PV_TY: Lazy<ProductType> = Lazy::new(|| {
        ProductType::from([
            ("id", AlgebraicType::U64),
            ("name", AlgebraicType::String),
            ("x", AlgebraicType::U32),
            ("y", AlgebraicType::U32),
            ("z", AlgebraicType::U32),
        ])
    });

    struct MockVisitor;

    impl Visitor for MockVisitor {
        type Error = DecodeError;
        type Row = ProductValue;

        fn visit_insert<'a, R: BufReader<'a>>(
            &mut self,
            _table_id: TableId,
            reader: &mut R,
        ) -> Result<Self::Row, Self::Error> {
            ProductValue::decode(&SOME_PV_TY, reader)
        }

        fn visit_delete<'a, R: BufReader<'a>>(
            &mut self,
            _table_id: TableId,
            reader: &mut R,
        ) -> Result<Self::Row, Self::Error> {
            ProductValue::decode(&SOME_PV_TY, reader)
        }
    }

    proptest! {
        #[test]
        fn prop_inputs_roundtrip(inputs in any::<Inputs>()) {
            let mut buf = Vec::new();
            inputs.encode(&mut buf);
            assert_eq!(inputs, Inputs::decode(&mut buf.as_slice()).unwrap());
        }

        #[test]
        fn prop_outputs_roundtrip(outputs in any::<Outputs>()) {
            let mut buf = Vec::new();
            outputs.encode(&mut buf);
            assert_eq!(outputs, Outputs::decode(&mut buf.as_slice()).unwrap());
        }

        #[test]
        fn prop_mutations_roundtrip(muts in gen_mutations(SOME_PV.clone())) {
            let mut buf = Vec::new();
            muts.encode(&mut buf);
            assert_eq!(muts, Mutations::decode(&mut MockVisitor, &mut buf.as_slice()).unwrap());
        }

        #[test]
        fn prop_txdata_roundtrip(txdata in gen_txdata(SOME_PV.clone())) {
            let mut buf = Vec::new();
            txdata.encode(&mut buf);
            assert_eq!(txdata, Txdata::decode(&mut MockVisitor, &mut buf.as_slice()).unwrap());
        }
    }
}