File: saved_tab_group_sync_bridge.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (531 lines) | stat: -rw-r--r-- 19,742 bytes parent folder | download | duplicates (2)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/saved_tab_groups/saved_tab_group_sync_bridge.h"

#include <algorithm>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>

#include "base/check.h"
#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/functional/callback_helpers.h"
#include "base/ranges/algorithm.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/uuid.h"
#include "components/saved_tab_groups/saved_tab_group.h"
#include "components/saved_tab_groups/saved_tab_group_model.h"
#include "components/saved_tab_groups/saved_tab_group_tab.h"
#include "components/sync/base/model_type.h"
#include "components/sync/model/entity_change.h"
#include "components/sync/model/metadata_batch.h"
#include "components/sync/model/metadata_change_list.h"
#include "components/sync/model/model_error.h"
#include "components/sync/model/model_type_change_processor.h"
#include "components/sync/model/model_type_store.h"
#include "components/sync/model/mutable_data_batch.h"
#include "components/sync/protocol/entity_data.h"
#include "components/sync/protocol/saved_tab_group_specifics.pb.h"

namespace {

// Discard orphaned tabs after 30 days if the associated group cannot be found.
constexpr base::TimeDelta kDiscardOrphanedTabsThreshold = base::Days(30);

std::unique_ptr<syncer::EntityData> CreateEntityData(
    std::unique_ptr<sync_pb::SavedTabGroupSpecifics> specific) {
  std::unique_ptr<syncer::EntityData> entity_data =
      std::make_unique<syncer::EntityData>();
  entity_data->name = specific->guid();
  entity_data->specifics.set_allocated_saved_tab_group(specific.release());
  return entity_data;
}

}  // anonymous namespace

SavedTabGroupSyncBridge::SavedTabGroupSyncBridge(
    SavedTabGroupModel* model,
    syncer::OnceModelTypeStoreFactory create_store_callback,
    std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor)
    : syncer::ModelTypeSyncBridge(std::move(change_processor)), model_(model) {
  DCHECK(model_);
  std::move(create_store_callback)
      .Run(syncer::SAVED_TAB_GROUP,
           base::BindOnce(&SavedTabGroupSyncBridge::OnStoreCreated,
                          weak_ptr_factory_.GetWeakPtr()));
}

SavedTabGroupSyncBridge::~SavedTabGroupSyncBridge() = default;

std::unique_ptr<syncer::MetadataChangeList>
SavedTabGroupSyncBridge::CreateMetadataChangeList() {
  return syncer::ModelTypeStore::WriteBatch::CreateMetadataChangeList();
}

absl::optional<syncer::ModelError> SavedTabGroupSyncBridge::MergeFullSyncData(
    std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
    syncer::EntityChangeList entity_changes) {
  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> write_batch =
      store_->CreateWriteBatch();
  std::set<std::string> synced_items;

  // Merge sync to local data.
  for (const auto& change : entity_changes) {
    synced_items.insert(change->storage_key());
    AddDataToLocalStorage(std::move(change->data().specifics.saved_tab_group()),
                          metadata_change_list.get(), write_batch.get(),
                          /*notify_sync=*/true);
  }

  ResolveTabsMissingGroups(write_batch.get());

  // Update sync with any locally stored data not currently stored in sync.
  for (const SavedTabGroup& group : model_->saved_tab_groups()) {
    for (const SavedTabGroupTab& tab : group.saved_tabs()) {
      if (synced_items.count(tab.saved_tab_guid().AsLowercaseString()))
        continue;
      SendToSync(tab.ToSpecifics(), metadata_change_list.get());
    }

    if (synced_items.count(group.saved_guid().AsLowercaseString()))
      continue;
    SendToSync(group.ToSpecifics(), metadata_change_list.get());
  }

  write_batch->TakeMetadataChangesFrom(std::move(metadata_change_list));
  store_->CommitWriteBatch(
      std::move(write_batch),
      base::BindOnce(&SavedTabGroupSyncBridge::OnDatabaseSave,
                     weak_ptr_factory_.GetWeakPtr()));
  return {};
}

