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 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync_file_system/local/local_file_sync_context.h"
#include <memory>
#include <utility>
#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/observer_list.h"
#include "base/task/single_thread_task_runner.h"
#include "chrome/browser/sync_file_system/file_change.h"
#include "chrome/browser/sync_file_system/local/local_file_change_tracker.h"
#include "chrome/browser/sync_file_system/local/local_origin_change_observer.h"
#include "chrome/browser/sync_file_system/local/root_delete_helper.h"
#include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
#include "chrome/browser/sync_file_system/local/syncable_file_operation_runner.h"
#include "chrome/browser/sync_file_system/logger.h"
#include "chrome/browser/sync_file_system/sync_file_metadata.h"
#include "chrome/browser/sync_file_system/syncable_file_system_util.h"
#include "storage/browser/blob/scoped_file.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_file_util.h"
#include "storage/browser/file_system/file_system_operation_context.h"
#include "storage/browser/file_system/file_system_operation_runner.h"
#include "storage/browser/file_system/file_system_url.h"
#include "storage/common/file_system/file_system_types.h"
#include "storage/common/file_system/file_system_util.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "url/origin.h"
using storage::FileSystemContext;
using storage::FileSystemFileUtil;
using storage::FileSystemOperation;
using storage::FileSystemOperationContext;
using storage::FileSystemURL;
namespace sync_file_system {
namespace {
const int kMaxConcurrentSyncableOperation = 3;
const int kNotifyChangesDurationInSec = 1;
const int kMaxURLsToFetchForLocalSync = 5;
const base::FilePath::CharType kSnapshotDir[] = FILE_PATH_LITERAL("snapshots");
} // namespace
LocalFileSyncContext::LocalFileSyncContext(
const base::FilePath& base_path,
leveldb::Env* env_override,
base::SingleThreadTaskRunner* ui_task_runner,
base::SingleThreadTaskRunner* io_task_runner)
: local_base_path_(base_path.Append(FILE_PATH_LITERAL("local"))),
env_override_(env_override),
ui_task_runner_(ui_task_runner),
io_task_runner_(io_task_runner),
shutdown_on_ui_(false),
shutdown_on_io_(false),
mock_notify_changes_duration_in_sec_(-1) {
DCHECK(base_path.IsAbsolute());
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
}
void LocalFileSyncContext::MaybeInitializeFileSystemContext(
const GURL& source_url,
FileSystemContext* file_system_context,
SyncStatusCallback callback) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
if (base::Contains(file_system_contexts_, file_system_context)) {
// The context has been already initialized. Just dispatch the callback
// with SYNC_STATUS_OK.
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), SYNC_STATUS_OK));
return;
}
StatusCallbackQueue& callback_queue =
pending_initialize_callbacks_[file_system_context];
callback_queue.push_back(std::move(callback));
if (callback_queue.size() > 1)
return;
// The sync service always expects the origin (app) is initialized
// for writable way (even when MaybeInitializeFileSystemContext is called
// from read-only OpenFileSystem), so open the filesystem with
// CREATE_IF_NONEXISTENT here.
storage::FileSystemBackend::ResolveURLCallback open_filesystem_callback =
base::BindOnce(
&LocalFileSyncContext::InitializeFileSystemContextOnIOThread, this,
source_url, base::RetainedRef(file_system_context));
const blink::StorageKey storage_key =
blink::StorageKey::CreateFirstParty(url::Origin::Create(source_url));
io_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&storage::SandboxFileSystemBackendDelegate::OpenFileSystem,
base::Unretained(file_system_context->sandbox_delegate()),
storage::BucketLocator::ForDefaultBucket(storage_key),
storage::kFileSystemTypeSyncable,
storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
std::move(open_filesystem_callback), GURL()));
}
void LocalFileSyncContext::ShutdownOnUIThread() {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
shutdown_on_ui_ = true;
io_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::ShutdownOnIOThread, this));
}
void LocalFileSyncContext::GetFileForLocalSync(
FileSystemContext* file_system_context,
LocalFileSyncInfoCallback callback) {
DCHECK(file_system_context);
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
file_system_context->default_file_task_runner()->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::GetNextURLsForSyncOnFileThread,
this, base::RetainedRef(file_system_context)),
base::BindOnce(&LocalFileSyncContext::TryPrepareForLocalSync, this,
base::RetainedRef(file_system_context),
std::move(callback)));
}
void LocalFileSyncContext::ClearChangesForURL(
FileSystemContext* file_system_context,
const FileSystemURL& url,
base::OnceClosure done_callback) {
// This is initially called on UI thread and to be relayed to FILE thread.
DCHECK(file_system_context);
if (!file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
file_system_context->default_file_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&LocalFileSyncContext::ClearChangesForURL,
this, base::RetainedRef(file_system_context),
url, std::move(done_callback)));
return;
}
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
backend->change_tracker()->ClearChangesForURL(url);
// Call the completion callback on UI thread.
ui_task_runner_->PostTask(FROM_HERE, std::move(done_callback));
}
void LocalFileSyncContext::FinalizeSnapshotSync(
storage::FileSystemContext* file_system_context,
const storage::FileSystemURL& url,
SyncStatusCode sync_finish_status,
base::OnceClosure done_callback) {
DCHECK(file_system_context);
DCHECK(url.is_valid());
if (!file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence()) {
file_system_context->default_file_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::FinalizeSnapshotSync, this,
base::RetainedRef(file_system_context), url,
sync_finish_status, std::move(done_callback)));
return;
}
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
if (sync_finish_status == SYNC_STATUS_OK ||
sync_finish_status == SYNC_STATUS_HAS_CONFLICT) {
// Commit the in-memory mirror change.
backend->change_tracker()->ResetToMirrorAndCommitChangesForURL(url);
} else {
// Abort in-memory mirror change.
backend->change_tracker()->RemoveMirrorAndCommitChangesForURL(url);
}
// We've been keeping it in writing mode, so clear the writing counter
// to unblock sync activities.
io_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::FinalizeSnapshotSyncOnIOThread,
this, url));
// Call the completion callback on UI thread.
ui_task_runner_->PostTask(FROM_HERE, std::move(done_callback));
}
void LocalFileSyncContext::FinalizeExclusiveSync(
storage::FileSystemContext* file_system_context,
const storage::FileSystemURL& url,
bool clear_local_changes,
base::OnceClosure done_callback) {
DCHECK(file_system_context);
if (!url.is_valid()) {
std::move(done_callback).Run();
return;
}
if (clear_local_changes) {
ClearChangesForURL(
file_system_context, url,
base::BindOnce(&LocalFileSyncContext::FinalizeExclusiveSync, this,
base::RetainedRef(file_system_context), url, false,
std::move(done_callback)));
return;
}
io_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&LocalFileSyncContext::ClearSyncFlagOnIOThread,
this, url, false /* for_snapshot_sync */));
std::move(done_callback).Run();
}
void LocalFileSyncContext::PrepareForSync(
FileSystemContext* file_system_context,
const FileSystemURL& url,
SyncMode sync_mode,
LocalFileSyncInfoCallback callback) {
// This is initially called on UI thread and to be relayed to IO thread.
if (!io_task_runner_->RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
io_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&LocalFileSyncContext::PrepareForSync, this,
base::RetainedRef(file_system_context), url,
sync_mode, std::move(callback)));
return;
}
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
const bool syncable = sync_status()->IsSyncable(url);
// Disable writing if it's ready to be synced.
if (syncable)
sync_status()->StartSyncing(url);
ui_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::DidGetWritingStatusForSync, this,
base::RetainedRef(file_system_context),
syncable ? SYNC_STATUS_OK : SYNC_STATUS_FILE_BUSY, url,
sync_mode, std::move(callback)));
}
void LocalFileSyncContext::RegisterURLForWaitingSync(
const FileSystemURL& url,
base::OnceClosure on_syncable_callback) {
// This is initially called on UI thread and to be relayed to IO thread.
if (!io_task_runner_->RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
io_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::RegisterURLForWaitingSync, this,
url, std::move(on_syncable_callback)));
return;
}
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_io_)
return;
if (sync_status()->IsSyncable(url)) {
// No need to register; fire the callback now.
ui_task_runner_->PostTask(FROM_HERE, std::move(on_syncable_callback));
return;
}
url_waiting_sync_on_io_ = url;
url_syncable_callback_ = std::move(on_syncable_callback);
}
void LocalFileSyncContext::ApplyRemoteChange(
FileSystemContext* file_system_context,
const FileChange& change,
const base::FilePath& local_path,
const FileSystemURL& url,
SyncStatusCallback callback) {
if (!io_task_runner_->RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
io_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::ApplyRemoteChange, this,
base::RetainedRef(file_system_context), change,
local_path, url, std::move(callback)));
return;
}
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(!sync_status()->IsWritable(url));
DCHECK(!sync_status()->IsWriting(url));
FileSystemOperation::StatusCallback operation_callback;
switch (change.change()) {
case FileChange::FILE_CHANGE_DELETE:
HandleRemoteDelete(file_system_context, url, std::move(callback));
return;
case FileChange::FILE_CHANGE_ADD_OR_UPDATE:
HandleRemoteAddOrUpdate(file_system_context, change, local_path, url,
std::move(callback));
return;
}
NOTREACHED();
}
void LocalFileSyncContext::HandleRemoteDelete(
FileSystemContext* file_system_context,
const FileSystemURL& url,
SyncStatusCallback callback) {
FileSystemURL url_for_sync = CreateSyncableFileSystemURLForSync(
file_system_context, url);
// Handle root directory case differently.
if (storage::VirtualPath::IsRootPath(url.path())) {
DCHECK(!root_delete_helper_);
root_delete_helper_ = std::make_unique<RootDeleteHelper>(
file_system_context, sync_status(), url,
base::BindOnce(&LocalFileSyncContext::DidApplyRemoteChange, this, url,
std::move(callback)));
root_delete_helper_->Run();
return;
}
file_system_context->operation_runner()->Remove(
url_for_sync, true /* recursive */,
base::BindOnce(&LocalFileSyncContext::DidApplyRemoteChange, this, url,
std::move(callback)));
}
void LocalFileSyncContext::HandleRemoteAddOrUpdate(
FileSystemContext* file_system_context,
const FileChange& change,
const base::FilePath& local_path,
const FileSystemURL& url,
SyncStatusCallback callback) {
FileSystemURL url_for_sync = CreateSyncableFileSystemURLForSync(
file_system_context, url);
if (storage::VirtualPath::IsRootPath(url.path())) {
DidApplyRemoteChange(url, std::move(callback), base::File::FILE_OK);
return;
}
file_system_context->operation_runner()->Remove(
url_for_sync, true /* recursive */,
base::BindOnce(
&LocalFileSyncContext::DidRemoveExistingEntryForRemoteAddOrUpdate,
this, base::RetainedRef(file_system_context), change, local_path, url,
std::move(callback)));
}
void LocalFileSyncContext::DidRemoveExistingEntryForRemoteAddOrUpdate(
FileSystemContext* file_system_context,
const FileChange& change,
const base::FilePath& local_path,
const FileSystemURL& url,
SyncStatusCallback callback,
base::File::Error error) {
// Remove() may fail if the target entry does not exist (which is ok),
// so we ignore |error| here.
if (shutdown_on_io_) {
std::move(callback).Run(SYNC_FILE_ERROR_ABORT);
return;
}
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(!sync_status()->IsWritable(url));
DCHECK(!sync_status()->IsWriting(url));
FileSystemURL url_for_sync = CreateSyncableFileSystemURLForSync(
file_system_context, url);
FileSystemOperation::StatusCallback operation_callback =
base::BindOnce(&LocalFileSyncContext::DidApplyRemoteChange, this, url,
std::move(callback));
DCHECK_EQ(FileChange::FILE_CHANGE_ADD_OR_UPDATE, change.change());
switch (change.file_type()) {
case SYNC_FILE_TYPE_FILE: {
DCHECK(!local_path.empty());
base::FilePath dir_path = storage::VirtualPath::DirName(url.path());
if (dir_path.empty() ||
storage::VirtualPath::DirName(dir_path) == dir_path) {
// Copying into the root directory.
file_system_context->operation_runner()->CopyInForeignFile(
local_path, url_for_sync, std::move(operation_callback));
} else {
FileSystemURL dir_url = file_system_context->CreateCrackedFileSystemURL(
url_for_sync.storage_key(), url_for_sync.mount_type(),
storage::VirtualPath::DirName(url_for_sync.virtual_path()));
file_system_context->operation_runner()->CreateDirectory(
dir_url, false /* exclusive */, true /* recursive */,
base::BindOnce(&LocalFileSyncContext::DidCreateDirectoryForCopyIn,
this, base::RetainedRef(file_system_context),
local_path, url, std::move(operation_callback)));
}
break;
}
case SYNC_FILE_TYPE_DIRECTORY:
file_system_context->operation_runner()->CreateDirectory(
url_for_sync, false /* exclusive */, true /* recursive */,
std::move(operation_callback));
break;
case SYNC_FILE_TYPE_UNKNOWN:
NOTREACHED() << "File type unknown for ADD_OR_UPDATE change";
}
}
void LocalFileSyncContext::RecordFakeLocalChange(
FileSystemContext* file_system_context,
const FileSystemURL& url,
const FileChange& change,
SyncStatusCallback callback) {
// This is called on UI thread and to be relayed to FILE thread.
DCHECK(file_system_context);
if (!file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
file_system_context->default_file_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&LocalFileSyncContext::RecordFakeLocalChange,
this, base::RetainedRef(file_system_context),
url, change, std::move(callback)));
return;
}
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
backend->change_tracker()->MarkDirtyOnDatabase(url);
backend->change_tracker()->RecordChange(url, change);
// Fire the callback on UI thread.
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), SYNC_STATUS_OK));
}
void LocalFileSyncContext::GetFileMetadata(
FileSystemContext* file_system_context,
const FileSystemURL& url,
SyncFileMetadataCallback callback) {
// This is initially called on UI thread and to be relayed to IO thread.
if (!io_task_runner_->RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
io_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&LocalFileSyncContext::GetFileMetadata, this,
base::RetainedRef(file_system_context), url,
std::move(callback)));
return;
}
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
FileSystemURL url_for_sync = CreateSyncableFileSystemURLForSync(
file_system_context, url);
file_system_context->operation_runner()->GetMetadata(
url_for_sync,
{storage::FileSystemOperation::GetMetadataField::kIsDirectory,
storage::FileSystemOperation::GetMetadataField::kSize,
storage::FileSystemOperation::GetMetadataField::kLastModified},
base::BindOnce(&LocalFileSyncContext::DidGetFileMetadata, this,
std::move(callback)));
}
void LocalFileSyncContext::HasPendingLocalChanges(
FileSystemContext* file_system_context,
const FileSystemURL& url,
HasPendingLocalChangeCallback callback) {
// This gets called on UI thread and relays the task on FILE thread.
DCHECK(file_system_context);
if (!file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
file_system_context->default_file_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&LocalFileSyncContext::HasPendingLocalChanges,
this, base::RetainedRef(file_system_context),
url, std::move(callback)));
return;
}
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
FileChangeList changes;
backend->change_tracker()->GetChangesForURL(url, &changes);
// Fire the callback on UI thread.
ui_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), SYNC_STATUS_OK, !changes.empty()));
}
void LocalFileSyncContext::PromoteDemotedChanges(
const GURL& origin,
storage::FileSystemContext* file_system_context,
base::OnceClosure callback) {
// This is initially called on UI thread and to be relayed to FILE thread.
DCHECK(file_system_context);
if (!file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
file_system_context->default_file_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::PromoteDemotedChanges, this,
origin, base::RetainedRef(file_system_context),
std::move(callback)));
return;
}
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
if (!backend->change_tracker()->PromoteDemotedChanges()) {
ui_task_runner_->PostTask(FROM_HERE, std::move(callback));
return;
}
io_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&LocalFileSyncContext::UpdateChangesForOrigin,
this, origin, std::move(callback)));
}
void LocalFileSyncContext::UpdateChangesForOrigin(const GURL& origin,
base::OnceClosure callback) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_io_)
return;
origins_with_pending_changes_.insert(origin);
ScheduleNotifyChangesUpdatedOnIOThread(std::move(callback));
}
void LocalFileSyncContext::AddOriginChangeObserver(
LocalOriginChangeObserver* observer) {
origin_change_observers_.AddObserver(observer);
}
void LocalFileSyncContext::RemoveOriginChangeObserver(
LocalOriginChangeObserver* observer) {
origin_change_observers_.RemoveObserver(observer);
}
base::WeakPtr<SyncableFileOperationRunner>
LocalFileSyncContext::operation_runner() const {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (operation_runner_)
return operation_runner_->AsWeakPtr();
return base::WeakPtr<SyncableFileOperationRunner>();
}
LocalFileSyncStatus* LocalFileSyncContext::sync_status() const {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
return sync_status_.get();
}
void LocalFileSyncContext::OnSyncEnabled(const FileSystemURL& url) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_io_)
return;
UpdateChangesForOrigin(url.origin().GetURL(), base::DoNothing());
if (url_syncable_callback_.is_null() ||
sync_status()->IsWriting(url_waiting_sync_on_io_)) {
return;
}
// TODO(kinuko): may want to check how many pending tasks we have.
ui_task_runner_->PostTask(FROM_HERE, std::move(url_syncable_callback_));
}
void LocalFileSyncContext::OnWriteEnabled(const FileSystemURL& url) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
// Nothing to do for now.
}
LocalFileSyncContext::~LocalFileSyncContext() = default;
void LocalFileSyncContext::ScheduleNotifyChangesUpdatedOnIOThread(
base::OnceClosure callback) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_io_)
return;
pending_completion_callbacks_.push_back(std::move(callback));
if (base::Time::Now() > last_notified_changes_ + NotifyChangesDuration()) {
NotifyAvailableChangesOnIOThread();
} else if (!timer_on_io_->IsRunning()) {
timer_on_io_->Start(
FROM_HERE, NotifyChangesDuration(),
base::BindOnce(&LocalFileSyncContext::NotifyAvailableChangesOnIOThread,
base::Unretained(this)));
}
}
void LocalFileSyncContext::NotifyAvailableChangesOnIOThread() {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_io_)
return;
std::vector<base::OnceClosure> completion_callbacks;
completion_callbacks.swap(pending_completion_callbacks_);
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&LocalFileSyncContext::NotifyAvailableChanges,
this, origins_with_pending_changes_,
std::move(completion_callbacks)));
last_notified_changes_ = base::Time::Now();
origins_with_pending_changes_.clear();
}
void LocalFileSyncContext::NotifyAvailableChanges(
const std::set<GURL>& origins,
std::vector<base::OnceClosure> callbacks) {
for (auto& observer : origin_change_observers_)
observer.OnChangesAvailableInOrigins(origins);
for (auto& callback : callbacks)
std::move(callback).Run();
}
void LocalFileSyncContext::ShutdownOnIOThread() {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
shutdown_on_io_ = true;
operation_runner_.reset();
root_delete_helper_.reset();
sync_status_.reset();
timer_on_io_.reset();
}
void LocalFileSyncContext::InitializeFileSystemContextOnIOThread(
const GURL& source_url,
FileSystemContext* file_system_context,
const GURL& /* root */,
const std::string& /* name */,
base::File::Error error) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_io_)
error = base::File::FILE_ERROR_ABORT;
if (error != base::File::FILE_OK) {
DidInitialize(source_url, file_system_context,
FileErrorToSyncStatusCode(error));
return;
}
DCHECK(file_system_context);
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
if (!backend->change_tracker()) {
// Create and initialize LocalFileChangeTracker and call back this method
// later again.
std::set<GURL>* origins_with_changes = new std::set<GURL>;
std::unique_ptr<LocalFileChangeTracker>* tracker_ptr(
new std::unique_ptr<LocalFileChangeTracker>);
file_system_context->default_file_task_runner()->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(
&LocalFileSyncContext::InitializeChangeTrackerOnFileThread, this,
tracker_ptr, base::RetainedRef(file_system_context),
origins_with_changes),
base::BindOnce(
&LocalFileSyncContext::DidInitializeChangeTrackerOnIOThread, this,
base::Owned(tracker_ptr), source_url,
base::RetainedRef(file_system_context),
base::Owned(origins_with_changes)));
return;
}
if (!operation_runner_) {
DCHECK(!sync_status_);
DCHECK(!timer_on_io_);
sync_status_ = std::make_unique<LocalFileSyncStatus>();
timer_on_io_ = std::make_unique<base::OneShotTimer>();
operation_runner_ = std::make_unique<SyncableFileOperationRunner>(
kMaxConcurrentSyncableOperation, sync_status_.get());
sync_status_->AddObserver(this);
}
backend->set_sync_context(this);
DidInitialize(source_url, file_system_context,
SYNC_STATUS_OK);
}
SyncStatusCode LocalFileSyncContext::InitializeChangeTrackerOnFileThread(
std::unique_ptr<LocalFileChangeTracker>* tracker_ptr,
FileSystemContext* file_system_context,
std::set<GURL>* origins_with_changes) {
DCHECK(file_system_context);
DCHECK(tracker_ptr);
DCHECK(origins_with_changes);
*tracker_ptr = std::make_unique<LocalFileChangeTracker>(
file_system_context->partition_path(), env_override_,
file_system_context->default_file_task_runner());
const SyncStatusCode status = (*tracker_ptr)->Initialize(file_system_context);
if (status != SYNC_STATUS_OK)
return status;
// Get all origins that have pending changes.
FileSystemURLQueue urls;
(*tracker_ptr)->GetNextChangedURLs(&urls, 0);
for (FileSystemURLQueue::iterator iter = urls.begin();
iter != urls.end(); ++iter) {
origins_with_changes->insert(iter->origin().GetURL());
}
// Creates snapshot directory.
base::CreateDirectory(local_base_path_.Append(kSnapshotDir));
return status;
}
void LocalFileSyncContext::DidInitializeChangeTrackerOnIOThread(
std::unique_ptr<LocalFileChangeTracker>* tracker_ptr,
const GURL& source_url,
FileSystemContext* file_system_context,
std::set<GURL>* origins_with_changes,
SyncStatusCode status) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
DCHECK(file_system_context);
DCHECK(origins_with_changes);
if (shutdown_on_io_)
status = SYNC_STATUS_ABORT;
if (status != SYNC_STATUS_OK) {
DidInitialize(source_url, file_system_context, status);
return;
}
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
backend->SetLocalFileChangeTracker(std::move(*tracker_ptr));
origins_with_pending_changes_.insert(origins_with_changes->begin(),
origins_with_changes->end());
ScheduleNotifyChangesUpdatedOnIOThread(base::DoNothing());
InitializeFileSystemContextOnIOThread(source_url, file_system_context,
GURL(), std::string(),
base::File::FILE_OK);
}
void LocalFileSyncContext::DidInitialize(
const GURL& source_url,
FileSystemContext* file_system_context,
SyncStatusCode status) {
if (!ui_task_runner_->RunsTasksInCurrentSequence()) {
ui_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::DidInitialize, this, source_url,
base::RetainedRef(file_system_context), status));
return;
}
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
DCHECK(!base::Contains(file_system_contexts_, file_system_context));
DCHECK(base::Contains(pending_initialize_callbacks_, file_system_context));
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
file_system_contexts_.insert(file_system_context);
StatusCallbackQueue& callback_queue =
pending_initialize_callbacks_[file_system_context];
while (!callback_queue.empty()) {
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(callback_queue.front()), status));
callback_queue.pop_front();
}
pending_initialize_callbacks_.erase(file_system_context);
}
std::unique_ptr<LocalFileSyncContext::FileSystemURLQueue>
LocalFileSyncContext::GetNextURLsForSyncOnFileThread(
FileSystemContext* file_system_context) {
DCHECK(file_system_context);
DCHECK(file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence());
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
std::unique_ptr<FileSystemURLQueue> urls(new FileSystemURLQueue);
backend->change_tracker()->GetNextChangedURLs(
urls.get(), kMaxURLsToFetchForLocalSync);
for (FileSystemURLQueue::iterator iter = urls->begin();
iter != urls->end(); ++iter)
backend->change_tracker()->DemoteChangesForURL(*iter);
return urls;
}
void LocalFileSyncContext::TryPrepareForLocalSync(
FileSystemContext* file_system_context,
LocalFileSyncInfoCallback callback,
std::unique_ptr<FileSystemURLQueue> urls) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
DCHECK(urls);
if (shutdown_on_ui_) {
std::move(callback).Run(SYNC_STATUS_ABORT, LocalFileSyncInfo(),
storage::ScopedFile());
return;
}
if (urls->empty()) {
std::move(callback).Run(SYNC_STATUS_NO_CHANGE_TO_SYNC, LocalFileSyncInfo(),
storage::ScopedFile());
return;
}
const FileSystemURL url = urls->front();
urls->pop_front();
PrepareForSync(
file_system_context, url, SYNC_SNAPSHOT,
base::BindOnce(&LocalFileSyncContext::DidTryPrepareForLocalSync, this,
base::RetainedRef(file_system_context), std::move(urls),
std::move(callback)));
}
void LocalFileSyncContext::DidTryPrepareForLocalSync(
FileSystemContext* file_system_context,
std::unique_ptr<FileSystemURLQueue> remaining_urls,
LocalFileSyncInfoCallback callback,
SyncStatusCode status,
const LocalFileSyncInfo& sync_file_info,
storage::ScopedFile snapshot) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
if (status != SYNC_STATUS_FILE_BUSY) {
PromoteDemotedChangesForURLs(file_system_context,
std::move(remaining_urls));
std::move(callback).Run(status, sync_file_info, std::move(snapshot));
return;
}
PromoteDemotedChangesForURL(file_system_context, sync_file_info.url);
// Recursively call TryPrepareForLocalSync with remaining_urls.
TryPrepareForLocalSync(file_system_context, std::move(callback),
std::move(remaining_urls));
}
void LocalFileSyncContext::PromoteDemotedChangesForURL(
FileSystemContext* file_system_context,
const FileSystemURL& url) {
DCHECK(file_system_context);
if (!file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_ui_)
return;
file_system_context->default_file_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::PromoteDemotedChangesForURL, this,
base::RetainedRef(file_system_context), url));
return;
}
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
backend->change_tracker()->PromoteDemotedChangesForURL(url);
}
void LocalFileSyncContext::PromoteDemotedChangesForURLs(
FileSystemContext* file_system_context,
std::unique_ptr<FileSystemURLQueue> urls) {
DCHECK(file_system_context);
if (!file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_ui_)
return;
file_system_context->default_file_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::PromoteDemotedChangesForURLs,
this, base::RetainedRef(file_system_context),
std::move(urls)));
return;
}
for (FileSystemURLQueue::iterator iter = urls->begin();
iter != urls->end(); ++iter)
PromoteDemotedChangesForURL(file_system_context, *iter);
}
void LocalFileSyncContext::DidGetWritingStatusForSync(
FileSystemContext* file_system_context,
SyncStatusCode status,
const FileSystemURL& url,
SyncMode sync_mode,
LocalFileSyncInfoCallback callback) {
// This gets called on UI thread and relays the task on FILE thread.
DCHECK(file_system_context);
if (!file_system_context->default_file_task_runner()->
RunsTasksInCurrentSequence()) {
DCHECK(ui_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_ui_) {
std::move(callback).Run(SYNC_STATUS_ABORT, LocalFileSyncInfo(),
storage::ScopedFile());
return;
}
file_system_context->default_file_task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::DidGetWritingStatusForSync, this,
base::RetainedRef(file_system_context), status, url,
sync_mode, std::move(callback)));
return;
}
SyncFileSystemBackend* backend =
SyncFileSystemBackend::GetBackend(file_system_context);
DCHECK(backend);
DCHECK(backend->change_tracker());
FileChangeList changes;
backend->change_tracker()->GetChangesForURL(url, &changes);
base::FilePath platform_path;
base::File::Info file_info;
FileSystemFileUtil* file_util =
file_system_context->sandbox_delegate()->sync_file_util();
DCHECK(file_util);
base::File::Error file_error = file_util->GetFileInfo(
std::make_unique<FileSystemOperationContext>(file_system_context).get(),
url, &file_info, &platform_path);
storage::ScopedFile snapshot;
if (file_error == base::File::FILE_OK && sync_mode == SYNC_SNAPSHOT) {
base::FilePath snapshot_path;
base::CreateTemporaryFileInDir(local_base_path_.Append(kSnapshotDir),
&snapshot_path);
if (base::CopyFile(platform_path, snapshot_path)) {
platform_path = snapshot_path;
snapshot =
storage::ScopedFile(snapshot_path,
storage::ScopedFile::DELETE_ON_SCOPE_OUT,
file_system_context->default_file_task_runner());
}
}
if (status == SYNC_STATUS_OK &&
file_error != base::File::FILE_OK &&
file_error != base::File::FILE_ERROR_NOT_FOUND) {
status = FileErrorToSyncStatusCode(file_error);
}
DCHECK(!file_info.is_symbolic_link);
SyncFileType file_type = SYNC_FILE_TYPE_FILE;
if (file_error == base::File::FILE_ERROR_NOT_FOUND)
file_type = SYNC_FILE_TYPE_UNKNOWN;
else if (file_info.is_directory)
file_type = SYNC_FILE_TYPE_DIRECTORY;
LocalFileSyncInfo sync_file_info;
sync_file_info.url = url;
sync_file_info.local_file_path = platform_path;
sync_file_info.metadata.file_type = file_type;
sync_file_info.metadata.size = file_info.size;
sync_file_info.metadata.last_modified = file_info.last_modified;
sync_file_info.changes = changes;
if (status == SYNC_STATUS_OK && sync_mode == SYNC_SNAPSHOT) {
if (!changes.empty()) {
// Now we create an empty mirror change record for URL (and we record
// changes to both mirror and original records during sync), so that
// we can reset to the mirror when the sync succeeds.
backend->change_tracker()->CreateFreshMirrorForURL(url);
}
// 'Unlock' the file for snapshot sync.
// (But keep it in writing status so that no other sync starts on
// the same URL)
io_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&LocalFileSyncContext::ClearSyncFlagOnIOThread, this,
url, true /* for_snapshot_sync */));
}
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), status, sync_file_info,
std::move(snapshot)));
}
void LocalFileSyncContext::ClearSyncFlagOnIOThread(
const FileSystemURL& url,
bool for_snapshot_sync) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_io_)
return;
sync_status()->EndSyncing(url);
if (for_snapshot_sync) {
// The caller will hold shared lock on this one.
sync_status()->StartWriting(url);
return;
}
// Since a sync has finished the number of changes must have been updated.
UpdateChangesForOrigin(url.origin().GetURL(), base::DoNothing());
}
void LocalFileSyncContext::FinalizeSnapshotSyncOnIOThread(
const FileSystemURL& url) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
if (shutdown_on_io_)
return;
sync_status()->EndWriting(url);
// Since a sync has finished the number of changes must have been updated.
UpdateChangesForOrigin(url.origin().GetURL(), base::DoNothing());
}
void LocalFileSyncContext::DidApplyRemoteChange(
const FileSystemURL& url,
SyncStatusCallback callback_on_ui,
base::File::Error file_error) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
root_delete_helper_.reset();
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(std::move(callback_on_ui),
FileErrorToSyncStatusCode(file_error)));
}
void LocalFileSyncContext::DidGetFileMetadata(
SyncFileMetadataCallback callback,
base::File::Error file_error,
const base::File::Info& file_info) {
DCHECK(io_task_runner_->RunsTasksInCurrentSequence());
SyncFileMetadata metadata;
if (file_error == base::File::FILE_OK) {
metadata.file_type = file_info.is_directory ?
SYNC_FILE_TYPE_DIRECTORY : SYNC_FILE_TYPE_FILE;
metadata.size = file_info.size;
metadata.last_modified = file_info.last_modified;
}
ui_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), FileErrorToSyncStatusCode(file_error),
metadata));
}
base::TimeDelta LocalFileSyncContext::NotifyChangesDuration() {
if (mock_notify_changes_duration_in_sec_ >= 0)
return base::Seconds(mock_notify_changes_duration_in_sec_);
return base::Seconds(kNotifyChangesDurationInSec);
}
void LocalFileSyncContext::DidCreateDirectoryForCopyIn(
FileSystemContext* file_system_context,
const base::FilePath& local_path,
const FileSystemURL& dest_url,
StatusCallback callback,
base::File::Error error) {
if (error != base::File::FILE_OK) {
std::move(callback).Run(error);
return;
}
FileSystemURL url_for_sync = CreateSyncableFileSystemURLForSync(
file_system_context, dest_url);
file_system_context->operation_runner()->CopyInForeignFile(
local_path, url_for_sync, std::move(callback));
}
} // namespace sync_file_system
|