Path: redb-route/redb.Route.GenericFile/RemoteFileConsumer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.GenericFile/RemoteFileConsumer.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.GenericFile; /// /// Base class for remote file consumers (SFTP, FTP). Extends /// with connection lifecycle management: auto-connect before poll, reconnect on failure, /// disconnect after poll if configured, and remote-specific features (MaxAge, MoveFailed, SendEmptyMessageWhenIdle). /// /// Concrete options type inheriting . public abstract class RemoteFileConsumer : GenericFileConsumer where TOptions : RemoteFileEndpointOptions { private readonly IRemoteFileOperations _remoteOps; /// Remote file operations with connection lifecycle. protected IRemoteFileOperations RemoteOperations => _remoteOps; /// Creates a remote file consumer. protected RemoteFileConsumer(IEndpoint endpoint, IProcessor processor, TOptions options, IRemoteFileOperations operations) : base(endpoint, processor, options, operations) { ArgumentNullException.ThrowIfNull(operations); _remoteOps = operations; } /// protected override Task OnStopped() { DisconnectClient(); return Task.CompletedTask; } // ═══════════════════════════════════════════════════════════════════ // HOOKS // ═══════════════════════════════════════════════════════════════════ /// /// Connects to the remote server and validates the starting directory if required. /// protected override async Task BeforePollAsync(CancellationToken ct) { await EnsureConnectedAsync(ct).ConfigureAwait(false); if (Options.StartingDirectoryMustExist && !await Operations.DirectoryExistsAsync(BasePath, ct).ConfigureAwait(false)) { throw new DirectoryNotFoundException( $"Starting directory does not exist: {BasePath} on {Options.Host}:{Options.Port}"); } } /// /// Disconnects from the remote server if the Disconnect option is set. /// protected override Task AfterPollAsync(List files, CancellationToken ct) { if (Options.Disconnect) DisconnectClient(); return Task.CompletedTask; } /// /// Sends an empty exchange when idle if is set. /// protected override async Task OnNoFilesFoundAsync(CancellationToken ct) { if (!Options.SendEmptyMessageWhenIdle) return; var emptyExchange = Exchange.Create(new Message { Body = null }, ConsumerEndpoint.ScopeFactory); emptyExchange.Pattern = ExchangePattern.InOnly; try { await Processor.Process(emptyExchange, ct).ConfigureAwait(false); } finally { await emptyExchange.DisposeAsync().ConfigureAwait(false); } } /// Disconnects from the remote server on poll error to force a fresh connection on next poll. protected override void OnPollError(Exception ex) { DisconnectClient(); } /// Checks maximum file age based on . protected override bool CheckMaxAge(GenericFileInfo file) { if (Options.MaxAge <= 0) return true; var ageMs = (DateTimeOffset.UtcNow - file.LastModified).TotalMilliseconds; return ageMs <= Options.MaxAge; } /// Moves the file to the MoveFailed directory if configured. protected override Task OnProcessingFailedAsync(GenericFileInfo file, string workPath, CancellationToken ct) => MoveFailedAsync(new GenericFileFacts(file, workPath, Operations), workPath, file.Name, file.BasePath, ct); /// protected override Task OnProcessingFailedAsync(string filePath, string fileName, string basePath, CancellationToken ct) => MoveFailedAsync(new GenericFileFacts(fileName, filePath, basePath, Operations), filePath, fileName, basePath, ct); private async Task MoveFailedAsync(IFileFacts facts, string filePath, string fileName, string basePath, CancellationToken ct) { if (string.IsNullOrEmpty(Options.MoveFailed)) return; try { var failedDir = ResolveDirectory( GenericFileUtils.SubstituteFileTokens(facts, Options.MoveFailed), basePath); await Operations.CreateDirectoryAsync(failedDir, ct).ConfigureAwait(false); var targetPath = Operations.CombinePath(failedDir, fileName); if (await Operations.ExistsAsync(targetPath, ct).ConfigureAwait(false)) { try { await Operations.DeleteAsync(targetPath, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: failed to delete target before move-failed {Path}", ConsumerName, targetPath); } } await Operations.MoveAsync(filePath, targetPath, false, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: failed to move file to failed directory {File}", ConsumerName, fileName); } } // ═══════════════════════════════════════════════════════════════════ // CONNECTION MANAGEMENT // ═══════════════════════════════════════════════════════════════════ /// /// Ensures a connection is active, reconnecting with retry if necessary. /// protected async Task EnsureConnectedAsync(CancellationToken ct) { if (_remoteOps.IsConnected) return; var attempts = 0; while (true) { try { await _remoteOps.DisconnectAsync(ct).ConfigureAwait(false); await _remoteOps.ConnectAsync(ct).ConfigureAwait(false); return; } catch (Exception ex) when (++attempts <= Options.MaximumReconnectAttempts) { Logger?.LogWarning(ex, "{Consumer} reconnect to {Host}:{Port} failed, attempt {Attempt}/{Max}", ConsumerName, Options.Host, Options.Port, attempts, Options.MaximumReconnectAttempts); await Task.Delay(Options.ReconnectDelay, ct).ConfigureAwait(false); } } } /// /// Safely disconnects from the remote server. /// protected void DisconnectClient() { try { if (_remoteOps.IsConnected) _remoteOps.DisconnectAsync(CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { Logger?.LogDebug(ex, "{Consumer}: error during disconnect", ConsumerName); } } }