-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathline.rs
More file actions
542 lines (472 loc) · 16.7 KB
/
line.rs
File metadata and controls
542 lines (472 loc) · 16.7 KB
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use alloc::borrow::Cow;
use alloc::rc::Rc;
use alloc::string::String;
use alloc::vec::Vec;
use serde::Deserialize;
use serde::de::{Error, IgnoredAny, VariantAccess, Visitor};
use serde_with::{DisplayFromStr, serde_as};
use crate::bson;
use crate::error::PowerSyncError;
use super::Checksum;
use super::bucket_priority::BucketPriority;
/// While we would like to always borrow strings for efficiency, that's not consistently possible.
/// With the JSON decoder, borrowing from input data is only possible when the string contains no
/// escape sequences (otherwise, the string is not a direct view of input data and we need an
/// internal copy).
pub type SyncLineStr<'a> = Cow<'a, str>;
#[derive(Clone, Copy)]
pub enum SyncLineSource<'a> {
/// Sync lines that have been decoded from JSON.
Text(&'a str),
/// Sync lines that have been decoded from BSON.
Binary(&'a [u8]),
}
impl<'a> SyncLineSource<'a> {
pub fn len(&self) -> usize {
match self {
SyncLineSource::Text(text) => text.len(),
SyncLineSource::Binary(binary) => binary.len(),
}
}
}
pub struct SyncLineWithSource<'a> {
pub source: SyncLineSource<'a>,
pub line: SyncLine<'a>,
}
impl<'a> SyncLineWithSource<'a> {
pub fn from_text(source: &'a str) -> Result<Self, PowerSyncError> {
let line = serde_json::from_str(source)
.map_err(|e| PowerSyncError::sync_protocol_error("invalid text line", e))?;
Ok(SyncLineWithSource {
source: SyncLineSource::Text(source),
line,
})
}
pub fn from_binary(source: &'a [u8]) -> Result<Self, PowerSyncError> {
let line = bson::from_bytes(source)
.map_err(|e| PowerSyncError::sync_protocol_error("invalid binary line", e))?;
Ok(SyncLineWithSource {
source: SyncLineSource::Binary(source),
line,
})
}
}
#[derive(Debug)]
pub enum SyncLine<'a> {
Checkpoint(Checkpoint<'a>),
CheckpointDiff(CheckpointDiff<'a>),
CheckpointComplete(CheckpointComplete),
CheckpointPartiallyComplete(CheckpointPartiallyComplete),
Data(DataLine<'a>),
KeepAlive(TokenExpiresIn),
UnknownSyncLine,
}
impl<'de> Deserialize<'de> for SyncLine<'de> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct SyncLineVisitor;
impl<'de> Visitor<'de> for SyncLineVisitor {
type Value = SyncLine<'de>;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(formatter, "a sync line")
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: serde::de::EnumAccess<'de>,
{
let (name, payload) = data.variant::<&'de str>()?;
Ok(match name {
"checkpoint" => SyncLine::Checkpoint(payload.newtype_variant::<Checkpoint>()?),
"checkpoint_diff" => {
SyncLine::CheckpointDiff(payload.newtype_variant::<CheckpointDiff>()?)
}
"checkpoint_complete" => SyncLine::CheckpointComplete(
payload.newtype_variant::<CheckpointComplete>()?,
),
"partial_checkpoint_complete" => SyncLine::CheckpointPartiallyComplete(
payload.newtype_variant::<CheckpointPartiallyComplete>()?,
),
"data" => SyncLine::Data(payload.newtype_variant::<DataLine>()?),
"token_expires_in" => {
SyncLine::KeepAlive(payload.newtype_variant::<TokenExpiresIn>()?)
}
_ => {
payload.newtype_variant::<IgnoredAny>()?;
SyncLine::UnknownSyncLine
}
})
}
}
deserializer.deserialize_enum("SyncLine", &[], SyncLineVisitor)
}
}
#[serde_as]
#[derive(Deserialize, Debug)]
pub struct Checkpoint<'a> {
#[serde_as(as = "DisplayFromStr")]
pub last_op_id: i64,
#[serde(default)]
#[serde_as(as = "Option<DisplayFromStr>")]
pub write_checkpoint: Option<i64>,
#[serde(borrow)]
pub buckets: Vec<BucketChecksum<'a>>,
#[serde(default, borrow)]
pub streams: Vec<StreamDescription<'a>>,
}
#[derive(Deserialize, Debug)]
pub struct StreamDescription<'a> {
pub name: SyncLineStr<'a>,
pub is_default: bool,
pub errors: Rc<Vec<StreamSubscriptionError>>,
}
#[derive(Deserialize, Debug)]
pub struct StreamSubscriptionError {
pub subscription: StreamSubscriptionErrorCause,
pub message: String,
}
/// The concrete stream subscription that has caused an error.
#[derive(Debug)]
pub enum StreamSubscriptionErrorCause {
/// The error is caused by the stream being subscribed to by default (i.e., no parameters).
Default,
/// The error is caused by an explicit subscription (e.g. due to invalid parameters).
///
/// The inner value is the index into [StreamSubscriptionRequest::subscriptions] of the
/// faulty subscription.
ExplicitSubscription(usize),
}
impl<'de> Deserialize<'de> for StreamSubscriptionErrorCause {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct CauseVisitor;
impl<'de> Visitor<'de> for CauseVisitor {
type Value = StreamSubscriptionErrorCause;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(formatter, "default or index")
}
fn visit_str<E>(self, _v: &str) -> Result<Self::Value, E>
where
E: Error,
{
return Ok(StreamSubscriptionErrorCause::Default);
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: Error,
{
return Ok(StreamSubscriptionErrorCause::ExplicitSubscription(
v as usize,
));
}
fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
where
E: Error,
{
return Ok(StreamSubscriptionErrorCause::ExplicitSubscription(
v as usize,
));
}
}
deserializer.deserialize_any(CauseVisitor)
}
}
#[serde_as]
#[derive(Deserialize, Debug)]
pub struct CheckpointDiff<'a> {
#[serde_as(as = "DisplayFromStr")]
pub last_op_id: i64,
#[serde(borrow)]
pub updated_buckets: Vec<BucketChecksum<'a>>,
#[serde(borrow)]
pub removed_buckets: Vec<SyncLineStr<'a>>,
#[serde_as(as = "Option<DisplayFromStr>")]
pub write_checkpoint: Option<i64>,
}
#[derive(Deserialize, Debug)]
pub struct CheckpointComplete {
// #[serde(deserialize_with = "deserialize_string_to_i64")]
// pub last_op_id: i64,
}
#[derive(Deserialize, Debug)]
pub struct CheckpointPartiallyComplete {
// #[serde(deserialize_with = "deserialize_string_to_i64")]
// pub last_op_id: i64,
pub priority: BucketPriority,
}
#[serde_as]
#[derive(Deserialize, Debug)]
pub struct BucketChecksum<'a> {
#[serde(borrow)]
pub bucket: SyncLineStr<'a>,
pub checksum: Checksum,
#[serde(default)]
pub priority: Option<BucketPriority>,
#[serde(default)]
pub count: Option<i64>,
#[serde(default)]
pub subscriptions: Rc<Vec<BucketSubscriptionReason>>,
// #[serde(default)]
// #[serde(deserialize_with = "deserialize_optional_string_to_i64")]
// pub last_op_id: Option<i64>,
}
/// The reason for why a bucket was included in a checkpoint.
#[derive(Debug)]
pub enum BucketSubscriptionReason {
/// A bucket was created from a default stream.
///
/// The inner value is the index of the stream in [Checkpoint::streams].
DerivedFromDefaultStream(usize),
/// A bucket was created for a subscription id we've explicitly requested in the sync request.
///
/// The inner value is the index of the stream in [StreamSubscriptionRequest::subscriptions].
DerivedFromExplicitSubscription(usize),
}
impl<'de> Deserialize<'de> for BucketSubscriptionReason {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct MyVisitor;
const VARIANTS: &'static [&'static str] = &["default", "sub"];
impl<'de> Visitor<'de> for MyVisitor {
type Value = BucketSubscriptionReason;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(formatter, "a subscription reason")
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: serde::de::EnumAccess<'de>,
{
let (key, variant) = data.variant::<&'de str>()?;
Ok(match key {
"default" => BucketSubscriptionReason::DerivedFromDefaultStream(
variant.newtype_variant()?,
),
"sub" => BucketSubscriptionReason::DerivedFromExplicitSubscription(
variant.newtype_variant()?,
),
other => return Err(A::Error::unknown_variant(other, VARIANTS)),
})
}
}
deserializer.deserialize_enum("BucketSubscriptionReason", VARIANTS, MyVisitor)
}
}
#[derive(Deserialize, Debug)]
pub struct DataLine<'a> {
#[serde(borrow)]
pub bucket: SyncLineStr<'a>,
pub data: Vec<OplogEntry<'a>>,
// #[serde(default)]
// pub has_more: bool,
// #[serde(default, borrow)]
// pub after: Option<SyncLineStr<'a>>,
// #[serde(default, borrow)]
// pub next_after: Option<SyncLineStr<'a>>,
}
#[serde_as]
#[derive(Deserialize, Debug)]
pub struct OplogEntry<'a> {
pub checksum: Checksum,
#[serde_as(as = "DisplayFromStr")]
pub op_id: i64,
pub op: OpType,
#[serde(default, borrow)]
pub object_id: Option<SyncLineStr<'a>>,
#[serde(default, borrow)]
pub object_type: Option<SyncLineStr<'a>>,
#[serde(default, borrow)]
pub subkey: Option<SyncLineStr<'a>>,
#[serde(default, borrow)]
pub data: Option<OplogData<'a>>,
}
#[derive(Debug)]
pub enum OplogData<'a> {
/// A string encoding a well-formed JSON object representing values of the row.
Json { data: Cow<'a, str> },
// BsonDocument { data: Cow<'a, [u8]> },
}
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpType {
CLEAR,
MOVE,
PUT,
REMOVE,
}
#[repr(transparent)]
#[derive(Deserialize, Debug, Clone, Copy)]
pub struct TokenExpiresIn(pub i32);
impl TokenExpiresIn {
pub fn is_expired(self) -> bool {
self.0 <= 0
}
pub fn should_prefetch(self) -> bool {
!self.is_expired() && self.0 <= 30
}
}
impl<'a, 'de: 'a> Deserialize<'de> for OplogData<'a> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
// For now, we will always get oplog data as a string. In the future, there may be the
// option of the sync service sending BSON-encoded data lines too, but that's not relevant
// for now.
return Ok(OplogData::Json {
data: Deserialize::deserialize(deserializer)?,
});
}
}
#[cfg(test)]
mod tests {
use alloc::string::ToString;
use super::*;
fn deserialize(source: &'_ str) -> SyncLine<'_> {
serde_json::from_str(source).expect("Should have deserialized")
}
#[test]
fn parse_token_expires_in() {
assert!(matches!(
deserialize(r#"{"token_expires_in": 123}"#),
SyncLine::KeepAlive(TokenExpiresIn(123))
));
}
#[test]
fn parse_checkpoint() {
assert!(matches!(
deserialize(r#"{"checkpoint": {"last_op_id": "10", "buckets": []}}"#),
SyncLine::Checkpoint(Checkpoint {
last_op_id: 10,
write_checkpoint: None,
buckets: _,
streams: _,
})
));
let SyncLine::Checkpoint(checkpoint) = deserialize(
r#"{"checkpoint": {"last_op_id": "10", "buckets": [{"bucket": "a", "checksum": 10}]}}"#,
) else {
panic!("Expected checkpoint");
};
assert_eq!(checkpoint.buckets.len(), 1);
let bucket = &checkpoint.buckets[0];
assert_eq!(bucket.bucket, "a");
assert_eq!(bucket.checksum, 10u32.into());
assert_eq!(bucket.priority, None);
let SyncLine::Checkpoint(checkpoint) = deserialize(
r#"{"checkpoint": {"last_op_id": "10", "buckets": [{"bucket": "a", "priority": 1, "checksum": 10}]}}"#,
) else {
panic!("Expected checkpoint");
};
assert_eq!(checkpoint.buckets.len(), 1);
let bucket = &checkpoint.buckets[0];
assert_eq!(bucket.bucket, "a");
assert_eq!(bucket.checksum, 10u32.into());
assert_eq!(bucket.priority, Some(BucketPriority { number: 1 }));
assert!(matches!(
deserialize(
r#"{"checkpoint":{"write_checkpoint":null,"last_op_id":"1","buckets":[{"bucket":"a","checksum":0,"priority":3,"count":1}]}}"#
),
SyncLine::Checkpoint(Checkpoint {
last_op_id: 1,
write_checkpoint: None,
buckets: _,
streams: _,
})
));
}
#[test]
fn parse_checkpoint_diff() {
let SyncLine::CheckpointDiff(diff) = deserialize(
r#"{"checkpoint_diff": {"last_op_id": "10", "buckets": [], "updated_buckets": [], "removed_buckets": [], "write_checkpoint": null}}"#,
) else {
panic!("Expected checkpoint diff")
};
assert_eq!(diff.updated_buckets.len(), 0);
assert_eq!(diff.removed_buckets.len(), 0);
}
#[test]
fn parse_checkpoint_diff_escape() {
let SyncLine::CheckpointDiff(diff) = deserialize(
r#"{"checkpoint_diff": {"last_op_id": "10", "buckets": [], "updated_buckets": [], "removed_buckets": ["foo\""], "write_checkpoint": null}}"#,
) else {
panic!("Expected checkpoint diff")
};
assert_eq!(diff.removed_buckets[0], "foo\"");
}
#[test]
fn parse_checkpoint_diff_no_write_checkpoint() {
let SyncLine::CheckpointDiff(_diff) = deserialize(
r#"{"checkpoint_diff":{"last_op_id":"12","updated_buckets":[{"bucket":"a","count":12,"checksum":0,"priority":3}],"removed_buckets":[]}}"#,
) else {
panic!("Expected checkpoint diff")
};
}
#[test]
fn parse_checkpoint_complete() {
assert!(matches!(
deserialize(r#"{"checkpoint_complete": {"last_op_id": "10"}}"#),
SyncLine::CheckpointComplete(CheckpointComplete {
// last_op_id: 10
})
));
}
#[test]
fn parse_checkpoint_partially_complete() {
assert!(matches!(
deserialize(r#"{"partial_checkpoint_complete": {"last_op_id": "10", "priority": 1}}"#),
SyncLine::CheckpointPartiallyComplete(CheckpointPartiallyComplete {
//last_op_id: 10,
priority: BucketPriority { number: 1 }
})
));
}
#[test]
fn parse_data() {
let SyncLine::Data(data) = deserialize(
r#"{"data": {
"bucket": "bkt",
"data": [{"checksum":10,"op_id":"1","object_id":"test","object_type":"users","op":"PUT","subkey":null,"data":"{\"name\":\"user 0\",\"email\":\"0@example.org\"}"}],
"after": null,
"next_after": null}
}"#,
) else {
panic!("Expected data line")
};
assert_eq!(data.bucket, "bkt");
assert_eq!(data.data.len(), 1);
let entry = &data.data[0];
assert_eq!(entry.checksum, 10u32.into());
assert!(matches!(
&data.data[0],
OplogEntry {
checksum: _,
op_id: 1,
object_id: Some(_),
object_type: Some(_),
op: OpType::PUT,
subkey: None,
data: _,
}
));
}
#[test]
fn parse_unknown() {
assert!(matches!(
deserialize("{\"foo\": {}}"),
SyncLine::UnknownSyncLine
));
assert!(matches!(
deserialize("{\"foo\": 123}"),
SyncLine::UnknownSyncLine
));
}
#[test]
fn parse_invalid_duplicate_key() {
let e = serde_json::from_str::<SyncLine>(r#"{"foo": {}, "bar": {}}"#).unwrap_err();
assert_eq!(e.to_string(), "expected value at line 1 column 10");
}
}