1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <memory>
6 #include <utility>
7 
8 #include "base/macros.h"
9 #include "base/run_loop.h"
10 #include "base/task/cancelable_task_tracker.h"
11 #include "chrome/browser/history/history_service_factory.h"
12 #include "components/history/core/browser/history_db_task.h"
13 #include "components/history/core/browser/history_service.h"
14 #include "content/public/test/test_utils.h"
15 
16 namespace {
17 
18 // Note: WaitableEvent is not used for synchronization between the main thread
19 // and history backend thread because the history subsystem posts tasks back
20 // to the main thread. Had we tried to Signal an event in such a task
21 // and Wait for it on the main thread, the task would not run at all because
22 // the main thread would be blocked on the Wait call, resulting in a deadlock.
23 
24 // A task to be scheduled on the history backend thread.
25 // Notifies the main thread after all history backend thread tasks have run.
26 class WaitForHistoryTask : public history::HistoryDBTask {
27  public:
WaitForHistoryTask()28   WaitForHistoryTask() {}
29 
RunOnDBThread(history::HistoryBackend * backend,history::HistoryDatabase * db)30   bool RunOnDBThread(history::HistoryBackend* backend,
31                      history::HistoryDatabase* db) override {
32     return true;
33   }
34 
DoneRunOnMainThread()35   void DoneRunOnMainThread() override {
36     base::RunLoop::QuitCurrentWhenIdleDeprecated();
37   }
38 
39  private:
~WaitForHistoryTask()40   ~WaitForHistoryTask() override {}
41 
42   DISALLOW_COPY_AND_ASSIGN(WaitForHistoryTask);
43 };
44 
45 }  // namespace
46 
WaitForHistoryBackendToRun(Profile * profile)47 void WaitForHistoryBackendToRun(Profile* profile) {
48   base::CancelableTaskTracker task_tracker;
49   std::unique_ptr<history::HistoryDBTask> task(new WaitForHistoryTask());
50   history::HistoryService* history = HistoryServiceFactory::GetForProfile(
51       profile, ServiceAccessType::EXPLICIT_ACCESS);
52   history->ScheduleDBTask(FROM_HERE, std::move(task), &task_tracker);
53   content::RunMessageLoop();
54 }
55