diff --git a/SFTPSync/SFTPSync.cs b/SFTPSync/SFTPSync.cs index a812003..f4a08e3 100644 --- a/SFTPSync/SFTPSync.cs +++ b/SFTPSync/SFTPSync.cs @@ -1,5 +1,4 @@ - -using SFTPSyncLib; +using SFTPSyncLib; namespace SFTPSync { @@ -14,23 +13,27 @@ static async Task Main(string[] args) else { var director = new SyncDirector(args[3]); - List remoteSyncWorkers = new List(); - Logger.LogInfo("Starting initial sync..."); - - foreach (var pattern in args[5].Split(';', StringSplitOptions.RemoveEmptyEntries)) - { - if (remoteSyncWorkers.Count > 0) + var remoteSync = new RemoteSync( + new RemoteSyncOptions { - await remoteSyncWorkers[0].DoneMakingFolders; - } - remoteSyncWorkers.Add(new RemoteSync(args[0], args[1], args[2], args[3], args[4], pattern, remoteSyncWorkers.Count == 0, director, null, false, remoteSyncWorkers.Count == 0)); + Host = args[0], + Username = args[1], + Password = args[2], + LocalRootDirectory = args[3], + RemoteRootDirectory = args[4], + SearchPatterns = args[5].Split(';', StringSplitOptions.RemoveEmptyEntries) + .Select(pattern => pattern.Trim()) + .Where(pattern => pattern.Length > 0) + .ToArray() + }, + director); + + director.Start(); - Logger.LogInfo($"Started sync worker {remoteSyncWorkers.Count} for pattern {pattern}"); - } + Logger.LogInfo("Starting initial sync..."); - //Wait for all sync workers to finish initial sync then tell the user - await Task.WhenAll(remoteSyncWorkers.Select(rsw => rsw.DoneInitialSync)); + await remoteSync.InitialSyncAsync(); Logger.LogInfo("Initial sync complete, real-time sync active"); @@ -46,14 +49,11 @@ static async Task Main(string[] args) } } - foreach (var remoteSync in remoteSyncWorkers) + try { - try - { - remoteSync.Dispose(); - } - catch { } + remoteSync.Dispose(); } + catch { } } } } diff --git a/SFTPSyncLib/RemoteSync.cs b/SFTPSyncLib/RemoteSync.cs index dc9920c..0557d13 100644 --- a/SFTPSyncLib/RemoteSync.cs +++ b/SFTPSyncLib/RemoteSync.cs @@ -1,394 +1,923 @@ using Renci.SshNet; +using Renci.SshNet.Common; using Renci.SshNet.Sftp; using System.Collections.Concurrent; +using System.Diagnostics; +using System.IO.Enumeration; using System.Text.RegularExpressions; +using System.Threading.Channels; namespace SFTPSyncLib { - public class RemoteSync : IDisposable + /// + /// Keeps a local directory tree in sync with a remote one. The initial sync shares its work between a number of + /// temporary connections, and afterwards changes are uploaded through a small elastic pool of connections, whatever + /// the number of search patterns. + /// + public sealed class RemoteSync : IDisposable { - string _host; - string _username; - string _password; - string _searchPattern; - string _localRootDirectory; - string _remoteRootDirectory; - readonly List? _excludedFolders; - readonly bool _deleteEnabled; - readonly CancellationTokenSource _shutdownCts = new CancellationTokenSource(); - readonly object _disposeLock = new object(); - Task? _connectTask; - - SftpClient _sftp; - SyncDirector _director; - HashSet _activeDirSync = new HashSet(); - readonly SemaphoreSlim _sftpLock = new SemaphoreSlim(1, 1); - bool _disposed; + private static readonly TimeSpan IdleConnectionTimeout = TimeSpan.FromSeconds(60); + + // Bounds the number of changed files being prepared (waiting for a connection or for the file to be writable) + private const int MaxPendingFileTasks = 64; + + private readonly RemoteSyncOptions _options; + private readonly string[] _searchPatterns; + private readonly string _localRootDirectory; + private readonly string _remoteRootDirectory; + private readonly List _excludedFolders; + private readonly bool _deleteEnabled; + private readonly SyncDirector _director; + private readonly CancellationTokenSource _shutdownCts = new CancellationTokenSource(); + private readonly CancellationToken _token; + private readonly SftpConnectionPool _pool; + private readonly object _disposeLock = new object(); + private bool _disposed; + + // Set once the initial sync has completed. File system events before then are ignored. + private volatile bool _realtimeActive; + + // Changes waiting to be uploaded. A file that changes again before its upload has started is only uploaded once. + private readonly object _queueLock = new object(); + private readonly Dictionary _pending = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _inFlight = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _blocked = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly Channel _queue = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); + private readonly SemaphoreSlim _pendingFileTasks = new SemaphoreSlim(MaxPendingFileTasks); + private long _directoryOperationSequence; + + // Remote directories that are known to exist, to avoid checking for them before every upload + private readonly ConcurrentDictionary _knownRemoteDirectories = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + private readonly object _directoryCreateLock = new object(); // VS writes to a temp file (8 alphanum chars + "." + 1-4 alphanum chars + "~") then renames it to the real file. // The temp was never synced remotely, so suppress the "not found" cleanup warning for these names. private static readonly Regex _vsTempFilePattern = new Regex(@"^[a-zA-Z0-9]{8}\.[a-zA-Z0-9]{1,4}~$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static bool IsVsTempFile(string path) => _vsTempFilePattern.IsMatch(Path.GetFileName(path)); - - public Task DoneMakingFolders { get; } - - public Task DoneInitialSync { get; } - - public RemoteSync(string host, string username, string password, - string localRootDirectory, string remoteRootDirectory, - string searchPattern, bool createFolders, SyncDirector director, List? excludedFolders, bool deleteEnabled, bool handleDirectoryDeletes) + public RemoteSync(RemoteSyncOptions options, SyncDirector director) { - _host = host; - _username = username; - _password = password; - _searchPattern = searchPattern; - _localRootDirectory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(localRootDirectory)); - _remoteRootDirectory = remoteRootDirectory.TrimEnd('/', '\\'); + _options = options; + _searchPatterns = options.SearchPatterns; + _localRootDirectory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(options.LocalRootDirectory)); + _remoteRootDirectory = options.RemoteRootDirectory.TrimEnd('/', '\\'); + _excludedFolders = options.ExcludedFolders ?? new List(); + _deleteEnabled = options.DeleteEnabled; _director = director; - _excludedFolders = excludedFolders ?? new List(); - _deleteEnabled = deleteEnabled; - _sftp = new SftpClient(host, username, password); + _token = _shutdownCts.Token; + _pool = new SftpConnectionPool(options.Host, options.Username, options.Password, + options.MaxConnections, IdleConnectionTimeout); - //The first instance is responsible for creating ALL of the the directories. - //Subsequent instances will not be created until this one completes. + // Register callbacks immediately; events are ignored until the initial sync has completed. + foreach (var pattern in _searchPatterns) + { + _director.AddCallback(pattern, OnFileEvent); + } + + if (_deleteEnabled) + { + _director.AddDirectoryDeleteCallback(args => OnDirectoryEvent(DirectoryOperation.Delete, args.FullPath, null)); + } + _director.AddDirectoryCreateCallback(args => OnDirectoryEvent(DirectoryOperation.Create, args.FullPath, null)); + _director.AddDirectoryRenameCallback(args => OnDirectoryEvent(DirectoryOperation.Rename, args.FullPath, args.OldFullPath)); + } - DoneMakingFolders = createFolders - ? CreateDirectories(_localRootDirectory, _remoteRootDirectory) - : Task.CompletedTask; + // ------------------------------------------------------------------------------------------------------------ + // Real-time sync: file system events are queued, then uploaded by whichever pooled connection is free + // ------------------------------------------------------------------------------------------------------------ - //Now perform the initial sync for the pattern this instance is responsible for + private enum ChangeKind + { + Upload, + Delete, + DirectoryCreate, + DirectoryDelete, + DirectoryRename + } - DoneInitialSync = InitialSync(_localRootDirectory, _remoteRootDirectory); + private enum DirectoryOperation + { + Create, + Delete, + Rename + } - // Register callbacks immediately; handler will ignore events until initial sync completes. - _director.AddCallback(searchPattern, (args) => Fsw_Changed(null, args)); - if (deleteEnabled && handleDirectoryDeletes) + private sealed class PendingChange + { + public PendingChange(ChangeKind kind, string path, string? oldPath) { - _director.AddDirectoryDeleteCallback((args) => Fsw_DirectoryDeleted(null, args)); + Kind = kind; + Path = path; + OldPath = oldPath; } - if (handleDirectoryDeletes) + + public ChangeKind Kind { get; private set; } + public string Path { get; } + + /// For a rename, the previous local path of the file or directory. + public string? OldPath { get; private set; } + + public bool IsDirectoryOperation => Kind >= ChangeKind.DirectoryCreate; + + /// Fold a newer event for the same file into this one that has not been started yet. + public void MergeFrom(PendingChange newer) { - _director.AddDirectoryCreateCallback((args) => Fsw_DirectoryCreated(null, args)); - _director.AddDirectoryRenameCallback((args) => Fsw_DirectoryRenamed(null, args)); + Kind = newer.Kind; + OldPath = newer.OldPath ?? OldPath; } } - public RemoteSync(string host, string username, string password, - string localRootDirectory, string remoteRootDirectory, - string searchPattern, SyncDirector director, List? excludedFolders, Task initialSyncTask, bool deleteEnabled, bool handleDirectoryDeletes) + private void OnFileEvent(FileSystemEventArgs arg) { - _host = host; - _username = username; - _password = password; - _searchPattern = searchPattern; - _localRootDirectory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(localRootDirectory)); - _remoteRootDirectory = remoteRootDirectory.TrimEnd('/', '\\'); - _director = director; - _excludedFolders = excludedFolders ?? new List(); - _deleteEnabled = deleteEnabled; - _sftp = new SftpClient(host, username, password); - - DoneMakingFolders = Task.CompletedTask; - - DoneInitialSync = initialSyncTask; + if (!_realtimeActive || _token.IsCancellationRequested) + return; - // Register callbacks immediately; handler will ignore events until initial sync completes. - _director.AddCallback(searchPattern, (args) => Fsw_Changed(null, args)); - if (deleteEnabled && handleDirectoryDeletes) + try { - _director.AddDirectoryDeleteCallback((args) => Fsw_DirectoryDeleted(null, args)); + if (arg.ChangeType == WatcherChangeTypes.Deleted) + { + if (_deleteEnabled) + { + Enqueue(arg.FullPath, new PendingChange(ChangeKind.Delete, arg.FullPath, null)); + } + } + else if (arg.ChangeType == WatcherChangeTypes.Changed || arg.ChangeType == WatcherChangeTypes.Created + || arg.ChangeType == WatcherChangeTypes.Renamed) + { + var oldPath = (arg as RenamedEventArgs)?.OldFullPath; + Enqueue(arg.FullPath, new PendingChange(ChangeKind.Upload, arg.FullPath, oldPath)); + } } - if (handleDirectoryDeletes) + catch (Exception ex) { - _director.AddDirectoryCreateCallback((args) => Fsw_DirectoryCreated(null, args)); - _director.AddDirectoryRenameCallback((args) => Fsw_DirectoryRenamed(null, args)); + Logger.LogError($"Unhandled file event exception: {ex.Message}"); } } - public static async Task RunSharedInitialSyncAsync( - string host, string username, string password, - string localRootDirectory, string remoteRootDirectory, - string[] searchPatterns, List? excludedFolders, int workerCount) + private void OnDirectoryEvent(DirectoryOperation operation, string path, string? oldPath) { - if (workerCount <= 0 || searchPatterns.Length == 0) - { + if (!_realtimeActive || _token.IsCancellationRequested) return; - } - - localRootDirectory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(localRootDirectory)); - remoteRootDirectory = NormalizeRemoteRootDirectory(remoteRootDirectory); try { - using (var sftp = new SftpClient(host, username, password)) + if (IsExcludedDirectoryPath(path) || (oldPath != null && IsExcludedDirectoryPath(oldPath))) + return; + + var kind = operation switch { - await ConnectWithRetryAsync(sftp, "directory creation"); - await CreateDirectoriesInternal(sftp, localRootDirectory, localRootDirectory, remoteRootDirectory, excludedFolders); - } + DirectoryOperation.Create => ChangeKind.DirectoryCreate, + DirectoryOperation.Delete => ChangeKind.DirectoryDelete, + _ => ChangeKind.DirectoryRename + }; + + // Directory operations are never merged, so each gets its own key + var key = $"\0directory:{Interlocked.Increment(ref _directoryOperationSequence)}"; + Enqueue(key, new PendingChange(kind, path, oldPath)); } catch (Exception ex) { - Logger.LogError($"Create directories failed. Exception: {ex.Message}"); - throw; + Logger.LogError($"Unhandled directory event exception: {ex.Message}"); } + } - var workQueue = new ConcurrentQueue(); - - foreach (var pair in EnumerateLocalDirectories(localRootDirectory, remoteRootDirectory, excludedFolders)) + private void Enqueue(string key, PendingChange change) + { + lock (_queueLock) { - foreach (var pattern in searchPatterns) + if (_pending.TryGetValue(key, out var existing)) { - workQueue.Enqueue(new SyncWorkItem(pair.LocalPath, pair.RemotePath, pattern)); + existing.MergeFrom(change); + return; } + + _pending[key] = change; } - var workers = new List(); + _queue.Writer.TryWrite(key); + } - for (int i = 0; i < workerCount; i++) + /// + /// Takes changes from the queue in order. Files are uploaded in parallel (up to the connection limit), but a + /// directory operation waits for everything started before it and then runs on its own, so a directory is never + /// deleted or renamed underneath an upload. + /// + private async Task DispatchLoopAsync() + { + var running = new List(); + + try { - int workerNumber = i + 1; - workers.Add(Task.Run(async () => + while (await _queue.Reader.WaitToReadAsync(_token).ConfigureAwait(false)) { - using (var sftp = new SftpClient(host, username, password)) + while (_queue.Reader.TryRead(out var key)) { - try + PendingChange? change; + + lock (_queueLock) { - await ConnectWithRetryAsync(sftp, $"sync worker {workerNumber}"); + if (!_pending.TryGetValue(key, out change)) + continue; + + // Never upload the same file on two connections at once. It is queued again when the first finishes. + if (!change.IsDirectoryOperation && _inFlight.Contains(key)) + { + _blocked.Add(key); + continue; + } + + _pending.Remove(key); + + if (!change.IsDirectoryOperation) + { + _inFlight.Add(key); + } } - catch (Exception ex) + + if (change.IsDirectoryOperation) { - // 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; - } + await Task.WhenAll(running).ConfigureAwait(false); + running.Clear(); - while (workQueue.TryDequeue(out var item)) + await Task.Run(() => ProcessDirectoryChange(change), _token).ConfigureAwait(false); + } + else { - await SyncDirectoryWithRetryAsync(sftp, item); + await _pendingFileTasks.WaitAsync(_token).ConfigureAwait(false); + + var fileKey = key; + var fileChange = change; + running.Add(Task.Run(() => ProcessFileChangeAsync(fileKey, fileChange))); + + if (running.Count >= MaxPendingFileTasks * 2) + { + running.RemoveAll(t => t.IsCompleted); + } } } - })); + } } - - await Task.WhenAll(workers); - - if (!workQueue.IsEmpty) + catch (OperationCanceledException) + { + // Shutting down + } + catch (Exception ex) { - throw new InvalidOperationException("Initial sync could not complete because no sync worker was able to connect."); + Logger.LogError($"Sync queue stopped unexpectedly. Exception: {ex.Message}"); } } - private const int MaxAttempts = 3; - private const int RetryDelayMs = 2000; - - private static async Task ConnectWithRetryAsync(SftpClient sftp, string description) + private async Task ProcessFileChangeAsync(string key, PendingChange change) { - for (int attempt = 1; ; attempt++) + try { - try - { - sftp.Connect(); + if (_token.IsCancellationRequested) return; + + if (change.Kind == ChangeKind.Upload) + { + if (Directory.Exists(change.Path)) + return; + + // Wait for whatever is writing the file to finish, without holding on to a connection + var waitStart = DateTime.UtcNow; + while (!IsFileReady(change.Path)) + { + if (!File.Exists(change.Path)) + return; + + if (DateTime.UtcNow - waitStart > TimeSpan.FromSeconds(30)) + { + Logger.LogWarnig($"Timeout waiting for file ready: {change.Path}"); + return; + } + + await Task.Delay(25, _token).ConfigureAwait(false); + } } - catch (Exception ex) when (attempt < MaxAttempts) + + using (var lease = await _pool.AcquireAsync(_token).ConfigureAwait(false)) { - Logger.LogWarnig($"Connection for {description} failed (attempt {attempt}/{MaxAttempts}), retrying. Exception: {ex.Message}"); - await Task.Delay(RetryDelayMs * attempt); + if (change.Kind == ChangeKind.Upload) + { + SyncChangedFile(lease.Client, change); + } + else + { + SyncFileDelete(lease.Client, change); + } + } + } + catch (OperationCanceledException) + { + // Shutting down + } + catch (Exception ex) + { + Logger.LogError($"Unhandled file sync exception: {ex.Message}"); + } + finally + { + _pendingFileTasks.Release(); + + lock (_queueLock) + { + _inFlight.Remove(key); + + if (_blocked.Remove(key)) + { + _queue.Writer.TryWrite(key); + } } } } - private static async Task SyncDirectoryWithRetryAsync(SftpClient sftp, SyncWorkItem item) + /// + /// Sync changes for a file. This is only used for changes AFTER the initial sync has completed. + /// + private void SyncChangedFile(SftpClient sftp, PendingChange change) { + var localPath = change.Path; + var remoteFilePath = GetRemotePathForLocal(localPath); + var remoteDirectoryPath = GetRemotePathForLocal(Path.GetDirectoryName(localPath) ?? _localRootDirectory); + + Logger.LogInfo($"Syncing {localPath}"); + + const int maxRetries = 5; + const int delayBetweenRetriesMs = 500; + for (int attempt = 1; ; attempt++) { try { - // Re-establish the connection if a previous timeout dropped it. + if (!File.Exists(localPath)) + return; // Gone again already; a delete event will follow if it matters + if (!sftp.IsConnected) { sftp.Connect(); } - await SyncDirectoryAsync(sftp, item.LocalPath, item.RemotePath, item.SearchPattern); - return; + EnsureRemoteDirectory(sftp, remoteDirectoryPath); + + // Because the VMS SFTP server uses Posix not RMS, and some older servers do not correctly + // handle truncating files when the content gets shorter (resulting in corruption at the end of the file), + // we delete the file first if it exists, before writing new content. + DeleteRemoteFileIfPresent(sftp, remoteFilePath); + + sftp.WriteAllText(remoteFilePath, File.ReadAllText(localPath)); + break; } catch (Exception ex) { - if (attempt >= MaxAttempts) + // Make sure the directory is checked for again + _knownRemoteDirectories.TryRemove(remoteDirectoryPath, out _); + + if (attempt >= maxRetries) { - Logger.LogError($"Sync failed for {item.LocalPath} ({item.SearchPattern}) after {MaxAttempts} attempts. Exception: {ex.Message}"); + Logger.LogError($"Sync failed after {maxRetries} retries. 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); + Logger.LogInfo($"Retry {attempt}/{maxRetries} after exception: {ex.Message}"); + Thread.Sleep(delayBetweenRetriesMs); } } + + DeleteRenamedSource(sftp, change, remoteFilePath); } /// - /// Sync changes for a file. This is only used for changes AFTER the initial sync has completed. + /// After a file has been renamed, delete the remote copy under its old name. /// - /// SFTP client - /// Path to the source file - /// Path to the destination file - public static void SyncFile(SftpClient sftp, string sourcePath, string destinationPath) + private void DeleteRenamedSource(SftpClient sftp, PendingChange change, string remoteFilePath) { - Logger.LogInfo($"Syncing {sourcePath}"); + if (!_deleteEnabled || change.OldPath == null || IsVsTempFile(change.OldPath)) + return; - int retryCount = 0; - const int maxRetries = 5; - const int delayBetweenRetriesMs = 500; + var oldRemoteFilePath = GetRemotePathForLocal(change.OldPath); + + if (string.Equals(oldRemoteFilePath, remoteFilePath, StringComparison.OrdinalIgnoreCase)) + return; - while (retryCount < maxRetries) + if (sftp.Exists(oldRemoteFilePath)) { - try + var attributes = sftp.GetAttributes(oldRemoteFilePath); + if (!attributes.IsDirectory) { - // Because the VMS SFTP server uses Posix not RMS, and some older servers do not correctly - // handle truncating files when the content gets shorter (resulting in corruption at the end of the file), - // we delete the file first if it exists, before writing new content. - if (sftp.Exists(destinationPath)) + sftp.DeleteFile(oldRemoteFilePath); + } + else + { + Logger.LogWarnig($"Rename cleanup skipped (directory): {oldRemoteFilePath}"); + } + } + else + { + Logger.LogWarnig($"Rename cleanup skipped (not found): {oldRemoteFilePath}"); + } + } + + private void SyncFileDelete(SftpClient sftp, PendingChange change) + { + var remotePath = GetRemotePathForLocal(change.Path); + + if (!sftp.IsConnected) + { + sftp.Connect(); + } + + if (sftp.Exists(remotePath)) + { + var attributes = sftp.GetAttributes(remotePath); + + if (!attributes.IsDirectory) + { + Logger.LogInfo($"Syncing delete {change.Path}"); + sftp.DeleteFile(remotePath); + } + else + { + Logger.LogWarnig($"Syncing delete skipped (directory): {remotePath}"); + } + } + else + { + Logger.LogWarnig($"Syncing delete {remotePath} not found"); + } + + DeleteRenamedSource(sftp, change, remotePath); + } + + /// + /// Make sure a remote directory (and any missing parents below the root) exists. + /// + private void EnsureRemoteDirectory(SftpClient sftp, string remotePath) + { + if (_knownRemoteDirectories.ContainsKey(remotePath)) + return; + + // Uploads run in parallel, so make sure only one of them creates a directory + lock (_directoryCreateLock) + { + EnsureRemoteDirectoryLocked(sftp, remotePath); + } + } + + private void EnsureRemoteDirectoryLocked(SftpClient sftp, string remotePath) + { + if (_knownRemoteDirectories.ContainsKey(remotePath)) + return; + + // The remote root must already exist (it is checked when the initial sync starts) + if (remotePath.Length > _remoteRootDirectory.Length && !sftp.Exists(remotePath)) + { + var separator = remotePath.LastIndexOf('/'); + if (separator > 0 && separator >= _remoteRootDirectory.Length) + { + EnsureRemoteDirectoryLocked(sftp, remotePath.Substring(0, separator)); + } + + Logger.LogInfo($"Creating directory {remotePath}"); + sftp.CreateDirectory(remotePath); + } + + _knownRemoteDirectories[remotePath] = 0; + } + + private void ForgetRemoteDirectories(string remotePath) + { + foreach (var known in _knownRemoteDirectories.Keys) + { + if (string.Equals(known, remotePath, StringComparison.OrdinalIgnoreCase) + || known.StartsWith(remotePath + "/", StringComparison.OrdinalIgnoreCase)) + { + _knownRemoteDirectories.TryRemove(known, out _); + } + } + } + + private void ProcessDirectoryChange(PendingChange change) + { + try + { + if (_token.IsCancellationRequested) + return; + + using (var lease = _pool.AcquireAsync(_token).GetAwaiter().GetResult()) + { + var sftp = lease.Client; + + switch (change.Kind) { - sftp.DeleteFile(destinationPath); + case ChangeKind.DirectoryCreate: + EnsureRemoteDirectory(sftp, GetRemotePathForLocal(change.Path)); + break; + + case ChangeKind.DirectoryDelete: + DeleteRemoteDirectory(sftp, change); + break; + + case ChangeKind.DirectoryRename: + RenameRemoteDirectory(sftp, change); + break; } + } + } + catch (OperationCanceledException) + { + // Shutting down + } + catch (Exception ex) + { + Logger.LogError($"Unhandled directory sync exception: {ex.Message}"); + } + } - // Read the local file content - var localFileContent = File.ReadAllText(sourcePath); + private void DeleteRemoteDirectory(SftpClient sftp, PendingChange change) + { + var remotePath = GetRemotePathForLocal(change.Path); + ForgetRemoteDirectories(remotePath); - // Write the remote file - sftp.WriteAllText(destinationPath, localFileContent); + if (!sftp.Exists(remotePath) && !sftp.Exists(remotePath + ".DIR")) + { + Logger.LogWarnig($"Deleting directory skipped (not found): {remotePath}"); + } + else + { + Logger.LogInfo($"Deleting directory {remotePath}"); + DeleteRemotePathRecursive(sftp, remotePath); + } + } + + private void RenameRemoteDirectory(SftpClient sftp, PendingChange change) + { + var oldRemotePath = GetRemotePathForLocal(change.OldPath ?? change.Path); + var newRemotePath = GetRemotePathForLocal(change.Path); + // OpenVMS directory names preserve case but are case-insensitive. A case-only + // local rename therefore refers to the same remote directory and needs no action. + if (string.Equals(oldRemotePath, newRemotePath, StringComparison.OrdinalIgnoreCase)) + { + Logger.LogInfo($"Ignoring case-only directory rename: {oldRemotePath} -> {newRemotePath}"); + return; + } + + ForgetRemoteDirectories(oldRemotePath); + + if (TryRenameRemoteDirectory(sftp, oldRemotePath, newRemotePath)) + { + Logger.LogInfo($"Renamed directory {oldRemotePath} -> {newRemotePath}"); + return; + } + + Logger.LogWarnig($"Directory rename failed. Attempting fallback: {oldRemotePath} -> {newRemotePath}"); + + MoveRemoteDirectoryRecursive(sftp, oldRemotePath, newRemotePath); + + Logger.LogInfo($"Fallback directory rename completed: {oldRemotePath} -> {newRemotePath}"); + } + + // ------------------------------------------------------------------------------------------------------------ + // Initial sync + // ------------------------------------------------------------------------------------------------------------ + + 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) + catch (Exception ex) when (attempt < MaxAttempts) { - retryCount++; - if (retryCount >= maxRetries) + Logger.LogWarnig($"Connection for {description} failed (attempt {attempt}/{MaxAttempts}), retrying. Exception: {ex.Message}"); + await Task.Delay(RetryDelayMs * attempt); + } + } + } + + + private sealed class SyncChunk + { + public SyncChunk(string remotePath, string[] files) + { + RemotePath = remotePath; + Files = files; + } + + public string RemotePath { get; } + public string[] Files { get; } + } + + private int _initialSyncFilesDone; + + private static readonly TimeSpan ProgressInterval = TimeSpan.FromSeconds(5); + + /// + /// Raised during the initial sync with the number of files uploaded so far and the total to upload. This can be + /// raised on any thread. + /// + public event Action? InitialSyncProgress; + + private async Task ReportProgressAsync(int totalFiles, CancellationToken token) + { + try + { + using (var timer = new PeriodicTimer(ProgressInterval)) + { + while (await timer.WaitForNextTickAsync(token).ConfigureAwait(false)) { - Logger.LogError($"Sync failed after {maxRetries} retries. Exception: {ex.Message}"); - return; + PublishProgress(totalFiles, logIt: true); } - - Logger.LogInfo($"Retry {retryCount}/{maxRetries} after exception: {ex.Message}"); - Thread.Sleep(delayBetweenRetriesMs); } } + catch (OperationCanceledException) + { + // The initial sync has finished + } } - public static Task> SyncDirectoryAsync(SftpClient sftp, string sourcePath, string destinationPath, string searchPattern) + private void PublishProgress(int totalFiles, bool logIt) { - if (new DirectoryInfo(sourcePath).EnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly).Any()) + int done = Volatile.Read(ref _initialSyncFilesDone); + + if (logIt) { - Logger.LogInfo($"Initial sync started for {sourcePath}\\{searchPattern}"); + Logger.LogInfo($"Initial sync: {done} of {totalFiles} files uploaded ({(totalFiles == 0 ? 100 : done * 100L / totalFiles)}%)"); + } - return Task.Run(() => UploadTopLevelFiles(sftp, sourcePath, destinationPath, searchPattern)); + try + { + InitialSyncProgress?.Invoke(done, totalFiles); } - else + catch (Exception ex) { - return Task.FromResult(Enumerable.Empty()); + Logger.LogError($"Progress notification failed. Exception: {ex.Message}"); } } /// - /// Uploads only the files directly in sourcePath (not subdirectories) to destinationPath. - /// SftpClient.SynchronizeDirectories enumerates recursively but uploads by file name only, which flattens - /// subdirectory files into every parent remote directory. Callers visit each directory individually, so - /// recursion is not needed. Remote files are deleted first, as the VMS server may not truncate correctly. + /// Create any missing remote directories, upload every matching file, then switch to real-time syncing. /// - private static IEnumerable UploadTopLevelFiles(SftpClient sftp, string sourcePath, string destinationPath, string searchPattern) + public async Task InitialSyncAsync() { - var uploadedFiles = new List(); + var stopwatch = Stopwatch.StartNew(); + var remoteRoot = NormalizeRemoteRootDirectory(_options.RemoteRootDirectory); + + try + { + using (var sftp = new SftpClient(_options.Host, _options.Username, _options.Password)) + { + await ConnectWithRetryAsync(sftp, "directory creation"); + await CreateDirectoriesInternal(sftp, _localRootDirectory, _localRootDirectory, remoteRoot, _excludedFolders); + } + } + catch (Exception ex) + { + Logger.LogError($"Create directories failed. Exception: {ex.Message}"); + throw; + } + + _token.ThrowIfCancellationRequested(); - foreach (var localFile in new DirectoryInfo(sourcePath).EnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly)) + // Look at each directory once, rather than once per pattern, and split large directories into chunks so that + // several connections can share them (one directory can hold thousands of files). The biggest chunks go first, + // so no connection is left uploading a large one on its own at the end. + var directories = EnumerateLocalDirectories(_localRootDirectory, remoteRoot, _excludedFolders).ToList(); + var chunkSize = Math.Max(1, _options.InitialSyncChunkSize); + var chunks = new List(); + int totalFiles = 0; + + foreach (var directory in directories) { - var remoteFileName = $"{destinationPath}/{localFile.Name}"; + _knownRemoteDirectories[directory.RemotePath] = 0; - try + var files = new DirectoryInfo(directory.LocalPath) + .EnumerateFiles("*", SearchOption.TopDirectoryOnly) + .Select(file => file.FullName) + .Where(path => MatchesSearchPattern(Path.GetFileName(path))) + .ToArray(); + + totalFiles += files.Length; + + for (int start = 0; start < files.Length; start += chunkSize) { - if (sftp.Exists(remoteFileName)) - { - sftp.DeleteFile(remoteFileName); - } + chunks.Add(new SyncChunk(directory.RemotePath, files.Skip(start).Take(chunkSize).ToArray())); + } + } + + var workQueue = new ConcurrentQueue(chunks.OrderByDescending(chunk => chunk.Files.Length)); + int workerCount = Math.Max(1, Math.Min(_options.InitialSyncWorkers, chunks.Count)); + + if (chunks.Count > 0) + { + Logger.LogInfo($"Initial sync: {totalFiles} files in {directories.Count} directories, using {workerCount} connections"); + + PublishProgress(totalFiles, logIt: false); + + using var progressCts = CancellationTokenSource.CreateLinkedTokenSource(_token); + var progressReporter = Task.Run(() => ReportProgressAsync(totalFiles, progressCts.Token)); - using (var file = File.OpenRead(localFile.FullName)) + var workers = new List(); + + for (int i = 0; i < workerCount; i++) + { + int workerNumber = i + 1; + workers.Add(Task.Run(async () => { - sftp.UploadFile(file, remoteFileName, canOverride: true); - } + using (var sftp = new SftpClient(_options.Host, _options.Username, _options.Password)) + { + 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; + } - uploadedFiles.Add(localFile); + try + { + while (!_token.IsCancellationRequested && workQueue.TryDequeue(out var chunk)) + { + await SyncChunkWithRetryAsync(sftp, chunk); + } + } + catch (OperationCanceledException) + { + // Shutting down + } + } + })); } - catch (Exception ex) + + try + { + await Task.WhenAll(workers); + } + finally + { + progressCts.Cancel(); + } + + await progressReporter; + PublishProgress(totalFiles, logIt: false); + + _token.ThrowIfCancellationRequested(); + + if (!workQueue.IsEmpty) { - throw new Exception($"Failed to upload {localFile.FullName} to {remoteFileName}", ex); + throw new InvalidOperationException("Initial sync could not complete because no sync worker was able to connect."); } } - return uploadedFiles; + Logger.LogInfo($"Initial sync finished: {_initialSyncFilesDone} of {totalFiles} files in {stopwatch.Elapsed.TotalSeconds:0.0} seconds"); + + // From now on changes are synced as they happen + _realtimeActive = true; + _ = Task.Run(DispatchLoopAsync); + + // Open the one connection that is kept warm, so the first change is not delayed by connecting + _ = Task.Run(async () => + { + try + { + using (await _pool.AcquireAsync(_token)) + { + } + } + catch (Exception) + { + // Reported when a change needs a connection + } + }); } - private string[] FilteredDirectories(string localPath) + private bool MatchesSearchPattern(string fileName) { - return FilteredDirectories(_localRootDirectory, localPath, _excludedFolders); + foreach (var pattern in _searchPatterns) + { + if (FileSystemName.MatchesSimpleExpression(pattern, fileName, ignoreCase: true)) + return true; + } + + return false; } - public async Task CreateDirectories(string localPath, string remotePath) + private async Task SyncChunkWithRetryAsync(SftpClient sftp, SyncChunk chunk) { - Logger.LogInfo($"Creating directory {remotePath}"); + int index = 0; - try + for (int attempt = 1; ; attempt++) { - if (!EnsureConnectedSafe()) + try + { + // Re-establish the connection if a previous timeout dropped it. + if (!sftp.IsConnected) + { + sftp.Connect(); + } + + // A retry carries on from the file that failed, not from the start of the chunk + for (; index < chunk.Files.Length; index++) + { + _token.ThrowIfCancellationRequested(); + UploadInitialFile(sftp, chunk.Files[index], chunk.RemotePath); + Interlocked.Increment(ref _initialSyncFilesDone); + } + return; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + var failedFile = index < chunk.Files.Length ? chunk.Files[index] : chunk.RemotePath; - await CreateDirectoriesInternal(_sftp, _localRootDirectory, localPath, remotePath, _excludedFolders); - } - catch (Exception) - { - Logger.LogError("Failed to create directories. Check the remote target directory exists."); + if (attempt >= MaxAttempts) + { + Logger.LogError($"Sync failed for {failedFile} after {MaxAttempts} attempts. Exception: {ex.Message}"); + return; + } - Environment.Exit(-1); + Logger.LogWarnig($"Sync failed for {failedFile} (attempt {attempt}/{MaxAttempts}), retrying. Exception: {ex.Message}"); + await Task.Delay(RetryDelayMs * attempt, _token); + } } } /// - /// For the pattern we are responsible for, sync the files in the local directory to the remote directory. + /// Delete a remote file before it is replaced, if it is there. This tries the delete straight away, rather than + /// checking for the file first, which saves a round trip for every file that exists. + /// + /// Only "file not found" may be ignored. Any other failure must stop the upload: if the old file were left in + /// place, the server could write the new content over it without truncating, leaving stale data at the end. /// - /// Local directory path - /// Remote directory path - /// - public async Task InitialSync(string localPath, string remotePath) + private static void DeleteRemoteFileIfPresent(SftpClient sftp, string remoteFilePath) { - //Wait for the folders to be created before starting the initial sync - await DoneMakingFolders; + try + { + sftp.DeleteFile(remoteFilePath); + } + catch (SftpPathNotFoundException) + { + // Not there, so there is nothing to delete + } + catch (SshException) + { + // A server that reports a missing file as some other failure: only carry on if the file really is absent + if (sftp.Exists(remoteFilePath)) + throw; + } + } - if (!EnsureConnectedSafe()) - return; + /// + /// Remote files are deleted first, as the VMS server may not truncate correctly. + /// + private static void UploadInitialFile(SftpClient sftp, string localFile, string remoteDirectory) + { + var remoteFileName = $"{remoteDirectory}/{Path.GetFileName(localFile)}"; - //Get the local directories to sync - var localDirectories = FilteredDirectories(localPath) - .OrderBy(path => path, StringComparer.OrdinalIgnoreCase) - .ToArray(); + try + { + DeleteRemoteFileIfPresent(sftp, remoteFileName); - //Get the remote directories to sync, removing the .DIR suffix if it exists - var remoteDirectories = (await ListDirectoryAsync(_sftp, remotePath)).Where(item => item.IsDirectory).ToDictionary(item => + using (var file = File.OpenRead(localFile)) + { + sftp.UploadFile(file, remoteFileName, canOverride: true); + } + } + catch (Exception ex) { - if (item.Name.Contains(".DIR", StringComparison.OrdinalIgnoreCase)) - return item.Name.Remove(item.Name.IndexOf(".DIR", StringComparison.OrdinalIgnoreCase)); - else - return item.Name; - }); + throw new Exception($"Failed to upload {localFile} to {remoteFileName}", ex); + } + } - // - foreach (var item in localDirectories) + public void Dispose() + { + lock (_disposeLock) { - var directoryName = item.Split(Path.DirectorySeparatorChar).Last(); - var nextRemotePath = AppendRemotePath(remotePath, directoryName); - await InitialSync(localPath + "\\" + directoryName, nextRemotePath); + if (_disposed) + return; + + _disposed = true; } - await SyncDirectoryAsync(_sftp, localPath, remotePath, _searchPattern); + _realtimeActive = false; + _shutdownCts.Cancel(); + _queue.Writer.TryComplete(); + _pool.Dispose(); + _shutdownCts.Dispose(); } private static string[] FilteredDirectories(string localRootDirectory, string localPath, List? excludedFolders) @@ -551,415 +1080,6 @@ private static string AppendRemotePath(string remotePath, string segment) return remotePath + "/" + normalizedSegment; } - private void EnsureConnected() - { - if (_disposed) - throw new ObjectDisposedException(nameof(RemoteSync)); - - if (_sftp.IsConnected) - return; - - _sftp.Connect(); - } - - private bool EnsureConnectedSafe() - { - try - { - EnsureConnected(); - return true; - } - catch (Exception ex) - { - Logger.LogError($"SFTP connection error: {ex.Message}"); - return false; - } - } - - public Task ConnectAsync() - { - var task = Task.Run(() => EnsureConnectedSafe()); - _connectTask = task; - return task; - } - - - private async void Fsw_Changed(object? sender, FileSystemEventArgs arg) - { - try - { - if (_shutdownCts.IsCancellationRequested) - return; - - if (!DoneInitialSync.IsCompleted) - return; - - if (_deleteEnabled && arg.ChangeType == WatcherChangeTypes.Deleted) - { - await SyncFileDeleteAsync(arg); - return; - } - - if (arg.ChangeType == WatcherChangeTypes.Changed || arg.ChangeType == WatcherChangeTypes.Created - || arg.ChangeType == WatcherChangeTypes.Renamed) - { - var renamedArgs = arg as RenamedEventArgs; - var changedPath = Path.GetDirectoryName(arg.FullPath); - var fullRemotePath = GetRemotePathForLocal(changedPath ?? _localRootDirectory); - var fullRemoteFilePath = GetRemotePathForLocal(arg.FullPath); - var oldRemoteFilePath = renamedArgs != null - ? GetRemotePathForLocal(renamedArgs.OldFullPath) - : null; - await Task.Yield(); - bool makeDirectory = true; - lock (_activeDirSync) - { - if (changedPath == null) - return; - if (_activeDirSync.Contains(changedPath)) - makeDirectory = false; - else - _activeDirSync.Add(changedPath); - } - - bool connectionOk; - await _sftpLock.WaitAsync(); - try - { - connectionOk = EnsureConnectedSafe(); - if (connectionOk) - { - //check if we're a new directory - if (makeDirectory && changedPath != null && Directory.Exists(changedPath) && !_sftp.Exists(fullRemotePath)) - { - _sftp.CreateDirectory(fullRemotePath); - } - } - } - finally - { - _sftpLock.Release(); - } - - if (!connectionOk) - { - if (makeDirectory) - { - lock (_activeDirSync) - { - _activeDirSync.Remove(changedPath); - } - } - return; - } - - if (makeDirectory) - { - lock (_activeDirSync) - { - _activeDirSync.Remove(changedPath); - } - } - - if (Directory.Exists(arg.FullPath)) - return; - - var waitStart = DateTime.UtcNow; - while (!IsFileReady(arg.FullPath)) - { - if (!File.Exists(arg.FullPath)) - return; - if (DateTime.UtcNow - waitStart > TimeSpan.FromSeconds(30)) - { - Logger.LogWarnig($"Timeout waiting for file ready: {arg.FullPath}"); - return; - } - await Task.Delay(25); - } - - lock (_activeDirSync) - { - if (_activeDirSync.Contains(arg.FullPath)) - return; - else - _activeDirSync.Add(arg.FullPath); - } - - bool fileConnectionOk; - await _sftpLock.WaitAsync(); - try - { - fileConnectionOk = EnsureConnectedSafe(); - if (fileConnectionOk) - { - SyncFile(_sftp, arg.FullPath, fullRemoteFilePath); - - if (_deleteEnabled && oldRemoteFilePath != null - && !IsVsTempFile(renamedArgs!.OldFullPath) - && !string.Equals(oldRemoteFilePath, fullRemoteFilePath, StringComparison.OrdinalIgnoreCase)) - { - if (_sftp.Exists(oldRemoteFilePath)) - { - var attributes = _sftp.GetAttributes(oldRemoteFilePath); - if (!attributes.IsDirectory) - { - _sftp.DeleteFile(oldRemoteFilePath); - } - else - { - Logger.LogWarnig($"Rename cleanup skipped (directory): {oldRemoteFilePath}"); - } - } - else - { - Logger.LogWarnig($"Rename cleanup skipped (not found): {oldRemoteFilePath}"); - } - } - else if (_deleteEnabled && renamedArgs != null && oldRemoteFilePath == null) - { - Logger.LogWarnig("Rename cleanup skipped (missing old path)."); - } - } - } - finally - { - _sftpLock.Release(); - lock (_activeDirSync) - { - _activeDirSync.Remove(arg.FullPath); - } - } - - if (!fileConnectionOk) - return; - } - } - catch (Exception ex) - { - Logger.LogError($"Unhandled file sync handler exception: {ex.Message}"); - } - } - - private async void Fsw_DirectoryDeleted(object? sender, FileSystemEventArgs arg) - { - try - { - if (_shutdownCts.IsCancellationRequested) - return; - - if (!DoneInitialSync.IsCompleted) - return; - - if (IsExcludedDirectoryPath(arg.FullPath)) - return; - - var remotePath = GetRemotePathForLocal(arg.FullPath); - await _sftpLock.WaitAsync(); - try - { - if (EnsureConnectedSafe()) - { - if (!_sftp.Exists(remotePath) && !_sftp.Exists(remotePath + ".DIR")) - { - Logger.LogWarnig($"Deleting directory skipped (not found): {remotePath}"); - } - else - { - Logger.LogInfo($"Deleting directory {remotePath}"); - DeleteRemotePathRecursive(_sftp, remotePath); - } - } - } - finally - { - _sftpLock.Release(); - } - } - catch (Exception ex) - { - Logger.LogError($"Unhandled directory delete handler exception: {ex.Message}"); - } - } - - private async void Fsw_DirectoryCreated(object? sender, FileSystemEventArgs arg) - { - try - { - if (_shutdownCts.IsCancellationRequested) - return; - - if (!DoneInitialSync.IsCompleted) - return; - - if (IsExcludedDirectoryPath(arg.FullPath)) - return; - - var remotePath = GetRemotePathForLocal(arg.FullPath); - await _sftpLock.WaitAsync(); - try - { - if (EnsureConnectedSafe()) - { - if (!_sftp.Exists(remotePath)) - { - Logger.LogInfo($"Creating directory {remotePath}"); - _sftp.CreateDirectory(remotePath); - } - } - } - finally - { - _sftpLock.Release(); - } - } - catch (Exception ex) - { - Logger.LogError($"Unhandled directory create handler exception: {ex.Message}"); - } - } - - private async void Fsw_DirectoryRenamed(object? sender, RenamedEventArgs arg) - { - try - { - if (_shutdownCts.IsCancellationRequested) - return; - - if (!DoneInitialSync.IsCompleted) - return; - - if (IsExcludedDirectoryPath(arg.OldFullPath) || IsExcludedDirectoryPath(arg.FullPath)) - return; - - var oldRemotePath = GetRemotePathForLocal(arg.OldFullPath); - var newRemotePath = GetRemotePathForLocal(arg.FullPath); - - // OpenVMS directory names preserve case but are case-insensitive. A case-only - // local rename therefore refers to the same remote directory and needs no action. - if (string.Equals(oldRemotePath, newRemotePath, StringComparison.OrdinalIgnoreCase)) - { - Logger.LogInfo($"Ignoring case-only directory rename: {oldRemotePath} -> {newRemotePath}"); - return; - } - - await _sftpLock.WaitAsync(); - try - { - if (!EnsureConnectedSafe()) - return; - - if (TryRenameRemoteDirectory(_sftp, oldRemotePath, newRemotePath)) - { - Logger.LogInfo($"Renamed directory {oldRemotePath} -> {newRemotePath}"); - return; - } - - Logger.LogWarnig($"Directory rename failed. Attempting fallback: {oldRemotePath} -> {newRemotePath}"); - - MoveRemoteDirectoryRecursive(_sftp, oldRemotePath, newRemotePath); - - Logger.LogInfo($"Fallback directory rename completed: {oldRemotePath} -> {newRemotePath}"); - } - finally - { - _sftpLock.Release(); - } - } - catch (Exception ex) - { - Logger.LogError($"Unhandled directory rename handler exception: {ex.Message}"); - } - } - - private async Task SyncFileDeleteAsync(FileSystemEventArgs arg) - { - if (_shutdownCts.IsCancellationRequested) - return; - - var remotePath = GetRemotePathForLocal(arg.FullPath); - - await _sftpLock.WaitAsync(); - - try - { - if (!EnsureConnectedSafe()) - return; - - if (_sftp.Exists(remotePath)) - { - var attributes = _sftp.GetAttributes(remotePath); - - if (!attributes.IsDirectory) - { - Logger.LogInfo($"Syncing delete {arg.FullPath}"); - _sftp.DeleteFile(remotePath); - } - else - { - Logger.LogWarnig($"Syncing delete skipped (directory): {remotePath}"); - } - } - else - { - Logger.LogWarnig($"Syncing delete {remotePath} not found"); - } - } - finally - { - _sftpLock.Release(); - } - } - - public void Dispose() - { - lock (_disposeLock) - { - if (_disposed) - return; - - if (!_shutdownCts.IsCancellationRequested) - { - _shutdownCts.Cancel(); - } - - var connectTask = _connectTask; - if (connectTask != null && !connectTask.IsCompleted) - { - _ = connectTask.ContinueWith(_ => DisposeNow(), TaskScheduler.Default); - return; - } - - DisposeNow(); - } - } - - private void DisposeNow() - { - lock (_disposeLock) - { - if (_disposed) - return; - - _disposed = true; - _shutdownCts.Dispose(); - _sftp.Dispose(); - } - } - - private sealed class SyncWorkItem - { - public SyncWorkItem(string localPath, string remotePath, string searchPattern) - { - LocalPath = localPath; - RemotePath = remotePath; - SearchPattern = searchPattern; - } - - public string LocalPath { get; } - public string RemotePath { get; } - public string SearchPattern { get; } - } - private bool IsExcludedDirectoryPath(string localPath) { var fullPath = Path.GetFullPath(localPath).TrimEnd(Path.DirectorySeparatorChar); diff --git a/SFTPSyncLib/RemoteSyncOptions.cs b/SFTPSyncLib/RemoteSyncOptions.cs new file mode 100644 index 0000000..ad2a7c1 --- /dev/null +++ b/SFTPSyncLib/RemoteSyncOptions.cs @@ -0,0 +1,39 @@ +namespace SFTPSyncLib +{ + /// + /// Everything a needs to know about what to sync and how many connections it may use. + /// + public sealed class RemoteSyncOptions + { + public const int DefaultInitialSyncWorkers = 20; + public const int DefaultMaxConnections = 6; + public const int DefaultInitialSyncChunkSize = 50; + + public string Host { get; set; } = string.Empty; + public string Username { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public string LocalRootDirectory { get; set; } = string.Empty; + public string RemoteRootDirectory { get; set; } = string.Empty; + + /// The file name patterns (for example *.DBL) that are synced. + public string[] SearchPatterns { get; set; } = Array.Empty(); + + public List? ExcludedFolders { get; set; } + public bool DeleteEnabled { get; set; } + + /// + /// The number of connections used (temporarily) to run the initial sync. Work is shared between them, so this is + /// independent of the number of search patterns. + /// + public int InitialSyncWorkers { get; set; } = DefaultInitialSyncWorkers; + + /// + /// The most connections that will be open at once for real-time syncing. Connections are only opened when there is + /// work for them (for example after switching Git branch) and are closed again when idle. + /// + public int MaxConnections { get; set; } = DefaultMaxConnections; + + /// Directories with more files than this are split so that several connections can share them. + public int InitialSyncChunkSize { get; set; } = DefaultInitialSyncChunkSize; + } +} diff --git a/SFTPSyncLib/SftpConnectionPool.cs b/SFTPSyncLib/SftpConnectionPool.cs new file mode 100644 index 0000000..fc88774 --- /dev/null +++ b/SFTPSyncLib/SftpConnectionPool.cs @@ -0,0 +1,209 @@ +using Renci.SshNet; + +namespace SFTPSyncLib +{ + /// + /// A small elastic pool of SFTP connections. A connection is only opened when work needs one and none is idle (up to + /// the maximum), and idle connections are closed after a while. One connection is always kept warm so that the first + /// change after a quiet period is not delayed by a reconnect. + /// + internal sealed class SftpConnectionPool : IDisposable + { + private const int MaxConnectAttempts = 3; + private const int ConnectRetryDelayMs = 2000; + private static readonly TimeSpan KeepAliveInterval = TimeSpan.FromSeconds(30); + + private readonly string _host; + private readonly string _username; + private readonly string _password; + private readonly TimeSpan _idleTimeout; + private readonly SemaphoreSlim _slots; + private readonly List _idle = new List(); + private readonly object _lock = new object(); + private readonly Timer _reaper; + private bool _disposed; + + public SftpConnectionPool(string host, string username, string password, int maxConnections, TimeSpan idleTimeout) + { + _host = host; + _username = username; + _password = password; + _idleTimeout = idleTimeout; + _slots = new SemaphoreSlim(Math.Max(1, maxConnections)); + _reaper = new Timer(_ => CloseIdleConnections(), null, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15)); + } + + /// + /// Wait for a free slot, then return a connected client (an idle one if there is one, otherwise a new one). + /// Dispose the lease to give the connection back. + /// + public async Task AcquireAsync(CancellationToken token) + { + await _slots.WaitAsync(token).ConfigureAwait(false); + + SftpClient? client = null; + try + { + for (int attempt = 1; ; attempt++) + { + client = TakeIdle() ?? CreateClient(); + try + { + if (!client.IsConnected) + { + var toConnect = client; + await Task.Run(() => toConnect.Connect(), token).ConfigureAwait(false); + } + return new Lease(this, client); + } + catch (Exception ex) when (attempt < MaxConnectAttempts && !token.IsCancellationRequested) + { + Logger.LogWarnig($"SFTP connection failed (attempt {attempt}/{MaxConnectAttempts}), retrying. Exception: {ex.Message}"); + DisposeQuietly(client); + client = null; + await Task.Delay(ConnectRetryDelayMs * attempt, token).ConfigureAwait(false); + } + } + } + catch + { + DisposeQuietly(client); + _slots.Release(); + throw; + } + } + + private SftpClient CreateClient() + { + return new SftpClient(_host, _username, _password) { KeepAliveInterval = KeepAliveInterval }; + } + + private SftpClient? TakeIdle() + { + lock (_lock) + { + if (_idle.Count == 0) + return null; + + // Most recently used first, so busy connections stay warm and the others age out + var entry = _idle[_idle.Count - 1]; + _idle.RemoveAt(_idle.Count - 1); + return entry.Client; + } + } + + private void Release(SftpClient client) + { + bool keep; + lock (_lock) + { + keep = !_disposed && client.IsConnected; + if (keep) + { + _idle.Add(new IdleConnection(client, DateTime.UtcNow)); + } + } + + if (!keep) + { + DisposeQuietly(client); + } + + try + { + _slots.Release(); + } + catch (ObjectDisposedException) + { + } + } + + private void CloseIdleConnections() + { + List? expired = null; + + lock (_lock) + { + if (_disposed) + return; + + var now = DateTime.UtcNow; + + // The oldest are at the start. Always leave one warm connection. + while (_idle.Count > 1 && now - _idle[0].IdleSince > _idleTimeout) + { + expired ??= new List(); + expired.Add(_idle[0].Client); + _idle.RemoveAt(0); + } + } + + if (expired != null) + { + Logger.LogInfo($"Closing {expired.Count} idle SFTP connection(s)"); + foreach (var client in expired) + { + DisposeQuietly(client); + } + } + } + + private static void DisposeQuietly(SftpClient? client) + { + try + { + client?.Dispose(); + } + catch + { + // Closing a dead connection can throw; nothing useful to do about it + } + } + + public void Dispose() + { + List idle; + + lock (_lock) + { + if (_disposed) + return; + + _disposed = true; + idle = new List(_idle); + _idle.Clear(); + } + + _reaper.Dispose(); + + // Closing a connection can block for a long time if the server is slow, so close them in parallel. + // Connections that are in use are closed when their lease is returned. + Parallel.ForEach(idle, entry => DisposeQuietly(entry.Client)); + } + + private readonly record struct IdleConnection(SftpClient Client, DateTime IdleSince); + + public sealed class Lease : IDisposable + { + private readonly SftpConnectionPool _pool; + private SftpClient? _client; + + internal Lease(SftpConnectionPool pool, SftpClient client) + { + _pool = pool; + _client = client; + } + + public SftpClient Client => _client ?? throw new ObjectDisposedException(nameof(Lease)); + + public void Dispose() + { + var client = Interlocked.Exchange(ref _client, null); + if (client != null) + { + _pool.Release(client); + } + } + } + } +} diff --git a/SFTPSyncUI/AppSettings.cs b/SFTPSyncUI/AppSettings.cs index ba0627f..133ad83 100644 --- a/SFTPSyncUI/AppSettings.cs +++ b/SFTPSyncUI/AppSettings.cs @@ -1,4 +1,5 @@  +using SFTPSyncLib; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -599,6 +600,46 @@ public string RemotePath } } + // The number of connections used during the initial sync (work is shared between them) + + private int initialSyncWorkers = RemoteSyncOptions.DefaultInitialSyncWorkers; + + public int InitialSyncWorkers + { + get => initialSyncWorkers; + set + { + if (initialSyncWorkers != value) + { + initialSyncWorkers = value; + if (!initialLoadSettings) + { + SaveToFile(); + } + } + } + } + + // The most connections open at once for real-time syncing (opened as needed, closed when idle) + + private int maxConnections = RemoteSyncOptions.DefaultMaxConnections; + + public int MaxConnections + { + get => maxConnections; + set + { + if (maxConnections != value) + { + maxConnections = value; + if (!initialLoadSettings) + { + SaveToFile(); + } + } + } + } + //Excluded directories, stored as paths relative to LocalPath private List excludedDirectories = new List(); diff --git a/SFTPSyncUI/SFTPSyncUI.cs b/SFTPSyncUI/SFTPSyncUI.cs index 637c92c..a39dded 100644 --- a/SFTPSyncUI/SFTPSyncUI.cs +++ b/SFTPSyncUI/SFTPSyncUI.cs @@ -1,4 +1,4 @@ - + using Microsoft.Win32; using SFTPSyncLib; using System.IO.Pipes; @@ -200,7 +200,7 @@ static void RemoveProgramFromStartup() } } - public static List RemoteSyncWorkers = new List(); + private static RemoteSync? activeSync; private static SyncDirector? activeDirector; private static Task? syncTask; private static CancellationTokenSource? syncCts; @@ -220,7 +220,7 @@ public static async void StartSync(Action loggerAction) return; Logger.LogUpdated += loggerAction; - Logger.LogInfo("Starting sync workers..."); + Logger.LogInfo("Starting sync..."); var setStatus = new Action(status => { @@ -246,12 +246,6 @@ public static async void StartSync(Action loggerAction) if (token.IsCancellationRequested) return; - var director = new SyncDirector(settings.LocalPath, settings.DeleteEnabled); - lock (DirectorLock) - { - activeDirector = director; - } - var patterns = settings.LocalSearchPattern .Split(';', StringSplitOptions.RemoveEmptyEntries) .Select(pattern => pattern.Trim()) @@ -260,130 +254,74 @@ public static async void StartSync(Action loggerAction) if (patterns.Length == 0) { - if (!token.IsCancellationRequested) - { - Logger.LogError("No valid search patterns were configured."); - setStatus("Invalid search patterns"); - } + Logger.LogError("No valid search patterns were configured."); + setStatus("Invalid search patterns"); return; } - var initialSyncTcs = new TaskCompletionSource(); - 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) - return; - - try - { - int workerIndex; - RemoteSync worker; - lock (RemoteSyncLock) - { - workerIndex = RemoteSyncWorkers.Count; - worker = new RemoteSync( - settings.RemoteHost, - settings.RemoteUsername, - DPAPIEncryption.Decrypt(settings.RemotePassword), - settings.LocalPath, - settings.RemotePath, - pattern, - director, - settings.GetExcludedDirectoryFullPaths(), - initialSyncTask, - settings.DeleteEnabled, - workerIndex == 0); - RemoteSyncWorkers.Add(worker); - } - - Logger.LogInfo($"Started sync worker {workerIndex + 1} for pattern {pattern}"); - } - catch (Exception) - { - if (!token.IsCancellationRequested) - Logger.LogError($"Failed to start sync worker for pattern {pattern}"); - } - } - - director.Start(); - - var connectTasks = new List(); - - RemoteSync[] workerSnapshot; - lock (RemoteSyncLock) - { - workerSnapshot = RemoteSyncWorkers.ToArray(); - } - - if (token.IsCancellationRequested) - return; - - Logger.LogInfo($"Establishing SFTP connections for {workerSnapshot.Length} workers"); - - for (int i = 0; i < workerSnapshot.Length; i++) + var director = new SyncDirector(settings.LocalPath, settings.DeleteEnabled); + lock (DirectorLock) { - connectTasks.Add(workerSnapshot[i].ConnectAsync()); + activeDirector = director; } - await Task.WhenAll(connectTasks); - Task runInitialSyncTask; + RemoteSync sync; try { - runInitialSyncTask = RemoteSync.RunSharedInitialSyncAsync( - settings.RemoteHost, - settings.RemoteUsername, - DPAPIEncryption.Decrypt(settings.RemotePassword), - settings.LocalPath, - settings.RemotePath, - patterns, - settings.GetExcludedDirectoryFullPaths(), - patterns.Length); + sync = new RemoteSync( + new RemoteSyncOptions + { + Host = settings.RemoteHost, + Username = settings.RemoteUsername, + Password = DPAPIEncryption.Decrypt(settings.RemotePassword), + LocalRootDirectory = settings.LocalPath, + RemoteRootDirectory = settings.RemotePath, + SearchPatterns = patterns, + ExcludedFolders = settings.GetExcludedDirectoryFullPaths(), + DeleteEnabled = settings.DeleteEnabled, + InitialSyncWorkers = Math.Max(1, settings.InitialSyncWorkers), + MaxConnections = Math.Max(1, settings.MaxConnections) + }, + director); } catch (Exception ex) { if (!token.IsCancellationRequested) { - Logger.LogError($"Failed to start initial sync. Exception: {ex.Message}"); - setStatus("Initial sync failed"); + Logger.LogError($"Failed to start sync. Exception: {ex.Message}"); + setStatus("Sync failed"); } return; } + lock (RemoteSyncLock) + { + activeSync = sync; + } + + // StopSync may have run before the sync was registered, in which case nobody else will dispose it if (token.IsCancellationRequested) + { + sync.Dispose(); return; + } - await runInitialSyncTask.ContinueWith(t => + sync.InitialSyncProgress += (done, total) => { - if (token.IsCancellationRequested) - return; - - if (t.IsFaulted && t.Exception != null) - { - initialSyncTcs.TrySetException(t.Exception.InnerExceptions); - } - else if (t.IsCanceled) - { - initialSyncTcs.TrySetCanceled(); - } - else - { - initialSyncTcs.TrySetResult(null); - } - }, TaskScheduler.Default); + if (!token.IsCancellationRequested) + setStatus($"Performing initial sync: {done} of {total} files ({(total == 0 ? 100 : done * 100L / total)}%)... DO NOT ALTER SYNCED FILES UNTIL COMPLETE"); + }; - //Wait for all sync workers to finish initial sync then tell the user + director.Start(); try { - await runInitialSyncTask; + await sync.InitialSyncAsync(); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + return; } catch (Exception ex) { @@ -437,29 +375,27 @@ public static async Task StopSync(Action loggerAction) Logger.LogUpdated -= loggerAction; - RemoteSync[] workerSnapshot; + RemoteSync? sync; lock (RemoteSyncLock) { - workerSnapshot = RemoteSyncWorkers.ToArray(); - RemoteSyncWorkers.Clear(); + sync = activeSync; + activeSync = null; } // Closing an SFTP connection is a blocking network call that can take a long time if the server is slow - // to respond, so tear everything down on background threads (in parallel) to keep the UI responsive. + // to respond, so tear everything down on a background thread (the connections are closed in parallel) + // to keep the UI responsive. await Task.Run(() => { - Parallel.ForEach(workerSnapshot, remoteSync => + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + try { - var stopwatch = System.Diagnostics.Stopwatch.StartNew(); - try - { - remoteSync.Dispose(); - } - catch { /* Swallow any exceptions */ } + sync?.Dispose(); + } + catch { /* Swallow any exceptions */ } - if (stopwatch.Elapsed > TimeSpan.FromSeconds(2)) - Logger.LogInfo($"Closing a connection took {stopwatch.Elapsed.TotalSeconds:0.0} seconds"); - }); + if (stopwatch.Elapsed > TimeSpan.FromSeconds(2)) + Logger.LogInfo($"Closing the connections took {stopwatch.Elapsed.TotalSeconds:0.0} seconds"); lock (DirectorLock) {