Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / drive / sync_client.cc
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.
4
5 #include "chrome/browser/chromeos/drive/sync_client.h"
6
7 #include <vector>
8
9 #include "base/bind.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"
19
20 using content::BrowserThread;
21
22 namespace drive {
23 namespace internal {
24
25 namespace {
26
27 // The delay constant is used to delay processing a sync task. We should not
28 // process SyncTasks immediately for the following reasons:
29 //
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.
33 //
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.
38 //
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;
42
43 // The delay constant is used to delay retrying a sync task on server errors.
44 const int kLongDelaySeconds = 600;
45
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) {
51   DCHECK(to_fetch);
52   DCHECK(to_update);
53
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);
60       continue;
61     }
62
63     bool should_update = false;
64     switch (entry.metadata_edit_state()) {
65       case ResourceEntry::CLEAN:
66         break;
67       case ResourceEntry::SYNCING:
68       case ResourceEntry::DIRTY:
69         should_update = true;
70         break;
71     }
72
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);
77
78       if (cache_entry.is_dirty())
79         should_update = true;
80     }
81     if (should_update)
82       to_update->push_back(local_id);
83   }
84   DCHECK(!it->HasError());
85 }
86
87 // Iterates cache entries and collects IDs of ones with obsolete cache files.
88 void CheckExistingPinnedFiles(ResourceMetadata* metadata,
89                               FileCache* cache,
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())
96       continue;
97
98     ResourceEntry entry;
99     FileError error = metadata->GetResourceEntryById(local_id, &entry);
100     if (error != FILE_ERROR_OK) {
101       LOG(WARNING) << "Entry not found: " << local_id;
102       continue;
103     }
104
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())
110       continue;
111
112     error = cache->Remove(local_id);
113     if (error != FILE_ERROR_OK) {
114       LOG(WARNING) << "Failed to remove cache entry: " << local_id;
115       continue;
116     }
117
118     error = cache->Pin(local_id);
119     if (error != FILE_ERROR_OK) {
120       LOG(WARNING) << "Failed to pin cache entry: " << local_id;
121       continue;
122     }
123
124     local_ids->push_back(local_id);
125   }
126   DCHECK(!it->HasError());
127 }
128
129 }  // namespace
130
131 SyncClient::SyncTask::SyncTask() : state(PENDING), should_run_again(false) {}
132 SyncClient::SyncTask::~SyncTask() {}
133
134 SyncClient::SyncClient(base::SequencedTaskRunner* blocking_task_runner,
135                        file_system::OperationObserver* observer,
136                        JobScheduler* scheduler,
137                        ResourceMetadata* metadata,
138                        FileCache* cache,
139                        const base::FilePath& temporary_file_directory)
140     : blocking_task_runner_(blocking_task_runner),
141       operation_observer_(observer),
142       metadata_(metadata),
143       cache_(cache),
144       download_operation_(new file_system::DownloadOperation(
145           blocking_task_runner,
146           observer,
147           scheduler,
148           metadata,
149           cache,
150           temporary_file_directory)),
151       entry_update_performer_(new EntryUpdatePerformer(blocking_task_runner,
152                                                        observer,
153                                                        scheduler,
154                                                        metadata,
155                                                        cache)),
156       delay_(base::TimeDelta::FromSeconds(kDelaySeconds)),
157       long_delay_(base::TimeDelta::FromSeconds(kLongDelaySeconds)),
158       weak_ptr_factory_(this) {
159   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
160 }
161
162 SyncClient::~SyncClient() {
163   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
164 }
165
166 void SyncClient::StartProcessingBacklog() {
167   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
168
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(
172       FROM_HERE,
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)));
178 }
179
180 void SyncClient::StartCheckingExistingPinnedFiles() {
181   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
182
183   std::vector<std::string>* local_ids = new std::vector<std::string>;
184   blocking_task_runner_->PostTaskAndReply(
185       FROM_HERE,
186       base::Bind(&CheckExistingPinnedFiles,
187                  metadata_,
188                  cache_,
189                  local_ids),
190       base::Bind(&SyncClient::AddFetchTasks,
191                  weak_ptr_factory_.GetWeakPtr(),
192                  base::Owned(local_ids)));
193 }
194
195 void SyncClient::AddFetchTask(const std::string& local_id) {
196   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
197   AddFetchTaskInternal(local_id, delay_);
198 }
199
200 void SyncClient::RemoveFetchTask(const std::string& local_id) {
201   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
202
203   SyncTasks::iterator it = tasks_.find(SyncTasks::key_type(FETCH, local_id));
204   if (it == tasks_.end())
205     return;
206
207   SyncTask* task = &it->second;
208   switch (task->state) {
209     case PENDING:
210       tasks_.erase(it);
211       break;
212     case RUNNING:
213       // TODO(kinaba): Cancel tasks in JobScheduler as well. crbug.com/248856
214       break;
215   }
216 }
217
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_);
222 }
223
224 void SyncClient::AddFetchTaskInternal(const std::string& local_id,
225                                       const base::TimeDelta& delay) {
226   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
227
228   SyncTask task;
229   task.task = base::Bind(
230       &file_system::DownloadOperation::EnsureFileDownloadedByLocalId,
231       base::Unretained(download_operation_.get()),
232       local_id,
233       ClientContext(BACKGROUND),
234       GetFileContentInitializedCallback(),
235       google_apis::GetContentCallback(),
236       base::Bind(&SyncClient::OnFetchFileComplete,
237                  weak_ptr_factory_.GetWeakPtr(),
238                  local_id));
239   AddTask(SyncTasks::key_type(FETCH, local_id), task, delay);
240 }
241
242 void SyncClient::AddUpdateTaskInternal(const ClientContext& context,
243                                        const std::string& local_id,
244                                        const base::TimeDelta& delay) {
245   SyncTask task;
246   task.task = base::Bind(
247       &EntryUpdatePerformer::UpdateEntry,
248       base::Unretained(entry_update_performer_.get()),
249       local_id,
250       context,
251       base::Bind(&SyncClient::OnUpdateComplete,
252                  weak_ptr_factory_.GetWeakPtr(),
253                  local_id));
254   AddTask(SyncTasks::key_type(UPDATE, local_id), task, delay);
255 }
256
257 void SyncClient::AddTask(const SyncTasks::key_type& key,
258                          const SyncTask& task,
259                          const base::TimeDelta& delay) {
260   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
261
262   SyncTasks::iterator it = tasks_.find(key);
263   if (it != tasks_.end()) {
264     switch (it->second.state) {
265       case PENDING:
266         // The same task will run, do nothing.
267         break;
268       case RUNNING:
269         // Something has changed since the task started. Schedule rerun.
270         it->second.should_run_again = true;
271         break;
272     }
273     return;
274   }
275
276   DCHECK_EQ(PENDING, task.state);
277   tasks_[key] = task;
278
279   base::MessageLoopProxy::current()->PostDelayedTask(
280       FROM_HERE,
281       base::Bind(&SyncClient::StartTask, weak_ptr_factory_.GetWeakPtr(), key),
282       delay);
283 }
284
285 void SyncClient::StartTask(const SyncTasks::key_type& key) {
286   SyncTasks::iterator it = tasks_.find(key);
287   if (it == tasks_.end())
288     return;
289
290   SyncTask* task = &it->second;
291   switch (task->state) {
292     case PENDING:
293       task->state = RUNNING;
294       task->task.Run();
295       break;
296     case RUNNING:  // Do nothing.
297       break;
298   }
299 }
300
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));
305
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);
312   }
313
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_);
318   }
319 }
320
321 void SyncClient::AddFetchTasks(const std::vector<std::string>* local_ids) {
322   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
323
324   for (size_t i = 0; i < local_ids->size(); ++i)
325     AddFetchTask((*local_ids)[i]);
326 }
327
328 bool SyncClient::OnTaskComplete(SyncType type, const std::string& local_id) {
329   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
330
331   const SyncTasks::key_type key(type, local_id);
332   SyncTasks::iterator it = tasks_.find(key);
333   DCHECK(it != tasks_.end());
334
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();
339     return false;
340   }
341
342   tasks_.erase(it);
343   return true;
344 }
345
346 void SyncClient::OnFetchFileComplete(const std::string& local_id,
347                                      FileError error,
348                                      const base::FilePath& local_path,
349                                      scoped_ptr<ResourceEntry> entry) {
350   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
351
352   if (!OnTaskComplete(FETCH, local_id))
353     return;
354
355   if (error == FILE_ERROR_OK) {
356     DVLOG(1) << "Fetched " << local_id << ": " << local_path.value();
357   } else {
358     switch (error) {
359       case FILE_ERROR_ABORT:
360         // If user cancels download, unpin the file so that we do not sync the
361         // file again.
362         base::PostTaskAndReplyWithResult(
363             blocking_task_runner_,
364             FROM_HERE,
365             base::Bind(&FileCache::Unpin, base::Unretained(cache_), local_id),
366             base::Bind(&util::EmptyFileOperationCallback));
367         break;
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_);
371         break;
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,
377             local_id);
378         break;
379       default:
380         operation_observer_->OnDriveSyncError(
381             file_system::DRIVE_SYNC_ERROR_MISC,
382             local_id);
383         LOG(WARNING) << "Failed to fetch " << local_id
384                      << ": " << FileErrorToString(error);
385     }
386   }
387 }
388
389 void SyncClient::OnUpdateComplete(const std::string& local_id,
390                                   FileError error) {
391   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
392
393   if (!OnTaskComplete(UPDATE, local_id))
394     return;
395
396   if (error == FILE_ERROR_OK) {
397     DVLOG(1) << "Updated " << local_id;
398   } else {
399     switch (error) {
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));
404         break;
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,
410             local_id);
411         break;
412       default:
413         operation_observer_->OnDriveSyncError(
414             file_system::DRIVE_SYNC_ERROR_MISC,
415             local_id);
416         LOG(WARNING) << "Failed to update " << local_id << ": "
417                      << FileErrorToString(error);
418     }
419   }
420 }
421
422 }  // namespace internal
423 }  // namespace drive