Added special handling of IfModifiedSince if a new shared container is detected
[pithos-ms-client] / trunk / Pithos.Core / Agents / PollAgent.cs
index 63d5fd5..6695436 100644 (file)
@@ -45,9 +45,12 @@ using System.ComponentModel.Composition;
 using System.Diagnostics;\r
 using System.Diagnostics.Contracts;\r
 using System.IO;\r
 using System.Diagnostics;\r
 using System.Diagnostics.Contracts;\r
 using System.IO;\r
+using System.Linq.Expressions;\r
 using System.Reflection;\r
 using System.Reflection;\r
+using System.Security.Cryptography;\r
 using System.Threading;\r
 using System.Threading.Tasks;\r
 using System.Threading;\r
 using System.Threading.Tasks;\r
+using System.Threading.Tasks.Dataflow;\r
 using Castle.ActiveRecord;\r
 using Pithos.Interfaces;\r
 using Pithos.Network;\r
 using Castle.ActiveRecord;\r
 using Pithos.Interfaces;\r
 using Pithos.Network;\r
@@ -59,6 +62,77 @@ namespace Pithos.Core.Agents
     using System.Collections.Generic;\r
     using System.Linq;\r
 \r
     using System.Collections.Generic;\r
     using System.Linq;\r
 \r
+    /*public class PollRequest\r
+    {\r
+        public DateTime? Since { get; set; }\r
+        public IEnumerable<string> Batch { get; set; }\r
+    }*/\r
+\r
+    [DebuggerDisplay("{FilePath} C:{C} L:{L} S:{S}")]\r
+    public class StateTuple\r
+    {\r
+        public string FilePath { get; private set; }\r
+\r
+        public string MD5 { get; set; }\r
+\r
+        public string L\r
+        {\r
+            get { return FileState==null?null:FileState.Checksum; }\r
+        }\r
+\r
+        private string _c;\r
+        public string C\r
+        {\r
+            get { return _c; }\r
+            set {\r
+                _c = String.IsNullOrWhiteSpace(value) ? null : value;\r
+            }\r
+        }\r
+\r
+        public string S\r
+        {\r
+            get { return ObjectInfo == null ? null : ObjectInfo.X_Object_Hash; }\r
+        }\r
+\r
+        private FileSystemInfo _fileInfo;\r
+        private TreeHash _merkle;\r
+\r
+        public FileSystemInfo FileInfo\r
+        {\r
+            get { return _fileInfo; }\r
+            set\r
+            {\r
+                _fileInfo = value;\r
+                FilePath = value.FullName;\r
+            }\r
+        }\r
+\r
+        public FileState FileState { get; set; }\r
+        public ObjectInfo ObjectInfo{ get; set; }\r
+\r
+\r
+        public TreeHash Merkle\r
+        {\r
+            get {\r
+                return _merkle;\r
+            }\r
+            set {\r
+                _merkle = value;\r
+                C = _merkle.TopHash.ToHashString();\r
+            }\r
+        }\r
+\r
+        public StateTuple() { }\r
+\r
+        public StateTuple(FileSystemInfo info)\r
+        {\r
+            FileInfo = info;\r
+        }\r
+\r
+\r
+    }\r
+\r
+\r
     /// <summary>\r
     /// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all\r
     /// objects and compares it with a previously cached version to detect differences. \r
     /// <summary>\r
     /// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all\r
     /// objects and compares it with a previously cached version to detect differences. \r
@@ -84,6 +158,29 @@ namespace Pithos.Core.Agents
 \r
         public IStatusNotification StatusNotification { get; set; }\r
 \r
 \r
         public IStatusNotification StatusNotification { get; set; }\r
 \r
