Debian Codegraph @

third_party/rust/webext-storage/src/sync/sync_tests.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 // This file tries to simulate "full syncs" - ie, from local state changing, to
6 // fetching incoming items, generating items to upload, then updating the local
7 // state (including the mirror) as a result.
8
9 use crate::api::{clear, get, set};
10 use crate::error::*;
11 use crate::schema::create_empty_sync_temp_tables;
12 use crate::sync::incoming::{apply_actions, get_incoming, plan_incoming, stage_incoming};
13 use crate::sync::outgoing::{get_outgoing, record_uploaded, stage_outgoing};
14 use crate::sync::test::new_syncable_mem_db;
15 use crate::sync::WebextRecord;
16 use interrupt_support::NeverInterrupts;
17 use rusqlite::{Connection, Row, Transaction};
18 use serde_json::json;
19 use sql_support::ConnExt;
20 use sync15::bso::{IncomingBso, IncomingContent, OutgoingBso};
21 use sync_guid::Guid;
22
23 // Here we try and simulate everything done by a "full sync", just minus the
24 // engine. Returns the records we uploaded.
25 fn do_sync(
26 tx: &Transaction<'_>,
27 incoming_payloads: &[IncomingContent<WebextRecord>],
28 ) -> Result<Vec<OutgoingBso>> {
29 info!("test do_sync() starting");
30 // First we stage the incoming in the temp tables.
31 stage_incoming(tx, incoming_payloads, &NeverInterrupts)?;
32 // Then we process them getting a Vec of (item, state), which we turn into
33 // a Vec of (item, action)
34 let actions = get_incoming(tx)?
35 .into_iter()
36 .map(|(item, state)| (item, plan_incoming(state)))
37 .collect();
38 debug!("do_sync applying {:?}", actions);
39 apply_actions(tx, actions, &NeverInterrupts)?;
40 // So we've done incoming - do outgoing.
41 stage_outgoing(tx)?;
42 let outgoing = get_outgoing(tx, &NeverInterrupts)?;
43 debug!("do_sync has outgoing {:?}", outgoing);
44 record_uploaded(
45 tx,
46 outgoing
47 .iter()
48 .map(|p| p.envelope.id.clone())
49 .collect::<Vec<Guid>>()
50 .as_slice(),
51 &NeverInterrupts,
52 )?;
53 create_empty_sync_temp_tables(tx)?;
54 info!("test do_sync() complete");
55 Ok(outgoing)
56 }
57
58 // Check *both* the mirror and local API have ended up with the specified data.
59 fn check_finished_with(conn: &Connection, ext_id: &str, val: serde_json::Value) -> Result<()> {
60 let local = get(conn, ext_id, serde_json::Value::Null)?;
61 assert_eq!(local, val);
62 let guid = get_mirror_guid(conn, ext_id)?;
63 let mirror = get_mirror_data(conn, &guid);
64 assert_eq!(mirror, DbData::Data(val.to_string()));
65 // and there should be zero items with a change counter.
66 let count = conn.query_row_and_then(
67 "SELECT COUNT(*) FROM storage_sync_data WHERE sync_change_counter != 0;",
68 [],
69 |row| row.get::<_, u32>(0),
70 )?;
71 assert_eq!(count, 0);
72 Ok(())
73 }
74
75 fn get_mirror_guid(conn: &Connection, extid: &str) -> Result<Guid> {
76 let guid = conn.query_row_and_then(
77 "SELECT m.guid FROM storage_sync_mirror m WHERE m.ext_id = ?;",
78 [extid],
79 |row| row.get::<_, Guid>(0),
80 )?;
81 Ok(guid)
82 }
83
84 #[derive(Debug, PartialEq)]
85 enum DbData {
86 NoRow,
87 NullRow,
88 Data(String),
89 }
90
91 impl DbData {
92 fn has_data(&self) -> bool {
93 matches!(self, DbData::Data(_))
94 }
95 }
96
97 fn _get(conn: &Connection, id_name: &str, expected_extid: &str, table: &str) -> DbData {
98 let sql = format!("SELECT {} as id, data FROM {}", id_name, table);
99
100 fn from_row(row: &Row<'_>) -> Result<(String, Option<String>)> {
101 Ok((row.get("id")?, row.get("data")?))
102 }
103 let mut items = conn
104 .conn()
105 .query_rows_and_then(&sql, [], from_row)
106 .expect("should work");
107 if items.is_empty() {
108 DbData::NoRow
109 } else {
110 let item = items.pop().expect("it exists");
111 assert_eq!(Guid::new(&item.0), expected_extid);
112 match item.1 {
113 None => DbData::NullRow,
114 Some(v) => DbData::Data(v),
115 }
116 }
117 }
118
119 fn get_mirror_data(conn: &Connection, expected_extid: &str) -> DbData {
120 _get(conn, "guid", expected_extid, "storage_sync_mirror")
121 }
122
123 fn get_local_data(conn: &Connection, expected_extid: &str) -> DbData {
124 _get(conn, "ext_id", expected_extid, "storage_sync_data")
125 }
126
127 fn make_incoming(
128 guid: &Guid,
129 ext_id: &str,
130 data: &serde_json::Value,
131 ) -> IncomingContent<WebextRecord> {
132 let content = json!({"id": guid, "extId": ext_id, "data": data.to_string()});
133 IncomingBso::from_test_content(content).into_content()
134 }
135
136 fn make_incoming_tombstone(guid: &Guid) -> IncomingContent<WebextRecord> {
137 IncomingBso::new_test_tombstone(guid.clone()).into_content()
138 }
139
140 #[test]
141 fn test_simple_outgoing_sync() -> Result<()> {
142 // So we are starting with an empty local store and empty server store.
143 let db = new_syncable_mem_db();
144 let conn = db.get_connection().expect("should retrieve connection");
145 let tx = conn.unchecked_transaction()?;
146 let data = json!({"key1": "key1-value", "key2": "key2-value"});
147 set(&tx, "ext-id", data.clone())?;
148 assert_eq!(do_sync(&tx, &[])?.len(), 1);
149 check_finished_with(&tx, "ext-id", data)?;
150 Ok(())
151 }
152
153 #[test]
154 fn test_simple_incoming_sync() -> Result<()> {
155 let db = new_syncable_mem_db();
156 let conn = db.get_connection().expect("should retrieve connection");
157 let tx = conn.unchecked_transaction()?;
158 let data = json!({"key1": "key1-value", "key2": "key2-value"});
159 let bridge_record = make_incoming(&Guid::new("guid"), "ext-id", &data);
160 assert_eq!(do_sync(&tx, &[bridge_record])?.len(), 0);
161 let key1_from_api = get(&tx, "ext-id", json!("key1"))?;
162 assert_eq!(key1_from_api, json!({"key1": "key1-value"}));
163 check_finished_with(&tx, "ext-id", data)?;
164 Ok(())
165 }
166
167 #[test]
168 fn test_outgoing_tombstone() -> Result<()> {
169 // Tombstones are only kept when the mirror has that record - so first
170 // test that, then arrange for the mirror to have the record.
171 let db = new_syncable_mem_db();
172 let conn = db.get_connection().expect("should retrieve connection");
173 let tx = conn.unchecked_transaction()?;
174 let data = json!({"key1": "key1-value", "key2": "key2-value"});
175 set(&tx, "ext-id", data.clone())?;
176 assert_eq!(
177 get_local_data(&tx, "ext-id"),
178 DbData::Data(data.to_string())
179 );
180 // hasn't synced yet, so clearing shouldn't write a tombstone.
181 clear(&tx, "ext-id")?;
182 assert_eq!(get_local_data(&tx, "ext-id"), DbData::NoRow);
183 // now set data again and sync and *then* remove.
184 set(&tx, "ext-id", data)?;
185 assert_eq!(do_sync(&tx, &[])?.len(), 1);
186 assert!(get_local_data(&tx, "ext-id").has_data());
187 let guid = get_mirror_guid(&tx, "ext-id")?;
188 assert!(get_mirror_data(&tx, &guid).has_data());
189 clear(&tx, "ext-id")?;
190 assert_eq!(get_local_data(&tx, "ext-id"), DbData::NullRow);
191 // then after syncing, the tombstone will be in the mirror but the local row
192 // has been removed.
193 assert_eq!(do_sync(&tx, &[])?.len(), 1);
194 assert_eq!(get_local_data(&tx, "ext-id"), DbData::NoRow);
195 assert_eq!(get_mirror_data(&tx, &guid), DbData::NullRow);
196 Ok(())
197 }
198
199 #[test]
200 fn test_incoming_tombstone_exists() -> Result<()> {
201 // An incoming tombstone for a record we've previously synced (and thus
202 // have data for)
203 let db = new_syncable_mem_db();
204 let conn = db.get_connection().expect("should retrieve connection");
205 let tx = conn.unchecked_transaction()?;
206 let data = json!({"key1": "key1-value", "key2": "key2-value"});
207 set(&tx, "ext-id", data.clone())?;
208 assert_eq!(
209 get_local_data(&tx, "ext-id"),
210 DbData::Data(data.to_string())
211 );
212 // sync to get data in our mirror.
213 assert_eq!(do_sync(&tx, &[])?.len(), 1);
214 assert!(get_local_data(&tx, "ext-id").has_data());
215 let guid = get_mirror_guid(&tx, "ext-id")?;
216 assert!(get_mirror_data(&tx, &guid).has_data());
217 // Now an incoming tombstone for it.
218 let tombstone = make_incoming_tombstone(&guid);
219 assert_eq!(
220 do_sync(&tx, &[tombstone])?.len(),
221 0,
222 "expect no outgoing records"
223 );
224 assert_eq!(get_local_data(&tx, "ext-id"), DbData::NoRow);
225 assert_eq!(get_mirror_data(&tx, &guid), DbData::NullRow);
226 Ok(())
227 }
228
229 #[test]
230 fn test_incoming_tombstone_not_exists() -> Result<()> {
231 let db = new_syncable_mem_db();
232 let conn = db.get_connection().expect("should retrieve connection");
233 let tx = conn.unchecked_transaction()?;
234 // An incoming tombstone for something that's not anywhere locally.
235 let guid = Guid::new("guid");
236 let tombstone = make_incoming_tombstone(&guid);
237 assert_eq!(
238 do_sync(&tx, &[tombstone])?.len(),
239 0,
240 "expect no outgoing records"
241 );
242 // But we still keep the tombstone in the mirror.
243 assert_eq!(get_local_data(&tx, "ext-id"), DbData::NoRow);
244 assert_eq!(get_mirror_data(&tx, &guid), DbData::NullRow);
245 Ok(())
246 }
247
248 #[test]
249 fn test_reconciled() -> Result<()> {
250 let db = new_syncable_mem_db();
251 let conn = db.get_connection().expect("should retrieve connection");
252 let tx = conn.unchecked_transaction()?;
253 let data = json!({"key1": "key1-value"});
254 set(&tx, "ext-id", data)?;
255 // Incoming payload with the same data
256 let record = make_incoming(&Guid::new("guid"), "ext-id", &json!({"key1": "key1-value"}));
257 // Should be no outgoing records as we reconciled.
258 assert_eq!(do_sync(&tx, &[record])?.len(), 0);
259 check_finished_with(&tx, "ext-id", json!({"key1": "key1-value"}))?;
260 Ok(())
261 }
262
263 /// Tests that we handle things correctly if we get a payload that is
264 /// identical to what is in the mirrored table.
265 #[test]
266 fn test_reconcile_with_null_payload() -> Result<()> {
267 let db = new_syncable_mem_db();
268 let conn = db.get_connection().expect("should retrieve connection");
269 let tx = conn.unchecked_transaction()?;
270 let data = json!({"key1": "key1-value"});
271 set(&tx, "ext-id", data.clone())?;
272 // We try to push this change on the next sync.
273 assert_eq!(do_sync(&tx, &[])?.len(), 1);
274 let guid = get_mirror_guid(&tx, "ext-id")?;
275 assert_eq!(get_mirror_data(&tx, &guid), DbData::Data(data.to_string()));
276 // Incoming payload with the same data.
277 // This could happen if, for example, another client changed the
278 // key and then put it back the way it was.
279 let record = make_incoming(&guid, "ext-id", &data);
280 // Should be no outgoing records as we reconciled.
281 assert_eq!(do_sync(&tx, &[record])?.len(), 0);
282 check_finished_with(&tx, "ext-id", data)?;
283 Ok(())
284 }
285
286 #[test]
287 fn test_accept_incoming_when_local_is_deleted() -> Result<()> {
288 let db = new_syncable_mem_db();
289 let conn = db.get_connection().expect("should retrieve connection");
290 let tx = conn.unchecked_transaction()?;
291 // We only record an extension as deleted locally if it has been
292 // uploaded before being deleted.
293 let data = json!({"key1": "key1-value"});
294 set(&tx, "ext-id", data)?;
295 assert_eq!(do_sync(&tx, &[])?.len(), 1);
296 let guid = get_mirror_guid(&tx, "ext-id")?;
297 clear(&tx, "ext-id")?;
298 // Incoming payload without 'key1'. Because we previously uploaded
299 // key1, this means another client deleted it.
300 let record = make_incoming(&guid, "ext-id", &json!({"key2": "key2-value"}));
301
302 // We completely accept the incoming record.
303 assert_eq!(do_sync(&tx, &[record])?.len(), 0);
304 check_finished_with(&tx, "ext-id", json!({"key2": "key2-value"}))?;
305 Ok(())
306 }
307
308 #[test]
309 fn test_accept_incoming_when_local_is_deleted_no_mirror() -> Result<()> {
310 let db = new_syncable_mem_db();
311 let conn = db.get_connection().expect("should retrieve connection");
312 let tx = conn.unchecked_transaction()?;
313 let data = json!({"key1": "key1-value"});
314 set(&tx, "ext-id", data)?;
315 assert_eq!(do_sync(&tx, &[])?.len(), 1);
316 clear(&tx, "ext-id")?;
317
318 // Use a random guid so that we don't find the mirrored data.
319 // This test is somewhat bad because deduping might obviate
320 // the need for it.
321 let record = make_incoming(&Guid::new("guid"), "ext-id", &json!({"key2": "key2-value"}));
322
323 // We completely accept the incoming record.
324 assert_eq!(do_sync(&tx, &[record])?.len(), 0);
325 check_finished_with(&tx, "ext-id", json!({"key2": "key2-value"}))?;
326 Ok(())
327 }
328
329 #[test]
330 fn test_accept_deleted_key_mirrored() -> Result<()> {
331 let db = new_syncable_mem_db();
332 let conn = db.get_connection().expect("should retrieve connection");
333 let tx = conn.unchecked_transaction()?;
334 let data = json!({"key1": "key1-value", "key2": "key2-value"});
335 set(&tx, "ext-id", data)?;
336 assert_eq!(do_sync(&tx, &[])?.len(), 1);
337 let guid = get_mirror_guid(&tx, "ext-id")?;
338 // Incoming payload without 'key1'. Because we previously uploaded
339 // key1, this means another client deleted it.
340 let record = make_incoming(&guid, "ext-id", &json!({"key2": "key2-value"}));
341 // We completely accept the incoming record.
342 assert_eq!(do_sync(&tx, &[record])?.len(), 0);
343 check_finished_with(&tx, "ext-id", json!({"key2": "key2-value"}))?;
344 Ok(())
345 }
346
347 #[test]
348 fn test_merged_no_mirror() -> Result<()> {
349 let db = new_syncable_mem_db();
350 let conn = db.get_connection().expect("should retrieve connection");
351 let tx = conn.unchecked_transaction()?;
352 let data = json!({"key1": "key1-value"});
353 set(&tx, "ext-id", data)?;
354 // Incoming payload without 'key1' and some data for 'key2'.
355 // Because we never uploaded 'key1', we merge our local values
356 // with the remote.
357 let record = make_incoming(&Guid::new("guid"), "ext-id", &json!({"key2": "key2-value"}));
358 assert_eq!(do_sync(&tx, &[record])?.len(), 1);
359 check_finished_with(
360 &tx,
361 "ext-id",
362 json!({"key1": "key1-value", "key2": "key2-value"}),
363 )?;
364 Ok(())
365 }
366
367 #[test]
368 fn test_merged_incoming() -> Result<()> {
369 let db = new_syncable_mem_db();
370 let conn = db.get_connection().expect("should retrieve connection");
371 let tx = conn.unchecked_transaction()?;
372 let old_data = json!({"key1": "key1-value", "key2": "key2-value", "doomed_key": "deletable"});
373 set(&tx, "ext-id", old_data)?;
374 assert_eq!(do_sync(&tx, &[])?.len(), 1);
375 let guid = get_mirror_guid(&tx, "ext-id")?;
376 // We update 'key1' locally.
377 let local_data = json!({"key1": "key1-new", "key2": "key2-value", "doomed_key": "deletable"});
378 set(&tx, "ext-id", local_data)?;
379 // Incoming payload where another client set 'key2' and removed
380 // the 'doomed_key'.
381 // Because we never uploaded our data, we'll merge our
382 // key1 in, but otherwise keep the server's changes.
383 let record = make_incoming(
384 &guid,
385 "ext-id",
386 &json!({"key1": "key1-value", "key2": "key2-incoming"}),
387 );
388 // We should send our 'key1'
389 assert_eq!(do_sync(&tx, &[record])?.len(), 1);
390 check_finished_with(
391 &tx,
392 "ext-id",
393 json!({"key2": "key2-incoming", "key1": "key1-new"}),
394 )?;
395 Ok(())
396 }
397
398 #[test]
399 fn test_merged_with_null_payload() -> Result<()> {
400 let db = new_syncable_mem_db();
401 let conn = db.get_connection().expect("should retrieve connection");
402 let tx = conn.unchecked_transaction()?;
403 let old_data = json!({"key1": "key1-value"});
404 set(&tx, "ext-id", old_data.clone())?;
405 // Push this change remotely.
406 assert_eq!(do_sync(&tx, &[])?.len(), 1);
407 let guid = get_mirror_guid(&tx, "ext-id")?;
408 assert_eq!(
409 get_mirror_data(&tx, &guid),
410 DbData::Data(old_data.to_string())
411 );
412 let local_data = json!({"key1": "key1-new", "key2": "key2-value"});
413 set(&tx, "ext-id", local_data.clone())?;
414 // Incoming payload with the same old data.
415 let record = make_incoming(&guid, "ext-id", &old_data);
416 // Three-way-merge will not detect any change in key1, so we
417 // should keep our entire new value.
418 assert_eq!(do_sync(&tx, &[record])?.len(), 1);
419 check_finished_with(&tx, "ext-id", local_data)?;
420 Ok(())
421 }
422
423 #[test]
424 fn test_deleted_mirrored_object_accept() -> Result<()> {
425 let db = new_syncable_mem_db();
426 let conn = db.get_connection().expect("should retrieve connection");
427 let tx = conn.unchecked_transaction()?;
428 let data = json!({"key1": "key1-value", "key2": "key2-value"});
429 set(&tx, "ext-id", data)?;
430 assert_eq!(do_sync(&tx, &[])?.len(), 1);
431 let guid = get_mirror_guid(&tx, "ext-id")?;
432 // Incoming payload with data deleted.
433 // We synchronize this deletion by deleting the keys we think
434 // were on the server.
435 let record = make_incoming_tombstone(&guid);
436 assert_eq!(do_sync(&tx, &[record])?.len(), 0);
437 assert_eq!(get_local_data(&tx, "ext-id"), DbData::NoRow);
438 assert_eq!(get_mirror_data(&tx, &guid), DbData::NullRow);
439 Ok(())
440 }
441
442 #[test]
443 fn test_deleted_mirrored_object_merged() -> Result<()> {
444 let db = new_syncable_mem_db();
445 let conn = db.get_connection().expect("should retrieve connection");
446 let tx = conn.unchecked_transaction()?;
447 set(&tx, "ext-id", json!({"key1": "key1-value"}))?;
448 assert_eq!(do_sync(&tx, &[])?.len(), 1);
449 let guid = get_mirror_guid(&tx, "ext-id")?;
450 set(
451 &tx,
452 "ext-id",
453 json!({"key1": "key1-new", "key2": "key2-value"}),
454 )?;
455 // Incoming payload with data deleted.
456 // We synchronize this deletion by deleting the keys we think
457 // were on the server.
458 let record = make_incoming_tombstone(&guid);
459 // This overrides the change to 'key1', but we still upload 'key2'.
460 assert_eq!(do_sync(&tx, &[record])?.len(), 1);
461 check_finished_with(&tx, "ext-id", json!({"key2": "key2-value"}))?;
462 Ok(())
463 }
464
465 /// Like the above test, but with a mirrored tombstone.
466 #[test]
467 fn test_deleted_mirrored_tombstone_merged() -> Result<()> {
468 let db = new_syncable_mem_db();
469 let conn = db.get_connection().expect("should retrieve connection");
470 let tx = conn.unchecked_transaction()?;
471 // Sync some data so we can get the guid for this extension.
472 set(&tx, "ext-id", json!({"key1": "key1-value"}))?;
473 assert_eq!(do_sync(&tx, &[])?.len(), 1);
474 let guid = get_mirror_guid(&tx, "ext-id")?;
475 // Sync a delete for this data so we have a tombstone in the mirror.
476 let record = make_incoming_tombstone(&guid);
477 assert_eq!(do_sync(&tx, &[record])?.len(), 0);
478 assert_eq!(get_mirror_data(&tx, &guid), DbData::NullRow);
479
480 // Set some data and sync it simultaneously with another incoming delete.
481 set(&tx, "ext-id", json!({"key2": "key2-value"}))?;
482 let record = make_incoming_tombstone(&guid);
483 // We cannot delete any matching keys because there are no
484 // matching keys. Instead we push our data.
485 assert_eq!(do_sync(&tx, &[record])?.len(), 1);
486 check_finished_with(&tx, "ext-id", json!({"key2": "key2-value"}))?;
487 Ok(())
488 }
489
490 #[test]
491 fn test_deleted_not_mirrored_object_merged() -> Result<()> {
492 let db = new_syncable_mem_db();
493 let conn = db.get_connection().expect("should retrieve connection");
494 let tx = conn.unchecked_transaction()?;
495 let data = json!({"key1": "key1-value", "key2": "key2-value"});
496 set(&tx, "ext-id", data)?;
497 // Incoming payload with data deleted.
498 let record = make_incoming_tombstone(&Guid::new("guid"));
499 // We normally delete the keys we think were on the server, but
500 // here we have no information about what was on the server, so we
501 // don't delete anything. We merge in all undeleted keys.
502 assert_eq!(do_sync(&tx, &[record])?.len(), 1);
503 check_finished_with(
504 &tx,
505 "ext-id",
506 json!({"key1": "key1-value", "key2": "key2-value"}),
507 )?;
508 Ok(())
509 }
510
511 #[test]
512 fn test_conflicting_incoming() -> Result<()> {
513 let db = new_syncable_mem_db();
514 let conn = db.get_connection().expect("should retrieve connection");
515 let tx = conn.unchecked_transaction()?;
516 let data = json!({"key1": "key1-value", "key2": "key2-value"});
517 set(&tx, "ext-id", data)?;
518 // Incoming payload without 'key1' and conflicting for 'key2'.
519 // Because we never uploaded either of our keys, we'll merge our
520 // key1 in, but the server key2 wins.
521 let record = make_incoming(
522 &Guid::new("guid"),
523 "ext-id",
524 &json!({"key2": "key2-incoming"}),
525 );
526 // We should send our 'key1'
527 assert_eq!(do_sync(&tx, &[record])?.len(), 1);
528 check_finished_with(
529 &tx,
530 "ext-id",
531 json!({"key1": "key1-value", "key2": "key2-incoming"}),
532 )?;
533 Ok(())
534 }
535
536 #[test]
537 fn test_invalid_incoming() -> Result<()> {
538 let db = new_syncable_mem_db();
539 let conn = db.get_connection().expect("should retrieve connection");
540 let tx = conn.unchecked_transaction()?;
541 let json = json!({"id": "id", "payload": json!("").to_string()});
542 let bso = serde_json::from_value::<IncomingBso>(json).unwrap();
543 let record = bso.into_content();
544
545 // Should do nothing.
546 assert_eq!(do_sync(&tx, &[record])?.len(), 0);
547 Ok(())
548 }