absl::optional<syncer::ModelError>
SavedTabGroupSyncBridge::ApplyIncrementalSyncChanges(
    std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
    syncer::EntityChangeList entity_changes) {
  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> write_batch =
      store_->CreateWriteBatch();

  for (const std::unique_ptr<syncer::EntityChange>& change : entity_changes) {
    switch (change->type()) {
      case syncer::EntityChange::ACTION_DELETE: {
        DeleteDataFromLocalStorage(
            base::Uuid::ParseLowercase(change->storage_key()),
            write_batch.get());
        break;
      }
      case syncer::EntityChange::ACTION_ADD:
      case syncer::EntityChange::ACTION_UPDATE: {
        AddDataToLocalStorage(
            std::move(change->data().specifics.saved_tab_group()),
            metadata_change_list.get(), write_batch.get(),
            /*notify_sync=*/false);
        break;
      }
    }
  }

  ResolveTabsMissingGroups(write_batch.get());

  write_batch->TakeMetadataChangesFrom(std::move(metadata_change_list));
  store_->CommitWriteBatch(
      std::move(write_batch),
      base::BindOnce(&SavedTabGroupSyncBridge::OnDatabaseSave,
                     weak_ptr_factory_.GetWeakPtr()));
  return {};
}

std::string SavedTabGroupSyncBridge::GetStorageKey(
    const syncer::EntityData& entity_data) {
  return entity_data.specifics.saved_tab_group().guid();
}

std::string SavedTabGroupSyncBridge::GetClientTag(
    const syncer::EntityData& entity_data) {
  return GetStorageKey(entity_data);
}

void SavedTabGroupSyncBridge::GetData(StorageKeyList storage_keys,
                                      DataCallback callback) {
  auto batch = std::make_unique<syncer::MutableDataBatch>();

  for (const std::string& guid : storage_keys) {
    base::Uuid parsed_guid = base::Uuid::ParseLowercase(guid);
    for (const SavedTabGroup& group : model_->saved_tab_groups()) {
      if (group.saved_guid() == parsed_guid) {
        AddEntryToBatch(batch.get(), group.ToSpecifics());
        break;
      }

      if (group.ContainsTab(parsed_guid)) {
        const SavedTabGroupTab& tab =
            group.saved_tabs()[group.GetIndexOfTab(parsed_guid).value()];
        AddEntryToBatch(batch.get(), tab.ToSpecifics());
        break;
      }
    }
  }

  std::move(callback).Run(std::move(batch));
}

void SavedTabGroupSyncBridge::GetAllDataForDebugging(DataCallback callback) {
  auto batch = std::make_unique<syncer::MutableDataBatch>();
  for (const SavedTabGroup& group : model_->saved_tab_groups()) {
    AddEntryToBatch(batch.get(), group.ToSpecifics());
    for (const SavedTabGroupTab& tab : group.saved_tabs()) {
      AddEntryToBatch(batch.get(), tab.ToSpecifics());
    }
  }

  std::move(callback).Run(std::move(batch));
}