+        private CancellationTokenSource _currentOperationCancellation = new CancellationTokenSource();\r
+\r
+        public void CancelCurrentOperation()\r
+        {\r
+            //What does it mean to cancel the current upload/download?\r
+            //Obviously, the current operation will be cancelled by throwing\r
+            //a cancellation exception.\r
+            //\r
+            //The default behavior is to retry any operations that throw.\r
+            //Obviously this is not what we want in this situation.\r
+            //The cancelled operation should NOT bea retried. \r
+            //\r
+            //This can be done by catching the cancellation exception\r
+            //and avoiding the retry.\r
+            //\r
+\r
+            //Have to reset the cancellation source - it is not possible to reset the source\r
+            //Have to prevent a case where an operation requests a token from the old source\r
+            var oldSource = Interlocked.Exchange(ref _currentOperationCancellation, new CancellationTokenSource());\r
+            oldSource.Cancel();\r
+\r
+        }\r
+\r
         public bool Pause\r
         {\r
             get {\r
         public bool Pause\r
         {\r
             get {\r
@@ -110,27 +207,51 @@ namespace Pithos.Core.Agents
         private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();\r
         private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();\r
 \r
         private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();\r
         private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();\r
 \r
+        //private readonly ActionBlock<PollRequest>  _pollAction;\r
+\r
+        HashSet<string> _knwonContainers = new HashSet<string>();\r
+\r
+        \r
 \r
 \r
+        /*private void ProcessPollRequest(PollRequest request)\r
+        {\r
+\r
+            if (request.Since == null && request.Batch != null)\r
+            {\r
+                _batchQueue.Enqueue(request.Batch);\r
+                _syncEvent.Set();                \r
+            }\r
+            else \r
+            {\r
+                PollRemoteFiles(request.Since).Wait();\r
+            }\r
+        }*/\r
         /// <summary>\r
         /// Start a manual synchronization\r
         /// </summary>\r
         /// <summary>\r
         /// Start a manual synchronization\r
         /// </summary>\r
-        public void SynchNow()\r
-        {            \r
-            _syncEvent.Set();\r
+        public void SynchNow(IEnumerable<string> paths=null)\r
+        {\r
+            _batchQueue.Enqueue(paths);\r
+            _syncEvent.Set();                \r
+\r
+            //_pollAction.Post(new PollRequest {Batch = paths});\r
         }\r
 \r
         }\r
 \r
+        readonly ConcurrentQueue<IEnumerable<string>> _batchQueue=new ConcurrentQueue<IEnumerable<string>>();\r
+\r
         /// <summary>\r
         /// Remote files are polled periodically. Any changes are processed\r
         /// </summary>\r
         /// <param name="since"></param>\r
         /// <returns></returns>\r
         /// <summary>\r
         /// Remote files are polled periodically. Any changes are processed\r
         /// </summary>\r
         /// <param name="since"></param>\r
         /// <returns></returns>\r
-        public async Task PollRemoteFiles(DateTime? since = null)\r
+        public  void PollRemoteFiles(DateTime? since = null)\r
         {\r
             if (Log.IsDebugEnabled)\r
                 Log.DebugFormat("Polling changes after [{0}]",since);\r
 \r
             Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");\r
         {\r
             if (Log.IsDebugEnabled)\r
                 Log.DebugFormat("Polling changes after [{0}]",since);\r
 \r
             Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");\r
-            \r
+\r
+            //GC.Collect();\r
 \r
             using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))\r
             {\r
 \r
             using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))\r
             {\r
@@ -138,13 +259,28 @@ namespace Pithos.Core.Agents
                 var nextSince = since;\r
                 try\r
                 {\r
                 var nextSince = since;\r
                 try\r
                 {\r
-                    await _unPauseEvent.WaitAsync();\r
+                    _unPauseEvent.Wait();\r
                     UpdateStatus(PithosStatus.PollSyncing);\r
 \r
                     UpdateStatus(PithosStatus.PollSyncing);\r
 \r
-                    var tasks = from accountInfo in _accounts.Values\r
-                                select ProcessAccountFiles(accountInfo, since);\r
+                    var accountBatches=new Dictionary<Uri, IEnumerable<string>>();\r
+                    IEnumerable<string> batch = null;\r
+                    if (_batchQueue.TryDequeue(out batch) && batch != null)\r
+                        foreach (var account in _accounts.Values)\r
+                        {\r
+                            var accountBatch = batch.Where(path => path.IsAtOrBelow(account.AccountPath));\r
+                            accountBatches[account.AccountKey] = accountBatch;\r
+                        }\r
+\r
+                    var tasks = new List<Task<DateTime?>>();\r
+                    foreach(var accountInfo in _accounts.Values)\r
+                    {\r
+                        IEnumerable<string> accountBatch ;\r
+                        accountBatches.TryGetValue(accountInfo.AccountKey,out accountBatch);\r
+                        var t=ProcessAccountFiles (accountInfo, accountBatch, since);\r
+                        tasks.Add(t);\r
+                    }\r
 \r
 \r
-                    var nextTimes=await TaskEx.WhenAll(tasks.ToList());\r
+                    var nextTimes=TaskEx.WhenAll(tasks.ToList()).Result;\r
 \r
                     _firstPoll = false;\r
                     //Reschedule the poll with the current timestamp as a "since" value\r
 \r
                     _firstPoll = false;\r
                     //Reschedule the poll with the current timestamp as a "since" value\r
@@ -167,12 +303,13 @@ namespace Pithos.Core.Agents
                 try\r
                 {\r
                     //Wait for the polling interval to pass or the Sync event to be signalled\r
                 try\r
                 {\r
                     //Wait for the polling interval to pass or the Sync event to be signalled\r
-                    nextSince = await WaitForScheduledOrManualPoll(nextSince);\r
+                    nextSince = WaitForScheduledOrManualPoll(nextSince).Result;\r
                 }\r
                 finally\r
                 {\r
                     //Ensure polling is scheduled even in case of error\r
                 }\r
                 finally\r
                 {\r
                     //Ensure polling is scheduled even in case of error\r
-                    TaskEx.Run(() => PollRemoteFiles(nextSince));                        \r
+                    PollRemoteFiles(nextSince);\r
+                    //_pollAction.Post(new PollRequest {Since = nextSince});\r
                 }\r
             }\r
         }\r
                 }\r
             }\r
         }\r
@@ -185,7 +322,7 @@ namespace Pithos.Core.Agents
         private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)\r
         {\r
             var sync = _syncEvent.WaitAsync();\r
         private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)\r
         {\r
             var sync = _syncEvent.WaitAsync();\r
-            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), NetworkAgent.CancellationToken);\r
+            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval));\r
             \r
             var signaledTask = await TaskEx.WhenAny(sync, wait);\r
             \r
             \r
             var signaledTask = await TaskEx.WhenAny(sync, wait);\r
             \r
@@ -206,7 +343,9 @@ namespace Pithos.Core.Agents
             return since;\r
         }\r
 \r
             return since;\r
         }\r
 \r
