File: sync_backend_host_core.cc

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (645 lines) | stat: -rw-r--r-- 24,620 bytes parent folder | download
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/sync/driver/glue/sync_backend_host_core.h"

#include <utility>

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/memory_dump_manager.h"
#include "components/data_use_measurement/core/data_use_user_data.h"
#include "components/invalidation/public/invalidation_util.h"
#include "components/invalidation/public/object_id_invalidation_map.h"
#include "components/sync/base/invalidation_adapter.h"
#include "components/sync/device_info/local_device_info_provider_impl.h"
#include "components/sync/engine/cycle/commit_counters.h"
#include "components/sync/engine/cycle/status_counters.h"
#include "components/sync/engine/cycle/sync_cycle_snapshot.h"
#include "components/sync/engine/cycle/update_counters.h"
#include "components/sync/engine/engine_components_factory.h"
#include "components/sync/engine/events/protocol_event.h"
#include "components/sync/engine/net/http_post_provider_factory.h"
#include "components/sync/engine/sync_backend_registrar.h"
#include "components/sync/engine/sync_manager.h"
#include "components/sync/engine/sync_manager_factory.h"
#include "components/sync/syncable/directory.h"

// Helper macros to log with the syncer thread name; useful when there
// are multiple syncers involved.

#define SLOG(severity) LOG(severity) << name_ << ": "

#define SDVLOG(verbose_level) DVLOG(verbose_level) << name_ << ": "

static const int kSaveChangesIntervalSeconds = 10;

namespace net {
class URLFetcher;
}

namespace {

void BindFetcherToDataTracker(net::URLFetcher* fetcher) {
  data_use_measurement::DataUseUserData::AttachToFetcher(
      fetcher, data_use_measurement::DataUseUserData::SYNC);
}

}  // namespace

namespace syncer {

class EngineComponentsFactory;

SyncBackendHostCore::SyncBackendHostCore(
    const std::string& name,
    const base::FilePath& sync_data_folder,
    const base::WeakPtr<SyncBackendHostImpl>& backend)
    : name_(name),
      sync_data_folder_(sync_data_folder),
      host_(backend),
      weak_ptr_factory_(this) {
  DCHECK(backend.get());
  // This is constructed on the UI thread but used from the sync thread.
  thread_checker_.DetachFromThread();
}

SyncBackendHostCore::~SyncBackendHostCore() {
  DCHECK(!sync_manager_.get());
}

bool SyncBackendHostCore::OnMemoryDump(
    const base::trace_event::MemoryDumpArgs& args,
    base::trace_event::ProcessMemoryDump* pmd) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!sync_manager_)
    return false;
  sync_manager_->OnMemoryDump(pmd);
  return true;
}

void SyncBackendHostCore::OnSyncCycleCompleted(
    const SyncCycleSnapshot& snapshot) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE,
             &SyncBackendHostImpl::HandleSyncCycleCompletedOnFrontendLoop,
             snapshot);
}

void SyncBackendHostCore::DoRefreshTypes(ModelTypeSet types) {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->RefreshTypes(types);
}