// SavedTabGroupModelObserver
void SavedTabGroupSyncBridge::SavedTabGroupAddedLocally(
    const base::Uuid& guid) {
  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> write_batch =
      store_->CreateWriteBatch();

  const SavedTabGroup* group = model_->Get(guid);
  DCHECK(group);

  int index = model_->GetIndexOf(guid).value();
  std::unique_ptr<sync_pb::SavedTabGroupSpecifics> group_specific =
      group->ToSpecifics();
  group_specific->mutable_group()->set_position(index);

  UpsertEntitySpecific(std::move(group_specific), write_batch.get());
  for (size_t i = 0; i < group->saved_tabs().size(); ++i) {
    std::unique_ptr<sync_pb::SavedTabGroupSpecifics> tab_specific =
        group->saved_tabs()[i].ToSpecifics();
    tab_specific->mutable_tab()->set_position(i);
    UpsertEntitySpecific(std::move(tab_specific), write_batch.get());
  }

  store_->CommitWriteBatch(
      std::move(write_batch),
      base::BindOnce(&SavedTabGroupSyncBridge::OnDatabaseSave,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SavedTabGroupSyncBridge::SavedTabGroupRemovedLocally(
    const SavedTabGroup* removed_group) {
  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> write_batch =
      store_->CreateWriteBatch();

  // Intentionally only remove the group (creating orphaned tabs in the
  // process), so other devices with the group open in the Tabstrip can react to
  // the deletion appropriately (i.e. We do not have to determine if a tab
  // deletion was part of a group deletion).
  RemoveEntitySpecific(removed_group->saved_guid(), write_batch.get());

  // Keep track of the newly orphaned tabs since their group no longer exists.
  for (const SavedTabGroupTab& tab : removed_group->saved_tabs()) {
    tabs_missing_groups_.emplace_back(*tab.ToSpecifics());
  }

  store_->CommitWriteBatch(
      std::move(write_batch),
      base::BindOnce(&SavedTabGroupSyncBridge::OnDatabaseSave,
                     weak_ptr_factory_.GetWeakPtr()));

  // Update the ModelTypeStore (local storage) and sync with the new positions
  // of all the groups after a remove has occurred so the positions are
  // preserved on browser restart. See crbug/1462443.
  SavedTabGroupReorderedLocally();
}

void SavedTabGroupSyncBridge::SavedTabGroupUpdatedLocally(
    const base::Uuid& group_guid,
    const absl::optional<base::Uuid>& tab_guid) {
  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> write_batch =
      store_->CreateWriteBatch();

  const SavedTabGroup* const group = model_->Get(group_guid);
  DCHECK(group);

  if (tab_guid.has_value()) {
    if (!group->ContainsTab(tab_guid.value())) {
      RemoveEntitySpecific(tab_guid.value(), write_batch.get());
    } else {
      int tab_index = group->GetIndexOfTab(tab_guid.value()).value();
      UpsertEntitySpecific(group->saved_tabs()[tab_index].ToSpecifics(),
                           write_batch.get());
    }
  } else {
    UpsertEntitySpecific(group->ToSpecifics(), write_batch.get());
  }

  store_->CommitWriteBatch(
      std::move(write_batch),
      base::BindOnce(&SavedTabGroupSyncBridge::OnDatabaseSave,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SavedTabGroupSyncBridge::SavedTabGroupTabsReorderedLocally(
    const base::Uuid& group_guid) {
  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> write_batch =
      store_->CreateWriteBatch();

  const SavedTabGroup* const group = model_->Get(group_guid);
  DCHECK(group);

  for (const SavedTabGroupTab& tab : group->saved_tabs()) {
    UpsertEntitySpecific(tab.ToSpecifics(), write_batch.get());
  }

  store_->CommitWriteBatch(std::move(write_batch), base::DoNothing());
}

void SavedTabGroupSyncBridge::SavedTabGroupReorderedLocally() {
  std::unique_ptr<syncer::ModelTypeStore::WriteBatch> write_batch =
      store_->CreateWriteBatch();

  for (const SavedTabGroup& group : model_->saved_tab_groups()) {
    UpsertEntitySpecific(group.ToSpecifics(), write_batch.get());
  }

  store_->CommitWriteBatch(std::move(write_batch), base::DoNothing());
}

void SavedTabGroupSyncBridge::UpsertEntitySpecific(
    std::unique_ptr<sync_pb::SavedTabGroupSpecifics> specific,
    syncer::ModelTypeStore::WriteBatch* write_batch) {
  write_batch->WriteData(specific->guid(), specific->SerializeAsString());
  SendToSync(std::move(specific), write_batch->GetMetadataChangeList());
}

void SavedTabGroupSyncBridge::RemoveEntitySpecific(
    const base::Uuid& guid,
    syncer::ModelTypeStore::WriteBatch* write_batch) {
  write_batch->DeleteData(guid.AsLowercaseString());

  if (!change_processor()->IsTrackingMetadata())
    return;

  change_processor()->Delete(guid.AsLowercaseString(),
                             write_batch->GetMetadataChangeList());
}

void SavedTabGroupSyncBridge::AddDataToLocalStorage(
    const sync_pb::SavedTabGroupSpecifics& specifics,
    syncer::MetadataChangeList* metadata_change_list,
    syncer::ModelTypeStore::WriteBatch* write_batch,
    bool notify_sync) {
  std::string group_id =
      specifics.has_tab() ? specifics.tab().group_guid() : specifics.guid();
  const SavedTabGroup* existing_group =
      model_->Get(base::Uuid::ParseLowercase(group_id));

  // Cases where `specifics` is a group.
  if (specifics.has_group()) {
    if (existing_group) {
      // Resolve the conflict by merging the sync and local data. Once
      // finished, write the result to the store and update sync with the new
      // merged result if appropriate.
      std::unique_ptr<sync_pb::SavedTabGroupSpecifics> merged_entry =
          model_->MergeGroup(std::move(specifics));

      // Write result to the store.
      write_batch->WriteData(merged_entry->guid(),
                             merged_entry->SerializeAsString());

      // Update sync with the new merged result.
      if (notify_sync)
        SendToSync(std::move(merged_entry), metadata_change_list);
    } else {
      // We do not have this group. Add the group from sync into local storage.
      write_batch->WriteData(specifics.guid(), specifics.SerializeAsString());
      model_->AddedFromSync(SavedTabGroup::FromSpecifics(specifics));
    }

    return;
  }

  // Cases where `specifics` is a tab.
  if (specifics.has_tab()) {
    if (existing_group && existing_group->ContainsTab(
                              base::Uuid::ParseLowercase(specifics.guid()))) {
      // Resolve the conflict by merging the sync and local data. Once finished,
      // write the result to the store and update sync with the new merged
      // result if appropriate.
      std::unique_ptr<sync_pb::SavedTabGroupSpecifics> merged_entry =
          model_->MergeTab(std::move(specifics));

      // Write result to the store.
      write_batch->WriteData(merged_entry->guid(),
                             merged_entry->SerializeAsString());

      // Update sync with the new merged result.
      if (notify_sync)
        SendToSync(std::move(merged_entry), metadata_change_list);

      return;
    }

    // We write tabs to local storage regardless of the existence of its group
    // in order to recover the tabs in the event the group was not received and
    // a crash / restart occurred.
    write_batch->WriteData(specifics.guid(), specifics.SerializeAsString());

    if (existing_group) {
      // We do not have this tab. Add the tab from sync into local storage.
      model_->AddTabToGroupFromSync(existing_group->saved_guid(),
                                    SavedTabGroupTab::FromSpecifics(specifics));
    } else {
      // We reach this case if we were unable to find a group for this tab. This
      // can happen when sync sends the tab data before the group data. In this
      // case, we will store the tabs in case the group comes in later.
      tabs_missing_groups_.emplace_back(std::move(specifics));
    }
  }
}

void SavedTabGroupSyncBridge::DeleteDataFromLocalStorage(
    const base::Uuid& guid,
    syncer::ModelTypeStore::WriteBatch* write_batch) {
  write_batch->DeleteData(guid.AsLowercaseString());
  // Check if the model contains the group guid. If so, remove that group and
  // all of its tabs.
  if (model_->Contains(guid)) {
    model_->RemovedFromSync(guid);
    return;
  }

  for (const SavedTabGroup& group : model_->saved_tab_groups()) {
    if (!group.ContainsTab(guid))
      continue;

    model_->RemoveTabFromGroupFromSync(group.saved_guid(), guid);
    return;
  }
}

void SavedTabGroupSyncBridge::ResolveTabsMissingGroups(
    syncer::ModelTypeStore::WriteBatch* write_batch) {
  auto tab_iterator = tabs_missing_groups_.begin();
  while (tab_iterator != tabs_missing_groups_.end()) {
    const SavedTabGroup* group = model_->Get(
        base::Uuid::ParseLowercase(tab_iterator->tab().group_guid()));
    if (!group) {
      base::Time last_update_time = base::Time::FromDeltaSinceWindowsEpoch(
          base::Microseconds(tab_iterator->update_time_windows_epoch_micros()));
      base::Time now = base::Time::Now();

      // Discard the tabs that do not have an associated group and have not been
      // updated within the discard threshold.
      if (now - last_update_time >= kDiscardOrphanedTabsThreshold) {
        RemoveEntitySpecific(base::Uuid::ParseLowercase(tab_iterator->guid()),
                             write_batch);
        tab_iterator = tabs_missing_groups_.erase(tab_iterator);
      } else {
        ++tab_iterator;
      }
    } else {
      write_batch->WriteData(tab_iterator->guid(),
                             tab_iterator->SerializeAsString());
      model_->AddTabToGroupFromSync(
          group->saved_guid(), SavedTabGroupTab::FromSpecifics(*tab_iterator));
      tab_iterator = tabs_missing_groups_.erase(tab_iterator);
    }
  }
}

void SavedTabGroupSyncBridge::AddEntryToBatch(
    syncer::MutableDataBatch* batch,
    std::unique_ptr<sync_pb::SavedTabGroupSpecifics> specific) {
  std::unique_ptr<syncer::EntityData> entity_data =
      CreateEntityData(std::move(specific));

  // Copy because our key is the name of `entity_data`.
  std::string name = entity_data->name;

  batch->Put(name, std::move(entity_data));
}

void SavedTabGroupSyncBridge::SendToSync(
    std::unique_ptr<sync_pb::SavedTabGroupSpecifics> specific,
    syncer::MetadataChangeList* metadata_change_list) {
  DCHECK(metadata_change_list);
  if (!change_processor()->IsTrackingMetadata())
    return;

  auto entity_data = CreateEntityData(std::move(specific));

  // Copy because our key is the name of `entity_data`.
  std::string name = entity_data->name;
  change_processor()->Put(name, std::move(entity_data), metadata_change_list);
}

void SavedTabGroupSyncBridge::OnStoreCreated(
    const absl::optional<syncer::ModelError>& error,
    std::unique_ptr<syncer::ModelTypeStore> store) {
  if (error) {
    change_processor()->ReportError(*error);
    return;
  }

  store_ = std::move(store);
  store_->ReadAllData(base::BindOnce(&SavedTabGroupSyncBridge::OnDatabaseLoad,
                                     weak_ptr_factory_.GetWeakPtr()));
}

void SavedTabGroupSyncBridge::OnDatabaseLoad(
    const absl::optional<syncer::ModelError>& error,
    std::unique_ptr<syncer::ModelTypeStore::RecordList> entries) {
  if (error) {
    change_processor()->ReportError(*error);
    return;
  }

  store_->ReadAllMetadata(
      base::BindOnce(&SavedTabGroupSyncBridge::OnReadAllMetadata,
                     weak_ptr_factory_.GetWeakPtr(), std::move(entries)));
}

void SavedTabGroupSyncBridge::OnReadAllMetadata(
    std::unique_ptr<syncer::ModelTypeStore::RecordList> entries,
    const absl::optional<syncer::ModelError>& error,
    std::unique_ptr<syncer::MetadataBatch> metadata_batch) {
  TRACE_EVENT0("ui", "SavedTabGroupSyncBridge::OnReadAllMetadata");
  if (error) {
    change_processor()->ReportError({FROM_HERE, "Failed to read metadata."});
    return;
  }

  change_processor()->ModelReadyToSync(std::move(metadata_batch));

  std::vector<sync_pb::SavedTabGroupSpecifics> stored_entries;
  stored_entries.reserve(entries->size());

  for (const syncer::ModelTypeStore::Record& r : *entries) {
    sync_pb::SavedTabGroupSpecifics proto;
    if (!proto.ParseFromString(r.value))
      continue;
    stored_entries.emplace_back(std::move(proto));
  }

  // Update `model_` with any data stored in local storage except for orphaned
  // tabs. Orphaned tabs will be returned and added to `tabs_missing_groups_` in
  // case their missing group ever arrives.
  tabs_missing_groups_ = model_->LoadStoredEntries(std::move(stored_entries));
  observation_.Observe(model_);
}

void SavedTabGroupSyncBridge::OnDatabaseSave(
    const absl::optional<syncer::ModelError>& error) {
  if (error) {
    change_processor()->ReportError({FROM_HERE, "Failed to save metadata."});
    return;
  }

  // TODO(dljames): React to store failures when a save is not successful.
}