-        public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)\r
+        \r
+\r
+        public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, IEnumerable<string> accountBatch, DateTime? since = null)\r
         {\r
             if (accountInfo == null)\r
                 throw new ArgumentNullException("accountInfo");\r
         {\r
             if (accountInfo == null)\r
                 throw new ArgumentNullException("accountInfo");\r
@@ -250,7 +389,7 @@ namespace Pithos.Core.Agents
                                              client.ListObjects(accountInfo.UserName, container.Name, since), container.Name)).ToList();\r
 \r
                     var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => \r
                                              client.ListObjects(accountInfo.UserName, container.Name, since), container.Name)).ToList();\r
 \r
                     var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => \r
-                        client.ListSharedObjects(since), "shared");\r
+                        client.ListSharedObjects(_knwonContainers,since), "shared");\r
                     listObjects.Add(listShared);\r
                     var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());\r
 \r
                     listObjects.Add(listShared);\r
                     var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());\r
 \r
@@ -262,14 +401,14 @@ namespace Pithos.Core.Agents
                         var remoteObjects = (from objectList in listTasks\r
                                             where (string)objectList.AsyncState != "trash"\r
                                             from obj in objectList.Result\r
                         var remoteObjects = (from objectList in listTasks\r
                                             where (string)objectList.AsyncState != "trash"\r
                                             from obj in objectList.Result\r
+                                            orderby obj.Bytes ascending \r
                                             select obj).ToList();\r
                         \r
                         //Get the latest remote object modification date, only if it is after\r
                                             select obj).ToList();\r
                         \r
                         //Get the latest remote object modification date, only if it is after\r
-                        //the original since date\r
+                        //the original since date                        \r
                         nextSince = GetLatestDateAfter(nextSince, remoteObjects);\r
 \r
                         var sharedObjects = dict["shared"].Result;\r
                         nextSince = GetLatestDateAfter(nextSince, remoteObjects);\r
 \r
                         var sharedObjects = dict["shared"].Result;\r
-                        nextSince = GetLatestDateBefore(nextSince, sharedObjects);\r
 \r
                         //DON'T process trashed files\r
                         //If some files are deleted and added again to a folder, they will be deleted\r
 \r
                         //DON'T process trashed files\r
                         //If some files are deleted and added again to a folder, they will be deleted\r
@@ -283,7 +422,7 @@ namespace Pithos.Core.Agents
                                         where\r
                                             !remoteObjects.Any(\r
                                                 info => info.Name == trash.Name && info.Hash == trash.Hash)\r
                                         where\r
                                             !remoteObjects.Any(\r
                                                 info => info.Name == trash.Name && info.Hash == trash.Hash)\r
-                                        select trash;\r
+                                   8     select trash;\r
                         ProcessTrashedFiles(accountInfo, realTrash);\r
 */\r
 \r
                         ProcessTrashedFiles(accountInfo, realTrash);\r
 */\r
 \r
@@ -296,37 +435,55 @@ namespace Pithos.Core.Agents
 \r
                         if (_firstPoll)\r
                             StatusKeeper.CleanupOrphanStates();\r
 \r
                         if (_firstPoll)\r
                             StatusKeeper.CleanupOrphanStates();\r
-                        StatusKeeper.CleanupStaleStates(accountInfo, cleanRemotes);\r
                         \r
                         var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);\r
                         \r
                         var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);\r
+                        var currentRemotes = differencer.Current.ToList();\r
+                        StatusKeeper.CleanupStaleStates(accountInfo, currentRemotes);\r
 \r
 \r
-                        var filterUris = Selectives.SelectiveUris[accountInfo.AccountKey];\r
+                        //var filterUris = Selectives.SelectiveUris[accountInfo.AccountKey];\r
 \r
 \r
-                        ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(filterUris));\r
+                        //May have to wait if the FileAgent has asked for a Pause, due to local changes\r
+                        await _unPauseEvent.WaitAsync();\r
 \r
 \r
-                        // @@@ NEED To add previous state here as well, To compare with previous hash\r
+                        //Get the local files here                        \r
+                        var agent = AgentLocator<FileAgent>.Get(accountInfo.AccountPath);                        \r
+                        //TODO: Pass the batch here as well\r
+                        var files = await LoadLocalFileTuples(accountInfo, accountBatch);\r
 \r
 \r
+                        var states = FileState.Queryable.ToList();                        \r
                         \r
                         \r
+                        var infos = (from remote in currentRemotes\r
+                                    let path = remote.RelativeUrlToFilePath(accountInfo.UserName)\r
+                                    let info=agent.GetFileSystemInfo(path)\r
+                                    select Tuple.Create(info.FullName,remote))\r
+                                    .ToList();\r
 \r
 \r
-                        //Create a list of actions from the remote files\r
-                        \r
-                        var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(filterUris))\r
-                                        .Union(\r
-                                        ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(filterUris)))\r
-                                        .Union(\r
-                                        CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(filterUris)));\r
+                        var token = _currentOperationCancellation.Token;\r
 \r
 \r
-                        //And remove those that are already being processed by the agent\r
-                        var distinctActions = allActions\r
-                            .Except(NetworkAgent.GetEnumerable(), new LocalFileComparer())\r
-                            .ToList();\r
+                        var tuples = MergeSources(infos, files, states).ToList();\r
 \r
 \r