void SyncBackendHostCore::OnInitializationComplete(
    const WeakHandle<JsBackend>& js_backend,
    const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener,
    bool success,
    const ModelTypeSet restored_types) {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (!success) {
    DoDestroySyncManager(STOP_SYNC);
    host_.Call(FROM_HERE,
               &SyncBackendHostImpl::HandleInitializationFailureOnFrontendLoop);
    return;
  }

  // Register for encryption related changes now. We have to do this before
  // the initializing downloading control types or initializing the encryption
  // handler in order to receive notifications triggered during encryption
  // startup.
  sync_manager_->GetEncryptionHandler()->AddObserver(this);

  // Sync manager initialization is complete, so we can schedule recurring
  // SaveChanges.
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::Bind(&SyncBackendHostCore::StartSavingChanges,
                            weak_ptr_factory_.GetWeakPtr()));

  // Hang on to these for a while longer.  We're not ready to hand them back to
  // the UI thread yet.
  js_backend_ = js_backend;
  debug_info_listener_ = debug_info_listener;

  // Before proceeding any further, we need to download the control types and
  // purge any partial data (ie. data downloaded for a type that was on its way
  // to being initially synced, but didn't quite make it.).  The following
  // configure cycle will take care of this.  It depends on the registrar state
  // which we initialize below to ensure that we don't perform any downloads if
  // all control types have already completed their initial sync.
  registrar_->SetInitialTypes(restored_types);

  ConfigureReason reason = restored_types.Empty()
                               ? CONFIGURE_REASON_NEW_CLIENT
                               : CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;

  ModelTypeSet new_control_types =
      registrar_->ConfigureDataTypes(ControlTypes(), ModelTypeSet());
  ModelSafeRoutingInfo routing_info;
  registrar_->GetModelSafeRoutingInfo(&routing_info);
  SDVLOG(1) << "Control Types " << ModelTypeSetToString(new_control_types)
            << " added; calling ConfigureSyncer";

  ModelTypeSet types_to_purge =
      Difference(ModelTypeSet::All(), GetRoutingInfoTypes(routing_info));

  sync_manager_->PurgeDisabledTypes(types_to_purge, ModelTypeSet(),
                                    ModelTypeSet());
  sync_manager_->ConfigureSyncer(
      reason, new_control_types, routing_info,
      base::Bind(&SyncBackendHostCore::DoInitialProcessControlTypes,
                 weak_ptr_factory_.GetWeakPtr()),
      base::Closure());
}

void SyncBackendHostCore::OnConnectionStatusChange(ConnectionStatus status) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE,
             &SyncBackendHostImpl::HandleConnectionStatusChangeOnFrontendLoop,
             status);
}

void SyncBackendHostCore::OnPassphraseRequired(
    PassphraseRequiredReason reason,
    const sync_pb::EncryptedData& pending_keys) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE, &SyncBackendHostImpl::NotifyPassphraseRequired, reason,
             pending_keys);
}

void SyncBackendHostCore::OnPassphraseAccepted() {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE, &SyncBackendHostImpl::NotifyPassphraseAccepted);
}

void SyncBackendHostCore::OnBootstrapTokenUpdated(
    const std::string& bootstrap_token,
    BootstrapTokenType type) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE, &SyncBackendHostImpl::PersistEncryptionBootstrapToken,
             bootstrap_token, type);
}

void SyncBackendHostCore::OnEncryptedTypesChanged(ModelTypeSet encrypted_types,
                                                  bool encrypt_everything) {
  DCHECK(thread_checker_.CalledOnValidThread());
  // NOTE: We're in a transaction.
  host_.Call(FROM_HERE, &SyncBackendHostImpl::NotifyEncryptedTypesChanged,
             encrypted_types, encrypt_everything);
}

void SyncBackendHostCore::OnEncryptionComplete() {
  DCHECK(thread_checker_.CalledOnValidThread());
  // NOTE: We're in a transaction.
  host_.Call(FROM_HERE, &SyncBackendHostImpl::NotifyEncryptionComplete);
}

void SyncBackendHostCore::OnCryptographerStateChanged(
    Cryptographer* cryptographer) {
  DCHECK(thread_checker_.CalledOnValidThread());
  // Do nothing.
}

void SyncBackendHostCore::OnPassphraseTypeChanged(PassphraseType type,
                                                  base::Time passphrase_time) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE,
             &SyncBackendHostImpl::HandlePassphraseTypeChangedOnFrontendLoop,
             type, passphrase_time);
}

void SyncBackendHostCore::OnLocalSetPassphraseEncryption(
    const SyncEncryptionHandler::NigoriState& nigori_state) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(
      FROM_HERE,
      &SyncBackendHostImpl::HandleLocalSetPassphraseEncryptionOnFrontendLoop,
      nigori_state);
}

