Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 68 additions & 10 deletions SFTPSyncLib/RemoteSync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public static async Task RunSharedInitialSyncAsync(
{
using (var sftp = new SftpClient(host, username, password))
{
sftp.Connect();
await ConnectWithRetryAsync(sftp, "directory creation");
await CreateDirectoriesInternal(sftp, localRootDirectory, localRootDirectory, remoteRootDirectory, excludedFolders);
}
}
Expand All @@ -147,27 +147,85 @@ public static async Task RunSharedInitialSyncAsync(

for (int i = 0; i < workerCount; i++)
{
int workerNumber = i + 1;
workers.Add(Task.Run(async () =>
{
using (var sftp = new SftpClient(host, username, password))
{
sftp.Connect();
try
{
await ConnectWithRetryAsync(sftp, $"sync worker {workerNumber}");
}
catch (Exception ex)
{
// Other workers drain the shared queue. If none can connect, this is reported after WhenAll.
Logger.LogWarnig($"Sync worker {workerNumber} could not connect and will not take part in the initial sync. Exception: {ex.Message}");
return;
}

while (workQueue.TryDequeue(out var item))
{
try
{
await SyncDirectoryAsync(sftp, item.LocalPath, item.RemotePath, item.SearchPattern);
}
catch (Exception ex)
{
Logger.LogError($"Sync failed for {item.LocalPath} ({item.SearchPattern}). Exception: {ex.Message}");
}
await SyncDirectoryWithRetryAsync(sftp, item);
}
}
}));
}

await Task.WhenAll(workers);

if (!workQueue.IsEmpty)
{
throw new InvalidOperationException("Initial sync could not complete because no sync worker was able to connect.");
}
}

private const int MaxAttempts = 3;
private const int RetryDelayMs = 2000;

private static async Task ConnectWithRetryAsync(SftpClient sftp, string description)
{
for (int attempt = 1; ; attempt++)
{
try
{
sftp.Connect();
return;
}
catch (Exception ex) when (attempt < MaxAttempts)
{
Logger.LogWarnig($"Connection for {description} failed (attempt {attempt}/{MaxAttempts}), retrying. Exception: {ex.Message}");
await Task.Delay(RetryDelayMs * attempt);
}
}
}

private static async Task SyncDirectoryWithRetryAsync(SftpClient sftp, SyncWorkItem item)
{
for (int attempt = 1; ; attempt++)
{
try
{
// Re-establish the connection if a previous timeout dropped it.
if (!sftp.IsConnected)
{
sftp.Connect();
}

await SyncDirectoryAsync(sftp, item.LocalPath, item.RemotePath, item.SearchPattern);
return;
}
catch (Exception ex)
{
if (attempt >= MaxAttempts)
{
Logger.LogError($"Sync failed for {item.LocalPath} ({item.SearchPattern}) after {MaxAttempts} attempts. Exception: {ex.Message}");
return;
}

Logger.LogWarnig($"Sync failed for {item.LocalPath} ({item.SearchPattern}) (attempt {attempt}/{MaxAttempts}), retrying. Exception: {ex.Message}");
await Task.Delay(RetryDelayMs * attempt);
}
}
}

/// <summary>
Expand Down
5 changes: 5 additions & 0 deletions SFTPSyncUI/SFTPSyncUI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,11 @@ public static async void StartSync(Action<string> loggerAction)
var initialSyncTcs = new TaskCompletionSource<object?>();
var initialSyncTask = initialSyncTcs.Task;

// The workers only poll DoneInitialSync.IsCompleted, so a faulted task would otherwise never be
// observed and later surface as an "Unobserved task exception". The failure itself is reported
// where runInitialSyncTask is awaited below.
_ = initialSyncTask.ContinueWith(t => _ = t.Exception, TaskContinuationOptions.OnlyOnFaulted);

foreach (var pattern in patterns)
{
if (token.IsCancellationRequested)
Expand Down