-                        await _unPauseEvent.WaitAsync();\r
-                        //Queue all the actions\r
-                        foreach (var message in distinctActions)\r
+                        //Process only the changes in the batch file, if one exists\r
+                        var stateTuples = accountBatch==null?tuples:tuples.Where(t => accountBatch.Contains(t.FilePath));\r
+                        foreach (var tuple in stateTuples)\r
+                        {\r
+                            await _unPauseEvent.WaitAsync();\r
+\r
+                            //Set the Merkle Hash\r
+                            SetMerkleHash(accountInfo, tuple);\r
+\r
+                            SyncSingleItem(accountInfo, tuple, agent, token);\r
+\r
+                        }\r
+\r
+\r
+                        //On the first run\r
+/*\r
+                        if (_firstPoll)\r
                         {\r
                         {\r
-                            NetworkAgent.Post(message);\r
+                            MarkSuspectedDeletes(accountInfo, cleanRemotes);\r
                         }\r
                         }\r
+*/\r
+\r
 \r
                         Log.Info("[LISTENER] End Processing");\r
                     }\r
 \r
                         Log.Info("[LISTENER] End Processing");\r
                     }\r
@@ -342,6 +499,350 @@ namespace Pithos.Core.Agents
             }\r
         }\r
 \r
             }\r
         }\r
 \r