void SyncBackendHostCore::OnCommitCountersUpdated(
    ModelType type,
    const CommitCounters& counters) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(
      FROM_HERE,
      &SyncBackendHostImpl::HandleDirectoryCommitCountersUpdatedOnFrontendLoop,
      type, counters);
}

void SyncBackendHostCore::OnUpdateCountersUpdated(
    ModelType type,
    const UpdateCounters& counters) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(
      FROM_HERE,
      &SyncBackendHostImpl::HandleDirectoryUpdateCountersUpdatedOnFrontendLoop,
      type, counters);
}

void SyncBackendHostCore::OnStatusCountersUpdated(
    ModelType type,
    const StatusCounters& counters) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(
      FROM_HERE,
      &SyncBackendHostImpl::HandleDirectoryStatusCountersUpdatedOnFrontendLoop,
      type, counters);
}

void SyncBackendHostCore::OnActionableError(
    const SyncProtocolError& sync_error) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE,
             &SyncBackendHostImpl::HandleActionableErrorEventOnFrontendLoop,
             sync_error);
}

void SyncBackendHostCore::OnMigrationRequested(ModelTypeSet types) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE,
             &SyncBackendHostImpl::HandleMigrationRequestedOnFrontendLoop,
             types);
}

void SyncBackendHostCore::OnProtocolEvent(const ProtocolEvent& event) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (forward_protocol_events_) {
    std::unique_ptr<ProtocolEvent> event_clone(event.Clone());
    host_.Call(FROM_HERE,
               &SyncBackendHostImpl::HandleProtocolEventOnFrontendLoop,
               base::Passed(std::move(event_clone)));
  }
}

void SyncBackendHostCore::DoOnInvalidatorStateChange(InvalidatorState state) {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->SetInvalidatorEnabled(state == INVALIDATIONS_ENABLED);
}

void SyncBackendHostCore::DoOnIncomingInvalidation(
    const ObjectIdInvalidationMap& invalidation_map) {
  DCHECK(thread_checker_.CalledOnValidThread());

  ObjectIdSet ids = invalidation_map.GetObjectIds();
  for (const invalidation::ObjectId& object_id : ids) {
    ModelType type;
    if (!NotificationTypeToRealModelType(object_id.name(), &type)) {
      DLOG(WARNING) << "Notification has invalid id: "
                    << ObjectIdToString(object_id);
    } else {
      SingleObjectInvalidationSet invalidation_set =
          invalidation_map.ForObject(object_id);
      for (Invalidation invalidation : invalidation_set) {
        auto last_invalidation = last_invalidation_versions_.find(type);
        if (!invalidation.is_unknown_version() &&
            last_invalidation != last_invalidation_versions_.end() &&
            invalidation.version() <= last_invalidation->second) {
          DVLOG(1) << "Ignoring redundant invalidation for "
                   << ModelTypeToString(type) << " with version "
                   << invalidation.version() << ", last seen version was "
                   << last_invalidation->second;
          continue;
        }
        std::unique_ptr<InvalidationInterface> inv_adapter(
            new InvalidationAdapter(invalidation));
        sync_manager_->OnIncomingInvalidation(type, std::move(inv_adapter));
        if (!invalidation.is_unknown_version())
          last_invalidation_versions_[type] = invalidation.version();
      }
    }
  }

  host_.Call(FROM_HERE, &SyncBackendHostImpl::UpdateInvalidationVersions,
             last_invalidation_versions_);
}

