1 // Copyright (c) 2012 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.
5 #include "chrome/browser/chromeos/drive/sync_client.h"
10 #include "base/message_loop/message_loop_proxy.h"
11 #include "chrome/browser/chromeos/drive/drive.pb.h"
12 #include "chrome/browser/chromeos/drive/file_cache.h"
13 #include "chrome/browser/chromeos/drive/file_system/download_operation.h"
14 #include "chrome/browser/chromeos/drive/file_system/operation_observer.h"
15 #include "chrome/browser/chromeos/drive/file_system_util.h"
16 #include "chrome/browser/chromeos/drive/sync/entry_update_performer.h"
17 #include "content/public/browser/browser_thread.h"
18 #include "google_apis/drive/task_util.h"
20 using content::BrowserThread;
27 // The delay constant is used to delay processing a sync task. We should not
28 // process SyncTasks immediately for the following reasons:
30 // 1) For fetching, the user may accidentally click on "Make available
31 // offline" checkbox on a file, and immediately cancel it in a second.
32 // It's a waste to fetch the file in this case.
34 // 2) For uploading, file writing via HTML5 file system API is performed in
35 // two steps: 1) truncate a file to 0 bytes, 2) write contents. We
36 // shouldn't start uploading right after the step 1). Besides, the user
37 // may edit the same file repeatedly in a short period of time.
39 // TODO(satorux): We should find a way to handle the upload case more nicely,
40 // and shorten the delay. crbug.com/134774
41 const int kDelaySeconds = 5;
43 // The delay constant is used to delay retrying a sync task on server errors.
44 const int kLongDelaySeconds = 600;
46 // Iterates entries and appends IDs to |to_fetch| if the file is pinned but not
47 // fetched (not present locally), to |to_update| if the file needs update.
48 void CollectBacklog(ResourceMetadata* metadata,
49 std::vector<std::string>* to_fetch,
50 std::vector<std::string>* to_update) {
54 scoped_ptr<ResourceMetadata::Iterator> it = metadata->GetIterator();
55 for (; !it->IsAtEnd(); it->Advance()) {
56 const std::string& local_id = it->GetID();
57 const ResourceEntry& entry = it->GetValue();
58 if (entry.parent_local_id() == util::kDriveTrashDirLocalId) {
59 to_update->push_back(local_id);
63 bool should_update = false;
64 switch (entry.metadata_edit_state()) {
65 case ResourceEntry::CLEAN:
67 case ResourceEntry::SYNCING:
68 case ResourceEntry::DIRTY:
73 FileCacheEntry cache_entry;
74 if (it->GetCacheEntry(&cache_entry)) {
75 if (cache_entry.is_pinned() && !cache_entry.is_present())
76 to_fetch->push_back(local_id);
78 if (cache_entry.is_dirty())
82 to_update->push_back(local_id);
84 DCHECK(!it->HasError());
87 // Iterates cache entries and collects IDs of ones with obsolete cache files.
88 void CheckExistingPinnedFiles(ResourceMetadata* metadata,
90 std::vector<std::string>* local_ids) {
91 scoped_ptr<FileCache::Iterator> it = cache->GetIterator();
92 for (; !it->IsAtEnd(); it->Advance()) {
93 const FileCacheEntry& cache_entry = it->GetValue();
94 const std::string& local_id = it->GetID();
95 if (!cache_entry.is_pinned() || !cache_entry.is_present())
99 FileError error = metadata->GetResourceEntryById(local_id, &entry);
100 if (error != FILE_ERROR_OK) {
101 LOG(WARNING) << "Entry not found: " << local_id;
105 // If MD5s don't match, it indicates the local cache file is stale, unless
106 // the file is dirty (the MD5 is "local"). We should never re-fetch the
107 // file when we have a locally modified version.
108 if (entry.file_specific_info().md5() == cache_entry.md5() ||
109 cache_entry.is_dirty())
112 error = cache->Remove(local_id);
113 if (error != FILE_ERROR_OK) {
114 LOG(WARNING) << "Failed to remove cache entry: " << local_id;
118 error = cache->Pin(local_id);
119 if (error != FILE_ERROR_OK) {
120 LOG(WARNING) << "Failed to pin cache entry: " << local_id;
124 local_ids->push_back(local_id);
126 DCHECK(!it->HasError());
131 SyncClient::SyncTask::SyncTask() : state(PENDING), should_run_again(false) {}
132 SyncClient::SyncTask::~SyncTask() {}
134 SyncClient::SyncClient(base::SequencedTaskRunner* blocking_task_runner,
135 file_system::OperationObserver* observer,
136 JobScheduler* scheduler,
137 ResourceMetadata* metadata,
139 const base::FilePath& temporary_file_directory)
140 : blocking_task_runner_(blocking_task_runner),
141 operation_observer_(observer),
144 download_operation_(new file_system::DownloadOperation(
145 blocking_task_runner,
150 temporary_file_directory)),
151 entry_update_performer_(new EntryUpdatePerformer(blocking_task_runner,
156 delay_(base::TimeDelta::FromSeconds(kDelaySeconds)),
157 long_delay_(base::TimeDelta::FromSeconds(kLongDelaySeconds)),
158 weak_ptr_factory_(this) {
159 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
162 SyncClient::~SyncClient() {
163 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
166 void SyncClient::StartProcessingBacklog() {
167 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
169 std::vector<std::string>* to_fetch = new std::vector<std::string>;
170 std::vector<std::string>* to_update = new std::vector<std::string>;
171 blocking_task_runner_->PostTaskAndReply(
173 base::Bind(&CollectBacklog, metadata_, to_fetch, to_update),
174 base::Bind(&SyncClient::OnGetLocalIdsOfBacklog,
175 weak_ptr_factory_.GetWeakPtr(),
176 base::Owned(to_fetch),
177 base::Owned(to_update)));
180 void SyncClient::StartCheckingExistingPinnedFiles() {
181 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
183 std::vector<std::string>* local_ids = new std::vector<std::string>;
184 blocking_task_runner_->PostTaskAndReply(
186 base::Bind(&CheckExistingPinnedFiles,
190 base::Bind(&SyncClient::AddFetchTasks,
191 weak_ptr_factory_.GetWeakPtr(),
192 base::Owned(local_ids)));
195 void SyncClient::AddFetchTask(const std::string& local_id) {
196 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
197 AddFetchTaskInternal(local_id, delay_);
200 void SyncClient::RemoveFetchTask(const std::string& local_id) {
201 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
203 SyncTasks::iterator it = tasks_.find(SyncTasks::key_type(FETCH, local_id));
204 if (it == tasks_.end())
207 SyncTask* task = &it->second;
208 switch (task->state) {
213 // TODO(kinaba): Cancel tasks in JobScheduler as well. crbug.com/248856
218 void SyncClient::AddUpdateTask(const ClientContext& context,
219 const std::string& local_id) {
220 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
221 AddUpdateTaskInternal(context, local_id, delay_);
224 void SyncClient::AddFetchTaskInternal(const std::string& local_id,
225 const base::TimeDelta& delay) {
226 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
229 task.task = base::Bind(
230 &file_system::DownloadOperation::EnsureFileDownloadedByLocalId,
231 base::Unretained(download_operation_.get()),
233 ClientContext(BACKGROUND),
234 GetFileContentInitializedCallback(),
235 google_apis::GetContentCallback(),
236 base::Bind(&SyncClient::OnFetchFileComplete,
237 weak_ptr_factory_.GetWeakPtr(),
239 AddTask(SyncTasks::key_type(FETCH, local_id), task, delay);
242 void SyncClient::AddUpdateTaskInternal(const ClientContext& context,
243 const std::string& local_id,
244 const base::TimeDelta& delay) {
246 task.task = base::Bind(
247 &EntryUpdatePerformer::UpdateEntry,
248 base::Unretained(entry_update_performer_.get()),
251 base::Bind(&SyncClient::OnUpdateComplete,
252 weak_ptr_factory_.GetWeakPtr(),
254 AddTask(SyncTasks::key_type(UPDATE, local_id), task, delay);
257 void SyncClient::AddTask(const SyncTasks::key_type& key,
258 const SyncTask& task,
259 const base::TimeDelta& delay) {
260 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
262 SyncTasks::iterator it = tasks_.find(key);
263 if (it != tasks_.end()) {
264 switch (it->second.state) {
266 // The same task will run, do nothing.
269 // Something has changed since the task started. Schedule rerun.
270 it->second.should_run_again = true;
276 DCHECK_EQ(PENDING, task.state);
279 base::MessageLoopProxy::current()->PostDelayedTask(
281 base::Bind(&SyncClient::StartTask, weak_ptr_factory_.GetWeakPtr(), key),
285 void SyncClient::StartTask(const SyncTasks::key_type& key) {
286 SyncTasks::iterator it = tasks_.find(key);
287 if (it == tasks_.end())
290 SyncTask* task = &it->second;
291 switch (task->state) {
293 task->state = RUNNING;
296 case RUNNING: // Do nothing.
301 void SyncClient::OnGetLocalIdsOfBacklog(
302 const std::vector<std::string>* to_fetch,
303 const std::vector<std::string>* to_update) {
304 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
306 // Give priority to upload tasks over fetch tasks, so that dirty files are
307 // uploaded as soon as possible.
308 for (size_t i = 0; i < to_update->size(); ++i) {
309 const std::string& local_id = (*to_update)[i];
310 DVLOG(1) << "Queuing to update: " << local_id;
311 AddUpdateTask(ClientContext(BACKGROUND), local_id);
314 for (size_t i = 0; i < to_fetch->size(); ++i) {
315 const std::string& local_id = (*to_fetch)[i];
316 DVLOG(1) << "Queuing to fetch: " << local_id;
317 AddFetchTaskInternal(local_id, delay_);
321 void SyncClient::AddFetchTasks(const std::vector<std::string>* local_ids) {
322 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
324 for (size_t i = 0; i < local_ids->size(); ++i)
325 AddFetchTask((*local_ids)[i]);
328 bool SyncClient::OnTaskComplete(SyncType type, const std::string& local_id) {
329 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
331 const SyncTasks::key_type key(type, local_id);
332 SyncTasks::iterator it = tasks_.find(key);
333 DCHECK(it != tasks_.end());
335 if (it->second.should_run_again) {
336 DVLOG(1) << "Running again: type = " << type << ", id = " << local_id;
337 it->second.should_run_again = false;
338 it->second.task.Run();
346 void SyncClient::OnFetchFileComplete(const std::string& local_id,
348 const base::FilePath& local_path,
349 scoped_ptr<ResourceEntry> entry) {
350 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
352 if (!OnTaskComplete(FETCH, local_id))
355 if (error == FILE_ERROR_OK) {
356 DVLOG(1) << "Fetched " << local_id << ": " << local_path.value();
359 case FILE_ERROR_ABORT:
360 // If user cancels download, unpin the file so that we do not sync the
362 base::PostTaskAndReplyWithResult(
363 blocking_task_runner_,
365 base::Bind(&FileCache::Unpin, base::Unretained(cache_), local_id),
366 base::Bind(&util::EmptyFileOperationCallback));
368 case FILE_ERROR_NO_CONNECTION:
369 // Add the task again so that we'll retry once the connection is back.
370 AddFetchTaskInternal(local_id, delay_);
372 case FILE_ERROR_SERVICE_UNAVAILABLE:
373 // Add the task again so that we'll retry once the service is back.
374 AddFetchTaskInternal(local_id, long_delay_);
375 operation_observer_->OnDriveSyncError(
376 file_system::DRIVE_SYNC_ERROR_SERVICE_UNAVAILABLE,
380 operation_observer_->OnDriveSyncError(
381 file_system::DRIVE_SYNC_ERROR_MISC,
383 LOG(WARNING) << "Failed to fetch " << local_id
384 << ": " << FileErrorToString(error);
389 void SyncClient::OnUpdateComplete(const std::string& local_id,
391 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
393 if (!OnTaskComplete(UPDATE, local_id))
396 if (error == FILE_ERROR_OK) {
397 DVLOG(1) << "Updated " << local_id;
400 case FILE_ERROR_NO_CONNECTION:
401 // Add the task again so that we'll retry once the connection is back.
402 AddUpdateTaskInternal(ClientContext(BACKGROUND), local_id,
403 base::TimeDelta::FromSeconds(0));
405 case FILE_ERROR_SERVICE_UNAVAILABLE:
406 // Add the task again so that we'll retry once the service is back.
407 AddUpdateTaskInternal(ClientContext(BACKGROUND), local_id, long_delay_);
408 operation_observer_->OnDriveSyncError(
409 file_system::DRIVE_SYNC_ERROR_SERVICE_UNAVAILABLE,
413 operation_observer_->OnDriveSyncError(
414 file_system::DRIVE_SYNC_ERROR_MISC,
416 LOG(WARNING) << "Failed to update " << local_id << ": "
417 << FileErrorToString(error);
422 } // namespace internal