+        private static void SetMerkleHash(AccountInfo accountInfo, StateTuple tuple)\r
+        {\r
+            //The Merkle hash for directories is that of an empty buffer\r
+            if (tuple.FileInfo is DirectoryInfo)\r
+                tuple.C = MERKLE_EMPTY;\r
+            else if (tuple.FileState != null && tuple.MD5 == tuple.FileState.ShortHash)\r
+            {\r
+                //If there is a state whose MD5 matches, load the merkle hash from the file state\r
+                //insteaf of calculating it\r
+                tuple.C = tuple.FileState.Checksum;                              \r
+            }\r
+            else\r
+            {\r
+                tuple.Merkle = TaskEx.Run(()=> Signature.CalculateTreeHash(tuple.FileInfo, accountInfo.BlockSize, accountInfo.BlockHash)).Result;\r
+                //tuple.C=tuple.Merkle.TopHash.ToHashString();                \r
+            }\r
+        }\r
+\r
+        private async Task<List<Tuple<FileSystemInfo, string>>> LoadLocalFileTuples(AccountInfo accountInfo,IEnumerable<string> batch )\r
+        {\r
+            using (ThreadContext.Stacks["Account Files Hashing"].Push(accountInfo.UserName))\r
+            {\r
+                var batchPaths = (batch==null)?new List<string>():batch.ToList();\r
+                IEnumerable<FileSystemInfo> localInfos=AgentLocator<FileAgent>.Get(accountInfo.AccountPath)\r
+                                                        .EnumerateFileSystemInfos();\r
+                if (batchPaths.Count>0)\r
+                    localInfos= localInfos.Where(fi => batchPaths.Contains(fi.FullName));\r
+                \r
+                //Use the queue to retry locked file hashing\r
+                var fileQueue = new Queue<FileSystemInfo>(localInfos);\r
+                var hasher = MD5.Create();\r
+\r
+                var results = new List<Tuple<FileSystemInfo, string>>();\r
+                var backoff = 0;\r
+                while (fileQueue.Count > 0)\r
+                {\r
+                    var file = fileQueue.Dequeue();\r
+                    using (ThreadContext.Stacks["File"].Push(file.FullName))\r
+                    {\r
+                        /*\r
+                                                Signature.CalculateTreeHash(file, accountInfo.BlockSize,\r
+                                                                                                 accountInfo.BlockHash).\r
+                                                                         TopHash.ToHashString()\r
+                        */\r
+                        try\r
+                        {\r
+                            //Replace MD5 here, do the calc while syncing individual files\r
+                            string hash ;\r
+                            if (file is DirectoryInfo)\r
+                                hash = MERKLE_EMPTY;\r
+                            else\r
+                            {\r
+                                //Wait in case the FileAgent has requested a Pause\r
+                                await _unPauseEvent.WaitAsync();\r
+                                \r
+                                using (StatusNotification.GetNotifier("Hashing {0}", "Finished hashing {0}", file.Name))\r
+                                using (var stream = (file as FileInfo).OpenRead())\r
+                                {                                    \r
+                                    hash = hasher.ComputeHash(stream).ToHashString();\r
+                                    backoff = 0;\r
+                                }\r
+                            }                            \r
+                            results.Add(Tuple.Create(file, hash));\r
+                        }\r
+                        catch (IOException exc)\r
+                        {\r
+                            Log.WarnFormat("[HASH] File in use, will retry [{0}]", exc);\r
+                            fileQueue.Enqueue(file);\r
+                            //If this is the only enqueued file                            \r
+                            if (fileQueue.Count != 1) continue;\r
+                            \r
+                            \r
+                            //Increase delay\r
+                            if (backoff<60000)\r
+                                backoff += 10000;\r
+                            //Pause Polling for the specified time\r
+                        }\r
+                        if (backoff>0)\r
+                            await PauseFor(backoff);\r
+                    }\r
+                }\r
+\r
+                return results;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Wait and Pause the agent while waiting\r
+        /// </summary>\r
+        /// <param name="backoff"></param>\r
+        /// <returns></returns>\r
+        private async Task PauseFor(int backoff)\r
+        {\r
+\r
+            Pause = true;\r
+            await TaskEx.Delay(backoff);\r
+            Pause = false;\r
+        }\r
+\r
+        private void SyncSingleItem(AccountInfo accountInfo, StateTuple tuple, FileAgent agent, CancellationToken token)\r
+        {\r
+            Log.DebugFormat("Sync [{0}] C:[{1}] L:[{2}] S:[{3}]",tuple.FilePath,tuple.C,tuple.L,tuple.S);\r
+\r
+            var localFilePath = tuple.FilePath;\r
+            //Don't use the tuple info, it may have been deleted\r
+            var localInfo = FileInfoExtensions.FromPath(localFilePath);\r
+\r
+\r
+            var isUnselectedRootFolder = agent.IsUnselectedRootFolder(tuple.FilePath);\r
+\r
+            //Unselected root folders that have not yet been uploaded should be uploaded and added to the \r
+            //selective folders\r
+\r
+            if (!Selectives.IsSelected(accountInfo, localFilePath) && !(isUnselectedRootFolder && tuple.ObjectInfo==null) )                \r
+                return;\r
+\r
+            // Local file unchanged? If both C and L are null, make sure it's because \r
+            //both the file is missing and the state checksum is not missing\r
+            if (tuple.C == tuple.L /*&& (localInfo.Exists || tuple.FileState == null)*/)\r
+            {\r
+                //No local changes\r
+                //Server unchanged?\r
+                if (tuple.S == tuple.L)\r
+                {\r
+                    // No server changes\r
+                    //Has the file been renamed on the server?\r
+                    MoveForServerMove(accountInfo, tuple);\r
+                }\r
+                else\r
+                {\r
+                    //Different from server\r
+                    //Does the server file exist?\r
+                    if (tuple.S == null)\r
+                    {\r
+                        //Server file doesn't exist\r
+                        //deleteObjectFromLocal()\r
+                        StatusKeeper.SetFileState(localFilePath, FileStatus.Deleted,\r
+                                                  FileOverlayStatus.Deleted, "");\r
+                        agent.Delete(localFilePath);\r
+                        //updateRecord(Remove C, L)\r
+                        StatusKeeper.ClearFileStatus(localFilePath);\r
+                    }\r
+                    else\r
+                    {\r
+                        //Server file exists\r
+                        //downloadServerObject() // Result: L = S\r
+                        //If the file has moved on the server, move it locally before downloading\r
+                        var targetPath = MoveForServerMove(accountInfo, tuple);\r
+\r
+                        StatusKeeper.SetFileState(targetPath, FileStatus.Modified,\r
+                                                  FileOverlayStatus.Modified, "");\r
+                        NetworkAgent.Downloader.DownloadCloudFile(accountInfo,\r
+                                                                  tuple.ObjectInfo,\r
+                                                                  targetPath, tuple.Merkle, token).Wait(token);\r
+                        //updateRecord( L = S )\r
+                        StatusKeeper.UpdateFileChecksum(targetPath, tuple.ObjectInfo.ETag,\r
+                                                        tuple.ObjectInfo.X_Object_Hash);\r
+\r
+                        StatusKeeper.StoreInfo(targetPath, tuple.ObjectInfo);\r
+\r
+                        /*\r
+                                                        StatusKeeper.SetFileState(targetPath, FileStatus.Unchanged,\r
+                                                                                  FileOverlayStatus.Normal, "");\r
+                            */\r
+                    }\r
+                }\r
+\r
+            }\r
+            else\r
+            {\r
+                //Local changes found\r
+\r
+                //Server unchanged?\r
+                if (tuple.S == tuple.L)\r
+                {\r
+                    //The FileAgent selective sync checks for new root folder files\r
+                    if (!agent.Ignore(localFilePath))\r
+                    {\r
+                        if ((tuple.C == null || !localInfo.Exists) && tuple.ObjectInfo != null)\r
+                        {\r
+                            //deleteObjectFromServer()\r
+                            DeleteCloudFile(accountInfo, tuple);\r
+                            //updateRecord( Remove L, S)                  \r
+                        }\r
+                        else\r
+                        {\r
+                            //uploadLocalObject() // Result: S = C, L = S                        \r
+\r
+                            //Debug.Assert(tuple.FileState !=null);\r
+                            var action = new CloudUploadAction(accountInfo, localInfo, tuple.FileState,\r
+                                                               accountInfo.BlockSize, accountInfo.BlockHash,\r
+                                                               "Poll", isUnselectedRootFolder);\r
+                            NetworkAgent.Uploader.UploadCloudFile(action, tuple.Merkle, token).Wait(token);\r
+\r
+                            //updateRecord( S = C )\r
+                            //State updated by the uploader\r
+\r
+                            if (isUnselectedRootFolder)\r
+                            {\r
+                                ProcessChildren(accountInfo, tuple, agent, token);\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+                else\r
+                {\r
+                    if (tuple.C == tuple.S)\r
+                    {\r
+                        // (Identical Changes) Result: L = S\r
+                        //doNothing()\r
+                        //Detect server moves\r
+                        var targetPath = MoveForServerMove(accountInfo, tuple);\r
+                        StatusKeeper.StoreInfo(targetPath, tuple.ObjectInfo);\r
+                    }\r
+                    else\r
+                    {\r
+                        if ((tuple.C == null || !localInfo.Exists) && tuple.ObjectInfo != null)\r
+                        {\r
+                            //deleteObjectFromServer()\r
+                            DeleteCloudFile(accountInfo, tuple);\r
+                            //updateRecord(Remove L, S)                  \r
+                        }\r
+                            //If both the local and server files are missing, the state is stale\r
+                        else if (!localInfo.Exists && (tuple.S == null || tuple.ObjectInfo == null))\r
+                        {\r
+                            StatusKeeper.ClearFileStatus(localInfo.FullName);\r
+                        }\r
+                        else\r
+                        {\r
+                            ReportConflictForMismatch(localFilePath);\r
+                            //identifyAsConflict() // Manual action required\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        private string MoveForServerMove(AccountInfo accountInfo, StateTuple tuple)\r
+        {\r
+            if (tuple.ObjectInfo == null)\r
+                return null;\r
+            var relativePath = tuple.ObjectInfo.RelativeUrlToFilePath(accountInfo.UserName);\r
+            var serverPath = Path.Combine(accountInfo.AccountPath, relativePath);\r
+            \r
+            //Compare Case Insensitive\r
+            if (String.Equals(tuple.FilePath ,serverPath,StringComparison.InvariantCultureIgnoreCase)) return serverPath;\r
+\r
+            if (tuple.FileInfo.Exists)\r
+            {                    \r
+                var fi = tuple.FileInfo as FileInfo;\r
+                if (fi != null)\r
+                    fi.MoveTo(serverPath);\r
+                var di = tuple.FileInfo as DirectoryInfo;\r
+                if (di != null)\r
+                    di.MoveTo(serverPath);\r
+                StatusKeeper.StoreInfo(serverPath, tuple.ObjectInfo);\r
+            }\r
+            else\r
+            {\r
+                Debug.Assert(false, "File does not exist");\r
+            }\r
+            return serverPath;\r
+        }\r
+\r
+        private void DeleteCloudFile(AccountInfo accountInfo, StateTuple tuple)\r
+        {\r
+            StatusKeeper.SetFileState(tuple.FilePath, FileStatus.Deleted,\r
+                                      FileOverlayStatus.Deleted, "");\r
+            NetworkAgent.DeleteAgent.DeleteCloudFile(accountInfo, tuple.ObjectInfo);\r
+            StatusKeeper.ClearFileStatus(tuple.FilePath);\r
+        }\r
+\r
+        private void ProcessChildren(AccountInfo accountInfo, StateTuple tuple, FileAgent agent, CancellationToken token)\r
+        {\r
+\r
+            var dirInfo = tuple.FileInfo as DirectoryInfo;\r
+            var folderTuples = from folder in dirInfo.EnumerateDirectories("*", SearchOption.AllDirectories)\r
+                               select new StateTuple(folder);\r
+            var fileTuples = from file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories)\r
+                             select new StateTuple(file);\r
+            \r
+            //Process folders first, to ensure folders appear on the sever as soon as possible\r
+            folderTuples.ApplyAction(t => SyncSingleItem(accountInfo, t, agent, token));\r
+            \r
+            fileTuples.ApplyAction(t => SyncSingleItem(accountInfo, t, agent, token));\r
+        }\r
+\r
+        private static IEnumerable<StateTuple> MergeSources(\r
+            IEnumerable<Tuple<string, ObjectInfo>> infos, \r
+            IEnumerable<Tuple<FileSystemInfo, string>> files, \r
+            IEnumerable<FileState> states)\r
+        {\r
+            var tuplesByPath = new Dictionary<string, StateTuple>();\r
+            foreach (var file in files)\r
+            {\r
+                var fsInfo = file.Item1;\r
+                var fileHash = fsInfo is DirectoryInfo? MERKLE_EMPTY:file.Item2;\r
+\r
+                tuplesByPath[fsInfo.FullName] = new StateTuple {FileInfo = fsInfo, MD5 = fileHash};\r
+            }\r
+            foreach (var state in states)\r
+            {\r
+                StateTuple hashTuple;\r
+                if (tuplesByPath.TryGetValue(state.FilePath, out hashTuple))\r
+                {\r
+                    hashTuple.FileState = state;\r
+                }\r
+                else\r
+                {\r
+                    var fsInfo = FileInfoExtensions.FromPath(state.FilePath);\r
+                    tuplesByPath[state.FilePath] = new StateTuple {FileInfo = fsInfo, FileState = state};\r
+                }\r
+            }\r
+\r
+            var tuplesByID = tuplesByPath.Values\r
+                .Where(tuple => tuple.FileState != null && tuple.FileState.ObjectID!=null)\r
+                .ToDictionary(tuple=>tuple.FileState.ObjectID,tuple=>tuple);//new Dictionary<Guid, StateTuple>();\r
+\r
+            foreach (var info in infos)\r
+            {\r
+                StateTuple hashTuple;\r
+                var filePath = info.Item1;\r
+                var objectInfo = info.Item2;\r
+                var objectID = objectInfo.UUID;\r
+\r
+                if (tuplesByID.TryGetValue(objectID, out hashTuple))\r
+                {\r
+                    hashTuple.ObjectInfo = objectInfo;                    \r
+                }\r
+                else if (tuplesByPath.TryGetValue(filePath, out hashTuple))\r
+                {\r
+                    hashTuple.ObjectInfo = objectInfo;\r
+                }\r
+                else\r
+                {\r
+                    var fsInfo = FileInfoExtensions.FromPath(filePath);\r
+                    var tuple = new StateTuple {FileInfo = fsInfo, ObjectInfo = objectInfo};\r
+                    tuplesByPath[filePath] = tuple;\r
+                    tuplesByID[objectInfo.UUID] = tuple;\r
+                }\r
+            }\r
+            return tuplesByPath.Values;\r
+        }\r
+\r
         /// <summary>\r
         /// Returns the latest LastModified date from the list of objects, but only if it is before\r
         /// than the threshold value\r
         /// <summary>\r
         /// Returns the latest LastModified date from the list of objects, but only if it is before\r
         /// than the threshold value\r
@@ -383,6 +884,7 @@ namespace Pithos.Core.Agents
         readonly AccountsDifferencer _differencer = new AccountsDifferencer();\r
         private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>();\r
         private bool _pause;\r
         readonly AccountsDifferencer _differencer = new AccountsDifferencer();\r
         private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>();\r
         private bool _pause;\r
+        private static string MERKLE_EMPTY = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";\r
 \r
         /// <summary>\r
         /// Deletes local files that are not found in the list of cloud files\r
 \r
         /// <summary>\r
         /// Deletes local files that are not found in the list of cloud files\r
@@ -399,81 +901,98 @@ namespace Pithos.Core.Agents
                 throw new ArgumentNullException("cloudFiles");\r
             Contract.EndContractBlock();\r
 \r
                 throw new ArgumentNullException("cloudFiles");\r
             Contract.EndContractBlock();\r
 \r
-            //On the first run\r
-            if (_firstPoll)\r
+            var deletedFiles = new List<FileSystemInfo>();\r
+            foreach (var objectInfo in cloudFiles)\r
             {\r
             {\r
-                //Only consider files that are not being modified, ie they are in the Unchanged state            \r
-                var deleteCandidates = FileState.Queryable.Where(state =>\r
-                    state.FilePath.StartsWith(accountInfo.AccountPath)\r
-                    && state.FileStatus == FileStatus.Unchanged).ToList();\r
-\r
+                if (Log.IsDebugEnabled)\r
+                    Log.DebugFormat("Handle deleted [{0}]", objectInfo.Uri);\r
+                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);\r
+                var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);\r
+                if (Log.IsDebugEnabled)\r
+                    Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName, objectInfo.Uri);\r
+                if (item.Exists)\r
+                {\r
+                    if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)\r
+                    {\r
+                        item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;\r
 \r
 \r
-                //TODO: filesToDelete must take into account the Others container            \r
-                var filesToDelete = (from deleteCandidate in deleteCandidates\r
-                                     let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)\r
-                                     let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)\r
-                                     where\r
-                                         !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)\r
-                                     select localFile).ToList();\r
+                    }\r
 \r
 \r
 \r
 \r
+                    Log.DebugFormat("Deleting {0}", item.FullName);\r
 \r
 \r
-                //Set the status of missing files to Conflict\r
-                foreach (var item in filesToDelete)\r
-                {\r
-                    //Try to acquire a gate on the file, to take into account files that have been dequeued\r
-                    //and are being processed\r
-                    using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))\r
-                    {\r
-                        if (gate.Failed)\r
-                            continue;\r
-                        StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted,"Local file missing from server");\r
-                    }\r
+                    var directory = item as DirectoryInfo;\r
+                    if (directory != null)\r
+                        directory.Delete(true);\r
+                    else\r
+                        item.Delete();\r
+                    Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);\r
+                    DateTime lastDate;\r
+                    _lastSeen.TryRemove(item.FullName, out lastDate);\r
+                    deletedFiles.Add(item);\r
                 }\r
                 }\r
-                UpdateStatus(PithosStatus.HasConflicts);\r
-                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted", filesToDelete.Count));\r
-                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);\r
+                StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted, "File Deleted");\r
             }\r
             }\r