void SyncBackendHostCore::DoInitialize(SyncEngine::InitParams params) {
  DCHECK(thread_checker_.CalledOnValidThread());

  // Blow away the partial or corrupt sync data folder before doing any more
  // initialization, if necessary.
  if (params.delete_sync_data_folder) {
    syncable::Directory::DeleteDirectoryFiles(sync_data_folder_);
  }

  // Make sure that the directory exists before initializing the backend.
  // If it already exists, this will do no harm.
  if (!base::CreateDirectory(sync_data_folder_)) {
    DLOG(FATAL) << "Sync Data directory creation failed.";
  }

  // Load the previously persisted set of invalidation versions into memory.
  last_invalidation_versions_ = params.invalidation_versions;

  DCHECK(!registrar_);
  registrar_ = std::move(params.registrar);
  DCHECK(registrar_);

  sync_manager_ = params.sync_manager_factory->CreateSyncManager(name_);
  sync_manager_->AddObserver(this);

  SyncManager::InitArgs args;
  args.database_location = sync_data_folder_;
  args.event_handler = params.event_handler;
  args.service_url = params.service_url;
  args.enable_local_sync_backend = params.enable_local_sync_backend;
  args.local_sync_backend_folder = params.local_sync_backend_folder;
  args.post_factory =
      params.http_factory_getter.Run(&release_request_context_signal_);
  // Finish initializing the HttpBridgeFactory.  We do this here because
  // building the user agent may block on some platforms.
  args.post_factory->Init(params.sync_user_agent,
                          base::Bind(&BindFetcherToDataTracker));
  registrar_->GetWorkers(&args.workers);
  args.extensions_activity = params.extensions_activity.get();
  args.change_delegate = registrar_.get();  // as SyncManager::ChangeDelegate
  args.credentials = params.credentials;
  args.invalidator_client_id = params.invalidator_client_id;
  args.restored_key_for_bootstrapping = params.restored_key_for_bootstrapping;
  args.restored_keystore_key_for_bootstrapping =
      params.restored_keystore_key_for_bootstrapping;
  args.engine_components_factory = std::move(params.engine_components_factory);
  args.encryptor = &encryptor_;
  args.unrecoverable_error_handler = params.unrecoverable_error_handler;
  args.report_unrecoverable_error_function =
      params.report_unrecoverable_error_function;
  args.cancelation_signal = &stop_syncing_signal_;
  args.saved_nigori_state = std::move(params.saved_nigori_state);
  sync_manager_->Init(&args);
  base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
      this, "SyncDirectory", base::ThreadTaskRunnerHandle::Get());
}

void SyncBackendHostCore::DoUpdateCredentials(
    const SyncCredentials& credentials) {
  DCHECK(thread_checker_.CalledOnValidThread());
  // UpdateCredentials can be called during backend initialization, possibly
  // when backend initialization has failed but hasn't notified the UI thread
  // yet. In that case, the sync manager may have been destroyed on the sync
  // thread before this task was executed, so we do nothing.
  if (sync_manager_) {
    sync_manager_->UpdateCredentials(credentials);
  }
}

void SyncBackendHostCore::DoStartSyncing(
    const ModelSafeRoutingInfo& routing_info,
    base::Time last_poll_time) {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->StartSyncingNormally(routing_info, last_poll_time);
}

void SyncBackendHostCore::DoSetEncryptionPassphrase(
    const std::string& passphrase,
    bool is_explicit) {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->GetEncryptionHandler()->SetEncryptionPassphrase(passphrase,
                                                                 is_explicit);
}

void SyncBackendHostCore::DoInitialProcessControlTypes() {
  DCHECK(thread_checker_.CalledOnValidThread());

  DVLOG(1) << "Initilalizing Control Types";

  // Initialize encryption.
  sync_manager_->GetEncryptionHandler()->Init();

  // Note: experiments are currently handled via SBH::AddExperimentalTypes,
  // which is called at the end of every sync cycle.
  // TODO(zea): eventually add an experiment handler and initialize it here.

  if (!sync_manager_->GetUserShare()) {  // Null in some tests.
    DVLOG(1) << "Skipping initialization of DeviceInfo";
    host_.Call(FROM_HERE,
               &SyncBackendHostImpl::HandleInitializationFailureOnFrontendLoop);
    return;
  }

  if (!sync_manager_->InitialSyncEndedTypes().HasAll(ControlTypes())) {
    LOG(ERROR) << "Failed to download control types";
    host_.Call(FROM_HERE,
               &SyncBackendHostImpl::HandleInitializationFailureOnFrontendLoop);
    return;
  }

  host_.Call(FROM_HERE,
             &SyncBackendHostImpl::HandleInitializationSuccessOnFrontendLoop,
             registrar_->GetLastConfiguredTypes(), js_backend_,
             debug_info_listener_,
             base::Passed(sync_manager_->GetModelTypeConnectorProxy()),
             sync_manager_->cache_guid());

  js_backend_.Reset();
  debug_info_listener_.Reset();
}