-            else\r
-            {\r
-                var deletedFiles = new List<FileSystemInfo>();\r
-                foreach (var objectInfo in cloudFiles)\r
-                {\r
-                    if (Log.IsDebugEnabled)\r
-                        Log.DebugFormat("Handle deleted [{0}]",objectInfo.Uri);\r
-                    var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);\r
-                    var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);\r
-                    if (Log.IsDebugEnabled)\r
-                        Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName,objectInfo.Uri);\r
-                    if (item.Exists)\r
-                    {\r
-                        if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)\r
-                        {\r
-                            item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;\r
+            Log.InfoFormat("[{0}] files were deleted", deletedFiles.Count);\r
+            StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count),\r
+                                              TraceLevel.Info);\r
 \r
 \r
-                        }\r
-                        \r
-                        \r
-                        Log.DebugFormat("Deleting {0}", item.FullName);\r
+        }\r
 \r
 \r
-                        var directory = item as DirectoryInfo;\r
-                        if (directory!=null)\r
-                            directory.Delete(true);\r
-                        else\r
-                            item.Delete();\r
-                        Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);\r
-                        DateTime lastDate;\r
-                        _lastSeen.TryRemove(item.FullName, out lastDate);\r
-                        deletedFiles.Add(item);\r
-                    }\r
-                    StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted, "File Deleted");\r
+        private void MarkSuspectedDeletes(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)\r
+        {\r
+//Only consider files that are not being modified, ie they are in the Unchanged state            \r
+            var deleteCandidates = FileState.Queryable.Where(state =>\r
+                                                             state.FilePath.StartsWith(accountInfo.AccountPath)\r
+                                                             && state.FileStatus == FileStatus.Unchanged).ToList();\r
+\r
+\r
+            //TODO: filesToDelete must take into account the Others container            \r
+            var filesToDelete = (from deleteCandidate in deleteCandidates\r
+                                 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)\r
+                                 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)\r
+                                 where\r
+                                     !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)\r
+                                 select localFile).ToList();\r
+\r
+\r
+            //Set the status of missing files to Conflict\r
+            foreach (var item in filesToDelete)\r
+            {\r
+                //Try to acquire a gate on the file, to take into account files that have been dequeued\r
+                //and are being processed\r
+                using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))\r
+                {\r
+                    if (gate.Failed)\r
+                        continue;\r
+                    StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted,\r
+                                              "Local file missing from server");\r
                 }\r
                 }\r
-                Log.InfoFormat("[{0}] files were deleted",deletedFiles.Count);\r
-                StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);\r
             }\r
             }\r
+            UpdateStatus(PithosStatus.HasConflicts);\r
+            StatusNotification.NotifyConflicts(filesToDelete,\r
+                                               String.Format(\r
+                                                   "{0} local files are missing from Pithos, possibly because they were deleted",\r
+                                                   filesToDelete.Count));\r
+            StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count),\r
+                                              TraceLevel.Info);\r
+        }\r
 \r
 \r
+        private void ReportConflictForMismatch(string localFilePath)\r
+        {\r
+            if (String.IsNullOrWhiteSpace(localFilePath))\r
+                throw new ArgumentNullException("localFilePath");\r
+            Contract.EndContractBlock();\r
+\r
+            StatusKeeper.SetFileState(localFilePath, FileStatus.Conflict, FileOverlayStatus.Conflict, "File changed at the server");\r
+            UpdateStatus(PithosStatus.HasConflicts);\r
+            var message = String.Format("Conflict detected for file {0}", localFilePath);\r
+            Log.Warn(message);\r
+            StatusNotification.NotifyChange(message, TraceLevel.Warning);\r
         }\r
 \r
         }\r
 \r
+\r
+\r
         /// <summary>\r
         /// Creates a Sync action for each changed server file\r
         /// </summary>\r
         /// <summary>\r
         /// Creates a Sync action for each changed server file\r
         /// </summary>\r