void SyncBackendHostCore::DoSetDecryptionPassphrase(
    const std::string& passphrase) {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->GetEncryptionHandler()->SetDecryptionPassphrase(passphrase);
}

void SyncBackendHostCore::DoEnableEncryptEverything() {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->GetEncryptionHandler()->EnableEncryptEverything();
}

void SyncBackendHostCore::ShutdownOnUIThread() {
  // This will cut short any blocking network tasks, cut short any in-progress
  // sync cycles, and prevent the creation of new blocking network tasks and new
  // sync cycles.  If there was an in-progress network request, it would have
  // had a reference to the RequestContextGetter.  This reference will be
  // dropped by the time this function returns.
  //
  // It is safe to call this even if Sync's backend classes have not been
  // initialized yet.  Those classes will receive the message when the sync
  // thread finally getes around to constructing them.
  stop_syncing_signal_.Signal();

  // This will drop the HttpBridgeFactory's reference to the
  // RequestContextGetter.  Once this has been called, the HttpBridgeFactory can
  // no longer be used to create new HttpBridge instances.  We can get away with
  // this because the stop_syncing_signal_ has already been signalled, which
  // guarantees that the ServerConnectionManager will no longer attempt to
  // create new connections.
  release_request_context_signal_.Signal();
}

void SyncBackendHostCore::DoShutdown(ShutdownReason reason) {
  DCHECK(thread_checker_.CalledOnValidThread());

  DoDestroySyncManager(reason);

  registrar_ = nullptr;

  if (reason == DISABLE_SYNC)
    syncable::Directory::DeleteDirectoryFiles(sync_data_folder_);

  host_.Reset();
  weak_ptr_factory_.InvalidateWeakPtrs();
}

void SyncBackendHostCore::DoDestroySyncManager(ShutdownReason reason) {
  DCHECK(thread_checker_.CalledOnValidThread());
  base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
      this);
  if (sync_manager_) {
    DisableDirectoryTypeDebugInfoForwarding();
    save_changes_timer_.reset();
    sync_manager_->RemoveObserver(this);
    sync_manager_->ShutdownOnSyncThread(reason);
    sync_manager_.reset();
  }
}

void SyncBackendHostCore::DoPurgeDisabledTypes(const ModelTypeSet& to_purge,
                                               const ModelTypeSet& to_journal,
                                               const ModelTypeSet& to_unapply) {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->PurgeDisabledTypes(to_purge, to_journal, to_unapply);
}

void SyncBackendHostCore::DoConfigureSyncer(
    ModelTypeConfigurer::ConfigureParams params) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!params.ready_task.is_null());
  DCHECK(!params.retry_callback.is_null());

  registrar_->ConfigureDataTypes(params.enabled_types, params.disabled_types);

  ModelSafeRoutingInfo routing_info;
  registrar_->GetModelSafeRoutingInfo(&routing_info);

  base::Closure chained_ready_task(base::Bind(
      &SyncBackendHostCore::DoFinishConfigureDataTypes,
      weak_ptr_factory_.GetWeakPtr(), params.to_download, params.ready_task));
  base::Closure chained_retry_task(
      base::Bind(&SyncBackendHostCore::DoRetryConfiguration,
                 weak_ptr_factory_.GetWeakPtr(), params.retry_callback));

  sync_manager_->ConfigureSyncer(params.reason, params.to_download,
                                 routing_info, chained_ready_task,
                                 chained_retry_task);
}