@@ -550,7 +1069,7 @@ namespace Pithos.Core.Agents
                                                      previousFile, objectInfo, state, accountInfo.BlockSize,\r
                                                      accountInfo.BlockHash,"Poll Moves");\r
                         //For modified files, we need to download the changes as well\r
                                                      previousFile, objectInfo, state, accountInfo.BlockSize,\r
                                                      accountInfo.BlockHash,"Poll Moves");\r
                         //For modified files, we need to download the changes as well\r
-                        if (objectInfo.Hash!=objectInfo.PreviousHash)\r
+                        if (objectInfo.X_Object_Hash != objectInfo.PreviousHash)\r
                             yield return new CloudDownloadAction(accountInfo,objectInfo, "Poll Moves");\r
                     }\r
                 }\r
                             yield return new CloudDownloadAction(accountInfo,objectInfo, "Poll Moves");\r
                     }\r
                 }\r
@@ -645,6 +1164,7 @@ namespace Pithos.Core.Agents
         {\r
             AccountInfo account;\r
             _accounts.TryRemove(accountInfo.AccountKey, out account);\r
         {\r
             AccountInfo account;\r
             _accounts.TryRemove(accountInfo.AccountKey, out account);\r
+\r
             SnapshotDifferencer differencer;\r
             _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);\r
         }\r
             SnapshotDifferencer differencer;\r
             _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);\r
         }\r
@@ -652,9 +1172,10 @@ namespace Pithos.Core.Agents
         public void SetSelectivePaths(AccountInfo accountInfo,Uri[] added, Uri[] removed)\r
         {\r
             AbortRemovedPaths(accountInfo,removed);\r
         public void SetSelectivePaths(AccountInfo accountInfo,Uri[] added, Uri[] removed)\r
         {\r
             AbortRemovedPaths(accountInfo,removed);\r
-            DownloadNewPaths(accountInfo,added);\r
+            //DownloadNewPaths(accountInfo,added);\r
         }\r
 \r
         }\r
 \r
+/*\r
         private void DownloadNewPaths(AccountInfo accountInfo, Uri[] added)\r
         {\r
             var client = new CloudFilesClient(accountInfo);\r
         private void DownloadNewPaths(AccountInfo accountInfo, Uri[] added)\r
         {\r
             var client = new CloudFilesClient(accountInfo);\r
@@ -707,8 +1228,9 @@ namespace Pithos.Core.Agents
             //Need to get a listing of each of the URLs, then post them to the NetworkAgent\r
             //CreatesToActions(accountInfo,)\r
 \r
             //Need to get a listing of each of the URLs, then post them to the NetworkAgent\r
             //CreatesToActions(accountInfo,)\r
 \r
-/*            NetworkAgent.Post();*/\r
+/*            NetworkAgent.Post();#1#\r
         }\r
         }\r
+*/\r
 \r
         private void AbortRemovedPaths(AccountInfo accountInfo, Uri[] removed)\r
         {\r
 \r
         private void AbortRemovedPaths(AccountInfo accountInfo, Uri[] removed)\r
         {\r