void SyncBackendHostCore::DoFinishConfigureDataTypes(
    ModelTypeSet types_to_config,
    const base::Callback<void(ModelTypeSet, ModelTypeSet)>& ready_task) {
  DCHECK(thread_checker_.CalledOnValidThread());

  // Update the enabled types for the bridge and sync manager.
  ModelSafeRoutingInfo routing_info;
  registrar_->GetModelSafeRoutingInfo(&routing_info);
  ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
  enabled_types.RemoveAll(ProxyTypes());

  const ModelTypeSet failed_configuration_types =
      Difference(types_to_config, sync_manager_->InitialSyncEndedTypes());
  const ModelTypeSet succeeded_configuration_types =
      Difference(types_to_config, failed_configuration_types);
  host_.Call(FROM_HERE,
             &SyncBackendHostImpl::FinishConfigureDataTypesOnFrontendLoop,
             enabled_types, succeeded_configuration_types,
             failed_configuration_types, ready_task);
}

void SyncBackendHostCore::DoRetryConfiguration(
    const base::Closure& retry_callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE, &SyncBackendHostImpl::RetryConfigurationOnFrontendLoop,
             retry_callback);
}

void SyncBackendHostCore::SendBufferedProtocolEventsAndEnableForwarding() {
  DCHECK(thread_checker_.CalledOnValidThread());
  forward_protocol_events_ = true;

  if (sync_manager_) {
    // Grab our own copy of the buffered events.
    // The buffer is not modified by this operation.
    std::vector<std::unique_ptr<ProtocolEvent>> buffered_events =
        sync_manager_->GetBufferedProtocolEvents();

    // Send them all over the fence to the host.
    for (auto& event : buffered_events) {
      host_.Call(FROM_HERE,
                 &SyncBackendHostImpl::HandleProtocolEventOnFrontendLoop,
                 base::Passed(std::move(event)));
    }
  }
}

void SyncBackendHostCore::DisableProtocolEventForwarding() {
  DCHECK(thread_checker_.CalledOnValidThread());
  forward_protocol_events_ = false;
}

void SyncBackendHostCore::EnableDirectoryTypeDebugInfoForwarding() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(sync_manager_);

  forward_type_info_ = true;

  if (!sync_manager_->HasDirectoryTypeDebugInfoObserver(this))
    sync_manager_->RegisterDirectoryTypeDebugInfoObserver(this);
  sync_manager_->RequestEmitDebugInfo();
}

void SyncBackendHostCore::DisableDirectoryTypeDebugInfoForwarding() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(sync_manager_);

  if (!forward_type_info_)
    return;

  forward_type_info_ = false;

  if (sync_manager_->HasDirectoryTypeDebugInfoObserver(this))
    sync_manager_->UnregisterDirectoryTypeDebugInfoObserver(this);
}

void SyncBackendHostCore::StartSavingChanges() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!save_changes_timer_.get());
  save_changes_timer_ = base::MakeUnique<base::RepeatingTimer>();
  save_changes_timer_->Start(
      FROM_HERE, base::TimeDelta::FromSeconds(kSaveChangesIntervalSeconds),
      this, &SyncBackendHostCore::SaveChanges);
}

void SyncBackendHostCore::SaveChanges() {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->SaveChanges();
}

void SyncBackendHostCore::DoClearServerData(
    const SyncManager::ClearServerDataCallback& frontend_callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  const SyncManager::ClearServerDataCallback callback =
      base::Bind(&SyncBackendHostCore::ClearServerDataDone,
                 weak_ptr_factory_.GetWeakPtr(), frontend_callback);
  sync_manager_->ClearServerData(callback);
}

void SyncBackendHostCore::DoOnCookieJarChanged(bool account_mismatch,
                                               bool empty_jar) {
  DCHECK(thread_checker_.CalledOnValidThread());
  sync_manager_->OnCookieJarChanged(account_mismatch, empty_jar);
}

void SyncBackendHostCore::ClearServerDataDone(
    const base::Closure& frontend_callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  host_.Call(FROM_HERE, &SyncBackendHostImpl::ClearServerDataDoneOnFrontendLoop,
             frontend_callback);
}

}  // namespace syncer