Bundle: redb-route / redb.Route.GenericFile (redb.Route.GenericFile.txt), 18 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.GenericFile/GenericFileConsumer.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/GenericFileConsumer.cs ---- using System.Diagnostics; using System.Reflection; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Telemetry; namespace redb.Route.GenericFile; /// /// Template-method base class for all file-based consumers (local file, SFTP, FTP). /// Owns the complete poll loop: enumerate → filter → sort → limit → per-file processing /// (min-age, done-file, idempotency, read-lock, pre-move, create exchange, post-process). /// Subclasses provide protocol-specific hooks via virtual/abstract methods. /// /// Concrete options type inheriting . public abstract class GenericFileConsumer : DrainableConsumer where TOptions : GenericFileEndpointOptions { private readonly IEndpoint _endpoint; private readonly InMemoryGenericFileIdempotentRepository? _idempotentRepo; private long _processedCount; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// Endpoint options. protected TOptions Options { get; } /// File operations (protocol-specific adapter). protected IFileOperations Operations { get; } /// Total number of files successfully processed. public long ProcessedCount => Interlocked.Read(ref _processedCount); /// The idempotent repository (null if idempotency is disabled). internal InMemoryGenericFileIdempotentRepository? IdempotentRepository => _idempotentRepo; /// Base path for file operations (directory for local, remote path for SFTP/FTP). protected abstract string BasePath { get; } /// Creates a generic file consumer. protected GenericFileConsumer(IEndpoint endpoint, IProcessor processor, TOptions options, IFileOperations operations) : base(processor) { ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(operations); _endpoint = endpoint; Options = options; Operations = operations; _idempotentRepo = options.Idempotent ? new InMemoryGenericFileIdempotentRepository() : null; _postProcessPathForm = CallsPathForm(GetType(), nameof(PostProcessAsync)); _failedPathForm = CallsPathForm(GetType(), nameof(OnProcessingFailedAsync)); } // A subclass written before 4.7.0 overrides the (filePath, fileName, basePath) form of a hook. When that form is // overridden below the type that overrides the (GenericFileInfo, workPath) form, the consumer calls it, as it // always did; otherwise it calls the file form, which knows the size and the time of the file. private readonly bool _postProcessPathForm; private readonly bool _failedPathForm; private static bool CallsPathForm(Type type, string hook) { const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; var pathForm = type.GetMethod(hook, flags, null, [typeof(string), typeof(string), typeof(string), typeof(CancellationToken)], null)!; var fileForm = type.GetMethod(hook, flags, null, [typeof(GenericFileInfo), typeof(string), typeof(CancellationToken)], null)!; return pathForm.DeclaringType!.IsSubclassOf(fileForm.DeclaringType!); } private Task PostProcessFileAsync(GenericFileInfo file, string workPath, CancellationToken ct) => _postProcessPathForm ? PostProcessAsync(workPath, file.Name, file.BasePath, ct) : PostProcessAsync(file, workPath, ct); private Task ProcessingFailedAsync(GenericFileInfo file, string workPath, CancellationToken ct) => _failedPathForm ? OnProcessingFailedAsync(workPath, file.Name, file.BasePath, ct) : OnProcessingFailedAsync(file, workPath, ct); // ═══════════════════════════════════════════════════════════════════ // POLL LOOP (RunAsync + PollDirectory) // ═══════════════════════════════════════════════════════════════════ /// protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { if (Options.InitialDelay > 0) { await Task.Delay(Options.InitialDelay, pollCt).ConfigureAwait(false); } var delay = TimeSpan.FromMilliseconds(Options.Delay); var backoff = new PollBackoff( Options.BackoffMultiplier, Options.BackoffIdleThreshold, Options.BackoffErrorThreshold); var wasSkipping = false; while (!pollCt.IsCancellationRequested) { // Backoff skip: wait one Delay WITHOUT polling — no BeforePollAsync, so a down server is not // reconnected on a skipped cycle. Stopping during a skip still resolves within Delay. if (backoff.ShouldSkip()) { wasSkipping = true; try { await Task.Delay(delay, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } continue; } if (wasSkipping) { Logger?.LogInformation("{Consumer}: resuming polling after backoff.", ConsumerName); wasSkipping = false; } PollOutcome outcome; try { var tally = await PollDirectory(processingCt).ConfigureAwait(false); outcome = PollBackoff.Classify(tally, Options.BackoffOnFailedExchanges); } catch (OperationCanceledException) when (pollCt.IsCancellationRequested || processingCt.IsCancellationRequested) { break; } catch (Exception ex) { Logger?.LogError(ex, "{Consumer} poll failed", ConsumerName); OnPollError(ex); outcome = PollOutcome.Error; } if (backoff.Record(outcome) is { } trigger) { Logger?.LogWarning( "{Consumer}: backing off after the {Reason} threshold — skipping the next {Skips} poll(s).", ConsumerName, trigger.ByError ? "error" : "idle", trigger.Skips); } try { await Task.Delay(delay, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } /// /// Polls the base directory for files, applies filters, and processes each file. /// This is the core template method — do not override. /// internal async Task PollDirectory(CancellationToken ct) { await BeforePollAsync(ct).ConfigureAwait(false); if (!await Operations.DirectoryExistsAsync(BasePath, ct).ConfigureAwait(false)) { await AfterPollAsync([], ct).ConfigureAwait(false); return default; } var files = await Operations.ListFilesAsync( BasePath, Options.Recursive, Options.MaxDepth, Options.MinDepth, DirectoryFilter(), ct).ConfigureAwait(false); var filtered = ApplyFilters(files); var sorted = ApplySort(filtered); var limited = ApplyMaxMessages(sorted); var fileList = limited.ToList(); if (fileList.Count == 0) { await OnNoFilesFoundAsync(ct).ConfigureAwait(false); await AfterPollAsync(fileList, ct).ConfigureAwait(false); return default; } // Tally created exchanges (files filtered by age / done-file / read-lock / idempotency contribute // nothing, so a poll that picks up only already-seen files still reads as idle) and how many of // those failed unhandled — the latter only matters when BackoffOnFailedExchanges is on. var created = 0; var failed = 0; foreach (var file in fileList) { ct.ThrowIfCancellationRequested(); var result = await ProcessFileAsync(file, ct).ConfigureAwait(false); if (result != FileProcessResult.Skipped) created++; if (result == FileProcessResult.Failed) failed++; } await AfterPollAsync(fileList, ct).ConfigureAwait(false); return new PollTally(created, failed); } // ── Per-file processing ───────────────────────────────────────── /// /// Processes one polled file. Returns once the file has been /// read and dispatched and the route left no unhandled failure, /// when it was dispatched but the route failed unhandled, and /// when no exchange was created (min/max age, missing done-file, lost read-lock, idempotent duplicate, /// or an unreadable file). The poll aggregates these into a for backoff. /// private async Task ProcessFileAsync(GenericFileInfo file, CancellationToken ct) { // Check minimum age if (Options.MinAge > 0) { var ageMs = (DateTimeOffset.UtcNow - file.LastModified).TotalMilliseconds; if (ageMs < Options.MinAge) return FileProcessResult.Skipped; } // Check maximum age (virtual — remote connectors override) if (!CheckMaxAge(file)) return FileProcessResult.Skipped; // Check done file if (!string.IsNullOrEmpty(Options.DoneFileName)) { var doneFilePath = GenericFileUtils.ResolveDoneFileName(file, Options.DoneFileName, Operations); if (!await Operations.ExistsAsync(doneFilePath, ct).ConfigureAwait(false)) return FileProcessResult.Skipped; } // Acquire read lock (virtual — local file only). // This runs BEFORE the idempotency claim: a consumer that loses the lock race must not // burn the idempotent key, otherwise the file is never picked up again by anyone. if (!await AcquireReadLockAsync(file, ct).ConfigureAwait(false)) return FileProcessResult.Skipped; var idempotentKey = ""; try { // Check idempotency if (_idempotentRepo != null) { idempotentKey = string.IsNullOrEmpty(Options.IdempotentKey) ? InMemoryGenericFileIdempotentRepository.DefaultKey(file) : GenericFileUtils.SubstituteFileTokens(new GenericFileFacts(file, ResolveWorkPath(file), Operations), Options.IdempotentKey); if (!await _idempotentRepo.Add(idempotentKey, ct).ConfigureAwait(false)) return FileProcessResult.Skipped; // Already processed } // PreMove var workPath = ResolveWorkPath(file); if (!string.IsNullOrEmpty(Options.PreMove)) { workPath = await PreMoveFileAsync(file, ct).ConfigureAwait(false); } // Create exchange with body and protocol-specific headers. // A file that cannot be read is a failure, not an empty message: releasing the // idempotent key and leaving the file in place lets the next poll retry it. Exchange exchange; try { exchange = await CreateExchangeAsync(file, workPath, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { Logger?.LogError(ex, "{Consumer}: cannot read {Path}, leaving the file in place", ConsumerName, workPath); if (_idempotentRepo != null) await _idempotentRepo.Remove(idempotentKey, ct).ConfigureAwait(false); await ProcessingFailedAsync(file, workPath, ct).ConfigureAwait(false); return FileProcessResult.Skipped; // no exchange created — a read failure counts as idle, not a poll error } exchange.Pattern = ExchangePattern.InOnly; // A file carries no trace context: its span is a root, never a child of the activity the poll runs under. using var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"file read {_endpoint.Component.Scheme}", ActivityKind.Consumer, "redb.system", _endpoint.Component.Scheme, _endpoint.Uri.NormalizedKey, null, static (_, _) => null, operation: "read"); IncrementInflight(); try { await Processor.Process(exchange, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; // our own stop — abort the poll, do not treat as a per-file failure } catch (Exception ex) { // An exception escaped the route (no matching OnException, or a handler that rethrew). // Record it on the exchange so the failure path below runs (idempotent-key release + // MoveFailed) and the poll loop continues to the next file — a single poison file must // not abort the whole batch and leave the files after it in the listing unprocessed. exchange.Exception ??= ex; } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } // A failed route marks the span; a rolled-back one (no exception) does not. if (exchange.Exception is { } failure && !exchange.ExceptionHandled) span.Activity.RecordFailure(failure); // A rollback-only exchange (.RollbackAll()) counts as failed too: its work was rolled back. if (exchange.EndedInFailure()) { // Processing failed — remove idempotent key so it can be retried if (_idempotentRepo != null) await _idempotentRepo.Remove(idempotentKey, ct).ConfigureAwait(false); // Move to failed directory (virtual hook — remote connectors) await ProcessingFailedAsync(file, workPath, ct).ConfigureAwait(false); return FileProcessResult.Failed; // exchange created but the route left an unhandled failure } // Post-processing await PostProcessFileAsync(file, workPath, ct).ConfigureAwait(false); // Confirm idempotent key if (_idempotentRepo != null) await _idempotentRepo.Confirm(idempotentKey, ct).ConfigureAwait(false); // Delete done file if present if (!string.IsNullOrEmpty(Options.DoneFileName)) { var donePath = GenericFileUtils.ResolveDoneFileName(file, Options.DoneFileName, Operations); try { await Operations.DeleteAsync(donePath, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: failed to delete done file {Path}", ConsumerName, donePath); } } Interlocked.Increment(ref _processedCount); return FileProcessResult.Processed; } catch when (_idempotentRepo != null && !string.IsNullOrEmpty(idempotentKey)) { await _idempotentRepo.Remove(idempotentKey, ct).ConfigureAwait(false); throw; } finally { await ReleaseReadLockAsync(file, ct).ConfigureAwait(false); } } // ═══════════════════════════════════════════════════════════════════ // SHARED LOGIC (non-virtual) // ═══════════════════════════════════════════════════════════════════ /// /// Applies Include/Exclude glob filters and excludes internal temp files. /// Override to add protocol-specific exclusions (e.g. lock files). /// protected virtual IEnumerable ApplyFilters(IEnumerable files) { // Exclude internal temp files files = files.Where(f => !f.Name.StartsWith(".redb_", StringComparison.OrdinalIgnoreCase)); // Exclude TempPrefix-prefixed files if (!string.IsNullOrEmpty(Options.TempPrefix)) { files = files.Where(f => !f.Name.StartsWith(Options.TempPrefix, StringComparison.OrdinalIgnoreCase)); } // Include filter (glob) if (!string.IsNullOrEmpty(Options.Include)) { files = files.Where(f => GenericFileUtils.GlobMatch(f.Name, Options.Include)); } // Exclude filter (glob) if (!string.IsNullOrEmpty(Options.Exclude)) { files = files.Where(f => !GenericFileUtils.GlobMatch(f.Name, Options.Exclude)); } // Path filters (Ant patterns over the path relative to the polled directory) — the name // globs above cannot see a directory, so this is what selects one out of a recursive poll. if (!string.IsNullOrEmpty(Options.AntInclude)) { files = files.Where(f => GenericFileUtils.AntMatch( RelativePathOf(f), Options.AntInclude, Options.AntFilterCaseSensitive)); } if (!string.IsNullOrEmpty(Options.AntExclude)) { files = files.Where(f => !GenericFileUtils.AntMatch( RelativePathOf(f), Options.AntExclude, Options.AntFilterCaseSensitive)); } // Condition over the file's own headers, and then the registry bean. Both run before the // file is read, moved or deleted: a file turned down here is left exactly as it was found. if (!string.IsNullOrEmpty(Options.FilterFile)) { var predicate = _fileFilter ??= Predicates.PredicateFactory.FromString(Options.FilterFile); files = files.Where(f => predicate.Matches(Probe(f, f.FullPath))); } if (Options.FilterInstance is { } bean) { files = files.Where(bean.Accept); } return files; } /// Path of a polled file relative to the directory it was enumerated from. private string RelativePathOf(GenericFileInfo file) => Operations.GetRelativePath(file.BasePath, file.FullPath); /// /// A headers-only exchange standing for a file or a directory, used to evaluate /// filterFile / filterDirectory. Nothing is read: the conditions see exactly the /// headers the route would see, which is why they are written the same way as any other /// condition in the DSL. /// private IExchange Probe(GenericFileInfo file, string path) { var message = new Message(); SetExchangeHeaders(message, file, path); return new Exchange(message); } /// /// Builds the directory predicate handed to the listing: the filterDirectory condition /// and the filter bean, or null when neither is configured and every subdirectory is walked. /// private Func? DirectoryFilter() { var condition = string.IsNullOrEmpty(Options.FilterDirectory) ? null : _directoryFilter ??= Predicates.PredicateFactory.FromString(Options.FilterDirectory); var bean = Options.FilterInstance; if (condition is null && bean is null) return null; return (fullPath, relativePath) => { if (bean is not null && !bean.AcceptDirectory(fullPath, relativePath)) return false; if (condition is null) return true; // The directory stands in for a file: name, path and parent are what a condition can // ask about; size and timestamp are not a directory's business and stay at zero. var asFile = new GenericFileInfo { Name = Operations.GetFileName(fullPath), FullPath = fullPath, BasePath = BasePath, Length = 0, LastModified = default }; return condition.Matches(Probe(asFile, fullPath)); }; } private IPredicate? _fileFilter; private IPredicate? _directoryFilter; private IEnumerable ApplySort(IEnumerable files) => Options.SortBy switch { GenericFileSortBy.Name => files.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase), GenericFileSortBy.NameDesc => files.OrderByDescending(f => f.Name, StringComparer.OrdinalIgnoreCase), GenericFileSortBy.Modified => files.OrderBy(f => f.LastModified), GenericFileSortBy.ModifiedDesc => files.OrderByDescending(f => f.LastModified), GenericFileSortBy.Size => files.OrderBy(f => f.Length), GenericFileSortBy.SizeDesc => files.OrderByDescending(f => f.Length), _ => files }; private IEnumerable ApplyMaxMessages(IEnumerable files) { if (Options.MaxMessagesPerPoll > 0) return files.Take(Options.MaxMessagesPerPoll); return files; } // ── Pre/Post processing ───────────────────────────────────────── /// /// Moves a file to the PreMove directory before processing. /// Returns the new path of the file. Override for protocol-specific behavior. /// protected virtual async Task PreMoveFileAsync(GenericFileInfo file, CancellationToken ct) { var preMoveDir = ResolveDirectory( GenericFileUtils.SubstituteFileTokens(new GenericFileFacts(file, ResolveWorkPath(file), Operations), Options.PreMove), file.BasePath); await Operations.CreateDirectoryAsync(preMoveDir, ct).ConfigureAwait(false); var sourcePath = ResolveWorkPath(file); var targetPath = Operations.CombinePath(preMoveDir, file.Name); // Delete existing file at target if present 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 existing file before pre-move {Path}", ConsumerName, targetPath); } } await Operations.MoveAsync(sourcePath, targetPath, true, ct).ConfigureAwait(false); return targetPath; } /// /// Applies the configured post-processing strategy (noop/delete/moveTo) to a processed file. The file keys in /// moveTo read at , all of /// included. /// /// The polled file. /// Where the file is now (after a pre-move or a read lock). /// Cancellation token. protected virtual Task PostProcessAsync(GenericFileInfo file, string workPath, CancellationToken ct) { ArgumentNullException.ThrowIfNull(file); return PostProcessCoreAsync(new GenericFileFacts(file, workPath, Operations), workPath, file.Name, file.BasePath, ct); } /// /// The compatibility form of . A subclass /// that overrides it keeps working: the consumer calls this form for it. Here the size and the time of the file /// are not known, so ${file:length} and ${file:modified} in moveTo write nothing; override /// the file form to have them. /// protected virtual Task PostProcessAsync(string filePath, string fileName, string basePath, CancellationToken ct) => PostProcessCoreAsync(new GenericFileFacts(fileName, filePath, basePath, Operations), filePath, fileName, basePath, ct); private async Task PostProcessCoreAsync(IFileFacts facts, string filePath, string fileName, string basePath, CancellationToken ct) { if (Options.Noop) return; if (Options.Delete) { try { await Operations.DeleteAsync(filePath, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: failed to delete processed file {Path}", ConsumerName, filePath); } return; } if (!string.IsNullOrEmpty(Options.MoveTo)) { var moveDir = ResolveDirectory( GenericFileUtils.SubstituteFileTokens(facts, Options.MoveTo), basePath); await Operations.CreateDirectoryAsync(moveDir, ct).ConfigureAwait(false); var targetPath = Operations.CombinePath(moveDir, fileName); // Handle existing file at target if (await Operations.ExistsAsync(targetPath, ct).ConfigureAwait(false)) { switch (Options.MoveExisting) { case GenericFileExistStrategy.Override: try { await Operations.DeleteAsync(targetPath, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: failed to delete target before move (Override) {Path}", ConsumerName, targetPath); } break; case GenericFileExistStrategy.Fail: throw new IOException($"Target file already exists: {targetPath}"); case GenericFileExistStrategy.Ignore: return; default: try { await Operations.DeleteAsync(targetPath, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "{Consumer}: failed to delete target before move (default) {Path}", ConsumerName, targetPath); } break; } } await Operations.MoveAsync(filePath, targetPath, false, ct).ConfigureAwait(false); } } // ── Exchange creation ─────────────────────────────────────────── /// /// Creates an exchange with the file body and protocol-specific headers. /// /// Original file info (for metadata). /// Current file path (may differ from file.FullPath after pre-move). /// Cancellation token. /// /// Read failures propagate. A file that cannot be read must not be delivered as an empty /// message: the caller treats the exception as a processing failure and leaves the file /// in place for the next poll. /// protected virtual async Task CreateExchangeAsync(GenericFileInfo file, string workPath, CancellationToken ct) { object body = Options.StreamBody ? await Operations.OpenReadAsync(workPath, ct).ConfigureAwait(false) : await Operations.ReadAllBytesAsync(workPath, ct).ConfigureAwait(false); var message = new Message { Body = body }; SetExchangeHeaders(message, file, workPath); return Exchange.Create(message, _endpoint.ScopeFactory); } /// /// Sets protocol-specific headers on the exchange message. /// Each connector sets headers with its own prefix (redbFile.*, redbSftp.*, redbFtp.*). /// /// Message to set headers on. /// Original file metadata (name, extension, base path, etc.). /// Current file location — may differ from file.FullPath after pre-move. protected abstract void SetExchangeHeaders(IMessage message, GenericFileInfo file, string workPath); // ═══════════════════════════════════════════════════════════════════ // VIRTUAL HOOKS (overridden by subclasses) // ═══════════════════════════════════════════════════════════════════ /// /// Called before each poll cycle. Override to connect to remote server, /// validate directory existence, etc. /// protected virtual Task BeforePollAsync(CancellationToken ct) => Task.CompletedTask; /// /// Called after each poll cycle with the list of files that were polled. /// Override to disconnect if configured, etc. /// protected virtual Task AfterPollAsync(List files, CancellationToken ct) => Task.CompletedTask; /// /// Called when a poll cycle finds no files. Override to send heartbeat exchanges. /// protected virtual Task OnNoFilesFoundAsync(CancellationToken ct) => Task.CompletedTask; /// /// Called when PollDirectory catches a non-cancellation exception. /// Override to disconnect from remote server after errors. /// protected virtual void OnPollError(Exception ex) { } /// /// Checks maximum file age. Returns true if the file should be processed. /// Override in remote connectors to implement MaxAge filtering. /// protected virtual bool CheckMaxAge(GenericFileInfo file) => true; /// /// Acquires a read lock on the file before processing. Returns true if lock was acquired. /// Override in local file consumer for read-lock strategies. /// protected virtual Task AcquireReadLockAsync(GenericFileInfo file, CancellationToken ct) => Task.FromResult(true); /// /// Path the file occupies once the read lock is held. Called after /// and before pre-move. /// Override where a read-lock strategy relocates the file (local file, rename strategy). /// protected virtual string ResolveWorkPath(GenericFileInfo file) => file.FullPath; /// /// Releases the read lock after processing. Override in local file consumer. /// protected virtual Task ReleaseReadLockAsync(GenericFileInfo file, CancellationToken ct) => Task.CompletedTask; /// /// Called when processing fails (exchange.Exception is set and not handled). Override in a connector to move the /// file to a failure directory; the file keys of that option read at /// . /// /// The polled file. /// Where the file is now (after a pre-move or a read lock). /// Cancellation token. protected virtual Task OnProcessingFailedAsync(GenericFileInfo file, string workPath, CancellationToken ct) => Task.CompletedTask; /// /// The compatibility form of . A /// subclass that overrides it keeps working: the consumer calls this form for it. Here the size and the time of /// the file are not known; override the file form to have them. /// protected virtual Task OnProcessingFailedAsync(string filePath, string fileName, string basePath, CancellationToken ct) => Task.CompletedTask; // ═══════════════════════════════════════════════════════════════════ // HELPERS // ═══════════════════════════════════════════════════════════════════ /// /// Resolves a directory path: if absolute, returns as-is; if relative, combines with basePath. /// protected string ResolveDirectory(string dir, string basePath) { if (Operations.IsAbsolutePath(dir)) return dir; return Operations.CombinePath(basePath, dir); } /// /// Resolves encoding from the option with UTF-8 fallback. /// protected Encoding ResolveEncoding() { try { return Encoding.GetEncoding(Options.Charset); } catch { return Encoding.UTF8; } } } Path: redb-route/redb.Route.GenericFile/GenericFileEndpointOptions.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/GenericFileEndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.GenericFile; /// /// Base endpoint options shared by all file-based transports (local file, SFTP, FTP). /// Provides consumer polling, post-processing, idempotency, done-file, and producer write options. /// public abstract class GenericFileEndpointOptions : EndpointOptions { // ═══════════════════════════════════════════════════════════════════ // CONSUMER: Polling // ═══════════════════════════════════════════════════════════════════ /// Polling delay in milliseconds between directory scans. (default: 500) public int Delay { get; set; } = 500; /// Initial delay before the first poll in milliseconds. (default: 0) public int InitialDelay { get; set; } /// Glob pattern to include files (e.g. "*.csv"). Multiple patterns: "*.csv,*.json". Empty = all files. public string Include { get; set; } = ""; /// Glob pattern to exclude files (e.g. "*.tmp,.*"). Empty = exclude nothing. public string Exclude { get; set; } = ""; /// /// Ant-style patterns over the path relative to the polled directory, several separated by /// commas: TYPE_A/outbox/*.csv,TYPE_B/outbox/*.csv. Unlike , which /// only ever sees a file name, this is how a recursive poll names the directories it wants. /// Empty = every path. Requires to reach anything below the top level. /// public string AntInclude { get; set; } = ""; /// /// Ant-style patterns over the relative path that drop a file: archive/**,**/*.tmp. /// Applied after . Empty = drop nothing. /// public string AntExclude { get; set; } = ""; /// /// Whether and respect case. (default: true, /// as in Apache Camel — a remote path is case-sensitive even when the local file system is not) /// public bool AntFilterCaseSensitive { get; set; } = true; /// /// Condition deciding whether a subdirectory is walked into, evaluated against the directory's /// own headers while the listing runs — a directory turned down here is never listed, which is /// what makes a poll over a partner tree of two hundred directories affordable. Empty = walk /// into every subdirectory. Only consulted when is on. /// public string FilterDirectory { get; set; } = ""; /// /// Condition deciding whether a polled file is taken, evaluated against the file's headers /// before anything reads or moves it (e.g. header.redbFile.Length > 1024). /// Empty = take every file the other filters left. /// public string FilterFile { get; set; } = ""; /// /// Name of an in the route registry (filter=#myFilter), /// for a decision that needs code rather than a condition string. Resolved by the component. /// [RegistryReference(typeof(IGenericFileFilter))] public string Filter { get; set; } = ""; /// /// The filter bean itself, put here by the component once it resolved from /// the registry. Set it directly when the route is built in code and has no registry entry. /// public IGenericFileFilter? FilterInstance { get; set; } /// Whether to recurse into subdirectories. (default: false) public bool Recursive { get; set; } /// Maximum recursion depth when Recursive=true. 0 = unlimited. (default: 0) public int MaxDepth { get; set; } /// Minimum recursion depth. Files at shallower levels are skipped. (default: 0) public int MinDepth { get; set; } /// Sort order for polled files. (default: None) public GenericFileSortBy SortBy { get; set; } = GenericFileSortBy.None; /// Maximum number of files to pick up per poll. 0 = unlimited. (default: 0) public int MaxMessagesPerPoll { get; set; } /// Minimum file age in milliseconds before the file is eligible for pickup. (default: 0) public long MinAge { get; set; } // ── Poll backoff (Apache Camel ScheduledPollConsumer parity) ── /// /// How many subsequent polls to skip once a backoff threshold is reached. 0 = backoff disabled (default). /// Requires at least one of / to be set. /// public int BackoffMultiplier { get; set; } /// /// Number of consecutive idle polls (a poll that created no exchange) that arms the backoff skip. /// 0 = idle backoff disabled (default). /// public int BackoffIdleThreshold { get; set; } /// /// Number of consecutive failed polls (the poll itself threw — e.g. the server is down) that arms the /// backoff skip. 0 = error backoff disabled (default). /// public int BackoffErrorThreshold { get; set; } /// /// Extension beyond Camel parity (default false): count a poll that created at least one exchange whose /// route all failed (unhandled) as an Error for . Lets a route /// back off polling when the downstream (e.g. the database) is down and every file fails, instead of /// re-reading the same files every . A poll with any successful exchange counts as /// success. Needs and to have effect. /// public bool BackoffOnFailedExchanges { get; set; } // ═══════════════════════════════════════════════════════════════════ // CONSUMER: Post-processing // ═══════════════════════════════════════════════════════════════════ /// If true, the file is not moved or deleted after processing (read-only mode). (default: false) public bool Noop { get; set; } /// If true, delete the file after successful processing. (default: false) public bool Delete { get; set; } /// Directory to move files to after successful processing. Supports the file keys of (${file:name}, ${file:ext}). public string MoveTo { get; set; } = ""; /// Strategy when the target file in MoveTo already exists. (default: Override) public GenericFileExistStrategy MoveExisting { get; set; } = GenericFileExistStrategy.Override; /// Directory to move files to BEFORE processing (pre-move for concurrency safety). public string PreMove { get; set; } = ""; // ═══════════════════════════════════════════════════════════════════ // CONSUMER: Idempotency // ═══════════════════════════════════════════════════════════════════ /// If true, skip files that have already been processed (tracked by idempotent key). (default: false) public bool Idempotent { get; set; } /// Expression for the idempotent key. Default uses path + last modified + size. public string IdempotentKey { get; set; } = ""; // ═══════════════════════════════════════════════════════════════════ // CONSUMER: Done file // ═══════════════════════════════════════════════════════════════════ /// /// Pattern for a "done" marker file. If set, the consumer waits for this marker before processing. /// Example: "${file:name}.done" — processes "order.csv" only when "order.csv.done" exists. /// public string DoneFileName { get; set; } = ""; // ═══════════════════════════════════════════════════════════════════ // CONSUMER: Body // ═══════════════════════════════════════════════════════════════════ /// /// If true, the consumer sets the exchange body to a Stream instead of reading /// the entire file into a byte array. The stream is closed by Exchange.DisposeAsync(). (default: false) /// public bool StreamBody { get; set; } // ═══════════════════════════════════════════════════════════════════ // PRODUCER: Write // ═══════════════════════════════════════════════════════════════════ /// Dynamic file name for the producer. Supports ${header.xxx} expressions. public DynamicValue? FileName { get; set; } /// Strategy when the target file already exists. (default: Override) public GenericFileExistStrategy FileExist { get; set; } = GenericFileExistStrategy.Override; /// Prefix for the temp file during write (e.g. ".redb_"). Empty = write directly. public string TempPrefix { get; set; } = ""; /// /// Full temp file name, in the target's directory. Overrides TempPrefix if set. The file keys read the target file /// (${file:name}.part, ${file:name.noext}.tmp), matching ignoring case as in the consumer options. /// public string TempFileName { get; set; } = ""; /// File encoding (default: "utf-8"). public string Charset { get; set; } = "utf-8"; /// If true, create the target directory if it doesn't exist. (default: true) public bool AutoCreate { get; set; } = true; /// If true, allow writing an empty file when body is null. (default: false) public bool AllowNullBody { get; set; } /// Characters to append after each Append write (e.g. "\n"). Empty = nothing. public string AppendChars { get; set; } = ""; /// If true, delete the target file before writing when using Override strategy. (default: true) public bool EagerDeleteTargetFile { get; set; } = true; // ═══════════════════════════════════════════════════════════════════ // VALIDATION (base — subclasses should call base.ValidateCommon()) // ═══════════════════════════════════════════════════════════════════ /// /// Validates common file endpoint options. Subclasses should call this from their Validate() method. /// protected void ValidateCommon() { if (Delay < 0) throw new ArgumentOutOfRangeException(nameof(Delay), Delay, "Delay cannot be negative."); if (InitialDelay < 0) throw new ArgumentOutOfRangeException(nameof(InitialDelay), InitialDelay, "InitialDelay cannot be negative."); if (MaxDepth < 0) throw new ArgumentOutOfRangeException(nameof(MaxDepth), MaxDepth, "MaxDepth cannot be negative."); if (MinDepth < 0) throw new ArgumentOutOfRangeException(nameof(MinDepth), MinDepth, "MinDepth cannot be negative."); if (MaxMessagesPerPoll < 0) throw new ArgumentOutOfRangeException(nameof(MaxMessagesPerPoll), MaxMessagesPerPoll, "MaxMessagesPerPoll cannot be negative."); if (MinAge < 0) throw new ArgumentOutOfRangeException(nameof(MinAge), MinAge, "MinAge cannot be negative."); if (Noop && Delete) throw new InvalidOperationException("Cannot set both Noop=true and Delete=true."); if (Noop && !string.IsNullOrEmpty(MoveTo)) throw new InvalidOperationException("Cannot set both Noop=true and MoveTo."); if (Delete && !string.IsNullOrEmpty(MoveTo)) throw new InvalidOperationException("Cannot set both Delete=true and MoveTo. Choose one post-processing strategy."); // The file keys of the consumer options, checked here so a wrong key fails when the endpoint is created. GenericFileUtils.ValidateFileKeys("moveTo", MoveTo); GenericFileUtils.ValidateFileKeys("preMove", PreMove); GenericFileUtils.ValidateFileKeys("doneFileName", DoneFileName); GenericFileUtils.ValidateFileKeys("idempotentKey", IdempotentKey); GenericFileUtils.ValidateFileKeys("tempFileName", TempFileName); if (BackoffMultiplier < 0) throw new ArgumentOutOfRangeException(nameof(BackoffMultiplier), BackoffMultiplier, "BackoffMultiplier cannot be negative."); if (BackoffIdleThreshold < 0) throw new ArgumentOutOfRangeException(nameof(BackoffIdleThreshold), BackoffIdleThreshold, "BackoffIdleThreshold cannot be negative."); if (BackoffErrorThreshold < 0) throw new ArgumentOutOfRangeException(nameof(BackoffErrorThreshold), BackoffErrorThreshold, "BackoffErrorThreshold cannot be negative."); // Camel refuses backoffMultiplier without a threshold; we also refuse a threshold without a // multiplier, since that configuration is ambiguous (a threshold that can never skip anything). var hasThreshold = BackoffIdleThreshold > 0 || BackoffErrorThreshold > 0; if (BackoffMultiplier > 0 && !hasThreshold) throw new InvalidOperationException( "BackoffMultiplier requires at least one of BackoffIdleThreshold / BackoffErrorThreshold to be set."); if (BackoffMultiplier == 0 && hasThreshold) throw new InvalidOperationException( "BackoffIdleThreshold / BackoffErrorThreshold require BackoffMultiplier to be set (> 0)."); } } Path: redb-route/redb.Route.GenericFile/GenericFileEnums.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/GenericFileEnums.cs ---- namespace redb.Route.GenericFile; /// /// Strategy for how the producer handles an existing file at the target path. /// Shared across all file-based transports (local, SFTP, FTP). /// public enum GenericFileExistStrategy { /// Overwrite the existing file. Override, /// Append to the existing file. Append, /// Throw an exception if the file exists. Fail, /// Do nothing — silently skip writing if the file exists. Ignore, /// Move the existing file to a backup before writing the new one. Move, /// Try to rename the existing file before writing. Fail silently if rename fails. TryRename } /// /// Sort criteria for ordering files during consumer polling. /// Shared across all file-based transports (local, SFTP, FTP). /// public enum GenericFileSortBy { /// No sorting — OS/server-native order. None, /// Sort by file name ascending (A → Z). Name, /// Sort by file name descending (Z → A). NameDesc, /// Sort by last modified time ascending (oldest first). Modified, /// Sort by last modified time descending (newest first). ModifiedDesc, /// Sort by file size ascending (smallest first). Size, /// Sort by file size descending (largest first). SizeDesc } Path: redb-route/redb.Route.GenericFile/GenericFileFacts.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/GenericFileFacts.cs ---- using redb.Route.Expressions; namespace redb.Route.GenericFile; /// /// The file facts of a file a consumer is handling, for the file keys in its own options (moveTo, /// preMove, moveFailed, doneFileName, idempotentKey). The values are the ones the file /// consumer writes into the redbFile.* headers, so ${file:ext} in moveTo and in a /// <log> of the same route agree. /// public sealed class GenericFileFacts : IFileFacts { private readonly IFileOperations _ops; private readonly string? _basePath; /// The facts of , which is now at . /// The polled file. /// Where the file is now: its own path, or where a pre-move or a read lock put it. /// The transport's path helpers. public GenericFileFacts(GenericFileInfo file, string workPath, IFileOperations ops) : this(file.Name, workPath, file.BasePath, ops) { Length = file.Length; LastModified = file.LastModified; } /// /// The facts known from a path alone, for the compatibility form of the consumer hooks: the size and the last /// write time are not known here and are null. /// public GenericFileFacts(string fileName, string workPath, string? basePath, IFileOperations ops) { ArgumentNullException.ThrowIfNull(fileName); ArgumentNullException.ThrowIfNull(ops); _ops = ops; _basePath = basePath; Name = fileName; AbsolutePath = workPath; } /// public string? Name { get; } /// public string? NameOnly => _ops.GetFileNameWithoutExtension(Name!); /// public string? Extension => FileLanguage.WithoutDot(_ops.GetExtension(Name!).ToLowerInvariant()); /// public string? Parent => string.IsNullOrEmpty(AbsolutePath) ? null : _ops.GetParentPath(AbsolutePath); /// public string? AbsolutePath { get; } /// public string? RelativePath => string.IsNullOrEmpty(AbsolutePath) || _basePath is null ? null : _ops.GetRelativePath(_basePath, AbsolutePath); /// public long? Length { get; } /// public DateTimeOffset? LastModified { get; } } Path: redb-route/redb.Route.GenericFile/GenericFileFilterResolution.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/GenericFileFilterResolution.cs ---- using redb.Route.Abstractions; using redb.Route.Extensions; namespace redb.Route.GenericFile; /// /// Turns filter=#myFilter into the filter instance the consumer calls. Shared by the /// file-based components so the reference is spelled and resolved the same way everywhere, and so /// an unknown name fails at endpoint creation instead of quietly polling everything. /// public static class GenericFileFilterResolution { /// /// Resolves from the route registry into /// . Does nothing when no name was given /// or when the instance was already supplied in code. /// /// Endpoint options carrying the reference. /// Route context owning the registry. public static void ResolveFilter(this GenericFileEndpointOptions options, IRouteContext? context) { ArgumentNullException.ThrowIfNull(options); if (string.IsNullOrEmpty(options.Filter) || options.FilterInstance is not null) return; // The leading '#' is Camel's spelling of "this is a registry name"; both forms are accepted // so a route ported from Camel keeps working, and a name that is not registered fails loud. var name = options.Filter.StartsWith('#') ? options.Filter[1..] : options.Filter; options.FilterInstance = context.GetRequiredFromRegistry(name); } } Path: redb-route/redb.Route.GenericFile/GenericFileInfo.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/GenericFileInfo.cs ---- namespace redb.Route.GenericFile; /// /// Protocol-agnostic file metadata. Used by consumers and producers /// to represent files from any source (local FS, SFTP, FTP). /// public sealed class GenericFileInfo { /// File name with extension (e.g. "report.csv"). public required string Name { get; init; } /// Full path: absolute path for local, remote path for SFTP/FTP. public required string FullPath { get; init; } /// Base polling directory from which this file was enumerated. public required string BasePath { get; init; } /// File size in bytes. public required long Length { get; init; } /// Last modified timestamp (UTC). public required DateTimeOffset LastModified { get; init; } /// Recursion depth: 0 = root dir, 1 = first subdirectory, etc. public int Depth { get; init; } /// /// Protocol-specific extras (e.g. SFTP UserId/GroupId, FTP permissions). /// Null if no extras are available. /// public Dictionary? Extras { get; init; } } Path: redb-route/redb.Route.GenericFile/GenericFileProducer.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/GenericFileProducer.cs ---- using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.GenericFile; /// /// Template-method base class for all file-based producers (local file, SFTP, FTP). /// Owns the complete write flow: resolve body → resolve path → handle existing file → /// write via temp → atomic rename → cleanup on failure. /// Subclasses provide protocol-specific hooks (connection, chmod, jail check). /// /// Concrete options type inheriting . public abstract class GenericFileProducer : IProducer where TOptions : GenericFileEndpointOptions { private ILogger? _logger; /// Endpoint this producer belongs to. protected IEndpoint ProducerEndpoint { get; } /// Endpoint options. protected TOptions Options { get; } /// File operations (protocol-specific adapter). protected IFileOperations Operations { get; } /// Logger resolved from the component. protected ILogger? Logger => _logger ??= (ProducerEndpoint.Component as ComponentBase)?.Logger; /// Base directory path for this producer. protected abstract string BasePath { get; } /// Header name for the produced file path (e.g. "redbFile.NameProduced"). protected abstract string FileNameProducedHeader { get; } /// Creates a generic file producer. protected GenericFileProducer(IEndpoint endpoint, TOptions options, IFileOperations operations) { ArgumentNullException.ThrowIfNull(endpoint); ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(operations); ProducerEndpoint = endpoint; Options = options; Operations = operations; } // ═══════════════════════════════════════════════════════════════════ // PROCESS (template method) // ═══════════════════════════════════════════════════════════════════ /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = ResolveBody(exchange); var targetPath = ResolveTargetPath(exchange); var targetDir = Operations.GetParentPath(targetPath); using var activity = RouteTelemetryExtensions.StartTransportSpan( (ProducerEndpoint.Component as ComponentBase)?.Context, $"file write {ProducerEndpoint.Component.Scheme}", ActivityKind.Producer, "redb.system", ProducerEndpoint.Component.Scheme, ProducerEndpoint.Uri.NormalizedKey, destination: targetPath, operation: "write"); try { await WriteAsync(exchange, body, targetPath, targetDir, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only our own token cancelling the write is a stop; any other failure marks the span. activity.RecordFailure(ex); throw; } } private async Task WriteAsync(IExchange exchange, object? body, string targetPath, string targetDir, CancellationToken ct) { // Validate path (virtual — jail check for remote) ValidatePath(targetPath); // Before-write hook (connect if remote, auto-create directory) await BeforeWriteAsync(targetDir, ct).ConfigureAwait(false); // Determine the path to write to (may be temp file) var writePath = ResolveTempPath(targetPath); var isTemp = !string.Equals(writePath, targetPath, StringComparison.Ordinal); try { // Handle existing file if (await Operations.ExistsAsync(targetPath, ct).ConfigureAwait(false)) { switch (Options.FileExist) { case GenericFileExistStrategy.Fail: throw new IOException( $"File already exists and FileExist=Fail: {targetPath}"); case GenericFileExistStrategy.Ignore: exchange.In.Headers[FileNameProducedHeader] = targetPath; await OnWriteCompletedAsync(exchange, targetPath, ct).ConfigureAwait(false); return; case GenericFileExistStrategy.Append: await AppendToFile(targetPath, body, ct).ConfigureAwait(false); exchange.In.Headers[FileNameProducedHeader] = targetPath; await OnWriteCompletedAsync(exchange, targetPath, ct).ConfigureAwait(false); return; case GenericFileExistStrategy.Move: await MoveExistingFile(targetPath, ct).ConfigureAwait(false); break; case GenericFileExistStrategy.TryRename: var renamePath = targetPath + "." + DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmssfff"); try { await Operations.MoveAsync(targetPath, renamePath, false, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "TryRename failed for {Path}", targetPath); } break; case GenericFileExistStrategy.Override: default: if (Options.EagerDeleteTargetFile) { try { await Operations.DeleteAsync(targetPath, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "EagerDelete failed for {Path}", targetPath); } } break; } } // Write the file await WriteBody(writePath, body, ct).ConfigureAwait(false); // Atomic rename from temp to target if (isTemp) { // Delete target if it appeared during write if (await Operations.ExistsAsync(targetPath, ct).ConfigureAwait(false)) { try { await Operations.DeleteAsync(targetPath, ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "Failed to delete target before rename {Path}", targetPath); } } await Operations.MoveAsync(writePath, targetPath, true, ct).ConfigureAwait(false); } exchange.In.Headers[FileNameProducedHeader] = targetPath; // After-write hook (chmod, keepLastModified, etc.) await AfterWriteAsync(exchange, targetPath, ct).ConfigureAwait(false); // Completion hook (disconnect if configured, etc.) await OnWriteCompletedAsync(exchange, targetPath, ct).ConfigureAwait(false); } catch { // Clean up temp file on failure if (isTemp) { try { if (await Operations.ExistsAsync(writePath, ct).ConfigureAwait(false)) await Operations.DeleteAsync(writePath, ct).ConfigureAwait(false); } catch (Exception cleanupEx) { Logger?.LogDebug(cleanupEx, "Failed to clean up temp file {Path}", writePath); } } throw; } } // ═══════════════════════════════════════════════════════════════════ // LIFECYCLE // ═══════════════════════════════════════════════════════════════════ /// public virtual Task Start(CancellationToken ct = default) { _logger ??= (ProducerEndpoint.Component as ComponentBase)?.Logger; Logger?.LogInformation("{Producer} started", EndpointUri.ForLog(ProducerEndpoint.Uri.NormalizedKey, Logger)); return Task.CompletedTask; } /// public virtual Task Stop(CancellationToken ct = default) { Logger?.LogInformation("{Producer} stopped", EndpointUri.ForLog(ProducerEndpoint.Uri.NormalizedKey, Logger)); return Task.CompletedTask; } // ═══════════════════════════════════════════════════════════════════ // SHARED LOGIC // ═══════════════════════════════════════════════════════════════════ /// Extracts the body from the exchange (Out preferred, falls back to In). protected object? ResolveBody(IExchange exchange) { var body = exchange.HasOut ? exchange.Out!.Body : exchange.In.Body; if (body == null && !Options.AllowNullBody) { throw new InvalidOperationException( "Exchange body is null and AllowNullBody=false. Set AllowNullBody=true to write empty files."); } return body; } /// Resolves the target file path from the FileName option or exchange headers. protected virtual string ResolveTargetPath(IExchange exchange) { string fileName; if (Options.FileName != null) { fileName = Options.FileName.Value.Resolve(exchange) ?? "output"; } else { // Try to get filename from incoming exchange headers var headerFileName = exchange.In.Headers.TryGetValue(FileNameProducedHeader.Replace("Produced", ""), out var hfn) ? hfn?.ToString() : null; fileName = headerFileName ?? $"redb-{Guid.NewGuid():N}"; } return Operations.CombinePath(BasePath, fileName); } /// /// Computes the temp file path if TempPrefix or TempFileName is configured. The file keys in TempFileName /// (${file:name}.part) read the target file, the one being written; its size and time are not known yet and /// write nothing. /// protected string ResolveTempPath(string targetPath) { if (!string.IsNullOrEmpty(Options.TempFileName)) { var dir = Operations.GetParentPath(targetPath); var target = new GenericFileFacts(Operations.GetFileName(targetPath), targetPath, BasePath, Operations); return Operations.CombinePath(dir, GenericFileUtils.SubstituteFileTokens(target, Options.TempFileName)); } if (!string.IsNullOrEmpty(Options.TempPrefix)) { var dir = Operations.GetParentPath(targetPath); var name = Operations.GetFileName(targetPath); return Operations.CombinePath(dir, Options.TempPrefix + name); } return targetPath; } /// Writes the body to the given path. protected async Task WriteBody(string path, object? body, CancellationToken ct) { if (body == null) { await Operations.WriteAsync(path, Array.Empty(), ct).ConfigureAwait(false); } else if (body is byte[] bytes) { await Operations.WriteAsync(path, bytes, ct).ConfigureAwait(false); } else if (body is Stream stream) { await Operations.WriteAsync(path, stream, ct).ConfigureAwait(false); } else { var text = BodyText.Of(body); var encoding = ResolveEncoding(); var textBytes = encoding.GetBytes(text); await Operations.WriteAsync(path, textBytes, ct).ConfigureAwait(false); } } /// Appends the body to the given path. protected async Task AppendToFile(string path, object? body, CancellationToken ct) { var encoding = ResolveEncoding(); if (body is byte[] bytes) { await Operations.AppendAsync(path, bytes, ct).ConfigureAwait(false); } else if (body is Stream stream) { using var ms = new MemoryStream(); await stream.CopyToAsync(ms, ct).ConfigureAwait(false); await Operations.AppendAsync(path, ms.ToArray(), ct).ConfigureAwait(false); } else { var text = body is null ? "" : BodyText.Of(body); await Operations.AppendTextAsync(path, text, encoding, ct).ConfigureAwait(false); } if (!string.IsNullOrEmpty(Options.AppendChars)) { await Operations.AppendTextAsync(path, Options.AppendChars, encoding, ct).ConfigureAwait(false); } } /// Moves an existing file at the target path to a backup name. protected virtual async Task MoveExistingFile(string path, CancellationToken ct) { var backupPath = path + ".bak"; await Operations.MoveAsync(path, backupPath, true, ct).ConfigureAwait(false); } /// Resolves encoding from the Charset option with UTF-8 fallback. protected Encoding ResolveEncoding() { try { return Encoding.GetEncoding(Options.Charset); } catch { return Encoding.UTF8; } } // ═══════════════════════════════════════════════════════════════════ // VIRTUAL HOOKS // ═══════════════════════════════════════════════════════════════════ /// /// Validates the target path before writing. Override for jail-directory checks. /// protected virtual void ValidatePath(string targetPath) { } /// /// Called before writing. Override to connect to remote server, auto-create directory with chmod, etc. /// Default implementation auto-creates the target directory if configured. /// protected virtual async Task BeforeWriteAsync(string targetDir, CancellationToken ct) { if (Options.AutoCreate) { await Operations.CreateDirectoryAsync(targetDir, ct).ConfigureAwait(false); } } /// /// Called after a successful write. Override for chmod, keepLastModified, content-type inference. /// protected virtual Task AfterWriteAsync(IExchange exchange, string targetPath, CancellationToken ct) => Task.CompletedTask; /// /// Called after write or early return (Ignore, Append). Override to disconnect if configured. /// protected virtual Task OnWriteCompletedAsync(IExchange exchange, string targetPath, CancellationToken ct) => Task.CompletedTask; } Path: redb-route/redb.Route.GenericFile/GenericFileUtils.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/GenericFileUtils.cs ---- using redb.Route.Expressions; using System.Text.RegularExpressions; namespace redb.Route.GenericFile; /// /// Shared utilities for file-based transports: glob matching, done-file resolution. /// public static class GenericFileUtils { /// /// Ant-style path matching, as Apache Camel's antInclude/antExclude use it: /// ? is one character, * matches within a single path segment and stops at a /// separator, and ** spans any number of segments. Several patterns are separated by /// commas, and the path is matched with / as the separator whatever the transport wrote. /// /// This is deliberately not with a longer input: there * becomes /// .* and crosses separators, so */x.csv and **/x.csv would mean the same /// thing and a pattern could never name one level. /// /// /// Path relative to the polled directory (e.g. "TYPE_A/outbox/a.csv"). /// One or more comma-separated Ant patterns. /// Whether matching respects case (Camel's antFilterCaseSensitive, default true). /// True when any pattern matches the path. public static bool AntMatch(string relativePath, string pattern, bool caseSensitive = true) { ArgumentNullException.ThrowIfNull(relativePath); ArgumentNullException.ThrowIfNull(pattern); var path = relativePath.Replace('\\', '/').TrimStart('/'); foreach (var single in pattern.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { var regex = AntPatternCache.GetOrAdd((single, caseSensitive), static key => BuildAntRegex(key.Pattern, key.CaseSensitive)); if (regex.IsMatch(path)) return true; } return false; } // One compiled Regex per (pattern, case) pair: a poll runs the same handful of patterns over // every file it listed, and a directory filter runs them again per directory. private static readonly System.Collections.Concurrent.ConcurrentDictionary<(string Pattern, bool CaseSensitive), Regex> AntPatternCache = new(); private static Regex BuildAntRegex(string pattern, bool caseSensitive) { var normalized = pattern.Replace('\\', '/').TrimStart('/'); var sb = new System.Text.StringBuilder("^"); for (var i = 0; i < normalized.Length; i++) { var c = normalized[i]; if (c == '*') { var isDouble = i + 1 < normalized.Length && normalized[i + 1] == '*'; if (isDouble) { i++; // "**/" also matches zero segments, so "**/x.csv" matches "x.csv" at the root. if (i + 1 < normalized.Length && normalized[i + 1] == '/') { i++; sb.Append("(?:.*/)?"); } else { sb.Append(".*"); } } else { sb.Append("[^/]*"); } } else if (c == '?') { sb.Append("[^/]"); } else { sb.Append(Regex.Escape(c.ToString())); } } sb.Append('$'); var options = RegexOptions.Compiled | (caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); return new Regex(sb.ToString(), options); } /// /// Simple glob matching supporting * and ? wildcards. /// Supports comma-separated patterns: "*.csv,*.json". /// /// File name to test. /// Glob pattern (e.g. "*.csv" or "*.csv,*.json"). /// True if the input matches the pattern. public static bool GlobMatch(string input, string pattern) { ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(pattern); // Support comma-separated patterns: "*.csv,*.json" if (pattern.Contains(',')) { return pattern.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Any(p => GlobMatch(input, p)); } var regexPattern = "^" + Regex.Escape(pattern) .Replace("\\*", ".*") .Replace("\\?", ".") + "$"; return Regex.IsMatch(input, regexPattern, RegexOptions.IgnoreCase); } /// /// Tests whether a already-normalized path is the base directory itself or lives underneath it. /// Used by producers to keep a caller-supplied file name from escaping the endpoint directory. /// /// Base directory. A trailing separator is ignored. /// Candidate path. Must already be normalized (no "..", no "." segments). /// Path separator of the transport ('/' for remote, OS separator for local). /// Comparison to use. Remote paths are case-sensitive; local ones follow the OS. /// True when the candidate stays inside the base directory. /// /// The separator is part of the comparison on purpose: a plain prefix test would accept /// "/data/out2/x" as living inside "/data/out". /// public static bool IsWithinDirectory( string basePath, string candidatePath, char separator, StringComparison comparison) { ArgumentNullException.ThrowIfNull(basePath); ArgumentNullException.ThrowIfNull(candidatePath); var root = basePath.TrimEnd(separator); if (root.Length == 0) return true; // the whole file system is the base return candidatePath.Equals(root, comparison) || candidatePath.StartsWith(root + separator, comparison); } /// /// Substitutes the file keys of Apache Camel's file language (${file:name}, ${file:name.noext}, /// ${file:ext}, ${file:parent} and the rest of ) in a pattern of a /// consumer option. Keys match ignoring case, as these options always have (${FILE:NAME}). /// /// The file the option is resolved for (). /// Pattern to substitute into. Returned unchanged when it holds no keys. /// The pattern with the file keys replaced. /// /// Only file keys are substituted. Exchange-level expressions (${header.*}, ${body}) cannot be used /// here: these patterns are resolved before the exchange exists, or while it is being disposed. /// /// A key is not a file key; reports it earlier. public static string SubstituteFileTokens(IFileFacts facts, string pattern) { ArgumentNullException.ThrowIfNull(facts); ArgumentNullException.ThrowIfNull(pattern); return FileLanguage.Substitute(pattern, facts, StringComparison.OrdinalIgnoreCase); } /// /// The compatibility form of for a caller that has only the /// file name: the keys that need the path, the size or the time write nothing. /// /// File name with extension (e.g. "order.csv"). /// Pattern to substitute into. Returned unchanged when it holds no keys. /// File operations for path helpers. /// The pattern with the file keys replaced. public static string SubstituteFileTokens(string fileName, string pattern, IFileOperations ops) { ArgumentNullException.ThrowIfNull(fileName); ArgumentNullException.ThrowIfNull(pattern); ArgumentNullException.ThrowIfNull(ops); return SubstituteFileTokens(new GenericFileFacts(fileName, "", null, ops), pattern); } /// /// Checks the file keys in a consumer option when the endpoint is created: a key that is not a file key would /// otherwise surface only when the first file arrives (before 4.7.0 it was left in the path as written). /// /// The option name, for the message (moveTo). /// The option value; empty or null passes. /// A key is not a file key; the message lists the keys. public static void ValidateFileKeys(string option, string? pattern) { if (string.IsNullOrEmpty(pattern)) return; if (FileLanguage.FindUnknownKey(pattern, StringComparison.OrdinalIgnoreCase) is { } key) throw new InvalidOperationException($"{option}='{pattern}': {FileLanguage.UnknownKeyMessage(key)}"); } /// /// Resolves a done-file name pattern by substituting the file keys (${file:name}, ${file:name.noext} /// and the rest of ). /// /// The file to resolve the done-file name for. /// The pattern (e.g. "${file:name}.done"). /// File operations for path helpers. /// Resolved done-file path. public static string ResolveDoneFileName(GenericFileInfo file, string doneFilePattern, IFileOperations ops) { ArgumentNullException.ThrowIfNull(file); ArgumentNullException.ThrowIfNull(doneFilePattern); ArgumentNullException.ThrowIfNull(ops); var pattern = SubstituteFileTokens(new GenericFileFacts(file, file.FullPath, ops), doneFilePattern); if (ops.IsAbsolutePath(pattern)) return pattern; var parentDir = ops.GetParentPath(file.FullPath); return ops.CombinePath(parentDir, pattern); } } Path: redb-route/redb.Route.GenericFile/IFileOperations.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/IFileOperations.cs ---- namespace redb.Route.GenericFile; /// /// Abstraction for file system operations. Implementations adapt /// concrete I/O APIs (System.IO, SSH.NET, FluentFTP) to a uniform interface. /// All path operations are protocol-aware (forward-slash for remote, OS-native for local). /// public interface IFileOperations { // ── Enumeration ───────────────────────────────────────────────── /// /// Lists files in the given directory. /// /// Base directory path. /// Whether to recurse into subdirectories. /// Maximum recursion depth (0 = unlimited). /// Minimum depth — files at shallower levels are skipped. /// /// Asked before walking into a subdirectory, with its full path and its path relative to /// ; false skips that subdirectory and everything below it /// without listing it. Null = walk into every subdirectory. The decision belongs here rather /// than in the consumer because skipping the listing is the entire saving. /// /// Cancellation token. /// List of file metadata. Task> ListFilesAsync( string directory, bool recursive, int maxDepth, int minDepth, Func? directoryFilter = null, CancellationToken ct = default); // ── Read ──────────────────────────────────────────────────────── /// Reads the entire file into a byte array. Task ReadAllBytesAsync(string path, CancellationToken ct = default); /// Opens a read stream to the file. Caller is responsible for disposing. Task OpenReadAsync(string path, CancellationToken ct = default); // ── Write ─────────────────────────────────────────────────────── /// Writes data to a file, creating or overwriting it. Task WriteAsync(string path, byte[] data, CancellationToken ct = default); /// Writes a stream to a file, creating or overwriting it. Task WriteAsync(string path, Stream data, CancellationToken ct = default); /// Appends data to an existing file. Task AppendAsync(string path, byte[] data, CancellationToken ct = default); /// Appends text to an existing file. Task AppendTextAsync(string path, string text, System.Text.Encoding encoding, CancellationToken ct = default); // ── File operations ───────────────────────────────────────────── /// Checks whether a file or directory exists. Task ExistsAsync(string path, CancellationToken ct = default); /// Deletes a file. Task DeleteAsync(string path, CancellationToken ct = default); /// Moves (renames) a file from source to destination. Task MoveAsync(string source, string destination, bool overwrite, CancellationToken ct = default); // ── Directory operations ──────────────────────────────────────── /// Creates a directory (and all parent directories if missing). Task CreateDirectoryAsync(string path, CancellationToken ct = default); /// Checks whether a directory exists. Task DirectoryExistsAsync(string path, CancellationToken ct = default); // ── Path helpers ──────────────────────────────────────────────── /// Combines a base path and a relative path using the appropriate separator. string CombinePath(string basePath, string relativePath); /// Returns the parent directory of the given path. string GetParentPath(string path); /// Returns the file name from a path. string GetFileName(string path); /// Returns the file name without extension. string GetFileNameWithoutExtension(string name); /// Returns the extension including the dot (e.g. ".csv"). string GetExtension(string name); /// Returns the relative path from basePath to fullPath. string GetRelativePath(string basePath, string fullPath); /// Checks whether the given path is absolute. bool IsAbsolutePath(string path); } /// /// Extension of for remote file systems (SFTP, FTP). /// Adds connection lifecycle management. /// public interface IRemoteFileOperations : IFileOperations { /// Whether a connection is currently established. bool IsConnected { get; } /// Establishes a connection to the remote server. Task ConnectAsync(CancellationToken ct = default); /// Disconnects from the remote server. Task DisconnectAsync(CancellationToken ct = default); } Path: redb-route/redb.Route.GenericFile/IGenericFileFilter.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/IGenericFileFilter.cs ---- namespace redb.Route.GenericFile; /// /// A filter the route author writes in code and names from the URI (filter=#myFilter), /// resolved from the route registry — Apache Camel's GenericFileFilter. Use it when the /// decision needs code: a lookup, a partner table, a calendar. For a condition that fits in a /// string, filterFile and filterDirectory are simpler, and for a path pattern /// antInclude/antExclude are simpler still. /// public interface IGenericFileFilter { /// /// Decides whether a polled file is taken. Called after the cheap filters (name patterns, path /// patterns) and before anything reads or moves the file. /// /// The file as the listing found it. /// true to poll the file, false to leave it untouched. bool Accept(GenericFileInfo file); /// /// Decides whether a subdirectory is walked into at all, while the listing is still running — /// so a directory turned down here costs nothing, not even a listing. The default takes every /// directory, which is what a filter that only cares about files wants. /// /// Full path of the subdirectory. /// Its path relative to the directory the endpoint polls. /// true to walk into it, false to skip it and everything below. bool AcceptDirectory(string fullPath, string relativePath) => true; } Path: redb-route/redb.Route.GenericFile/InMemoryGenericFileIdempotentRepository.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/InMemoryGenericFileIdempotentRepository.cs ---- using redb.Route.Abstractions; namespace redb.Route.GenericFile; /// /// In-memory idempotent repository for tracking processed files across all file-based transports. /// Tracks files by a composite key (path + last modified + size) to detect re-processing. /// Thread-safe via HashSet + lock. /// public sealed class InMemoryGenericFileIdempotentRepository : IIdempotentRepository { // Ordinal, not OrdinalIgnoreCase: the key embeds the file path, and every SFTP/FTP server // and every non-Windows file system is case-sensitive. Folding case there makes two real // files share one key, and the second one is skipped as a duplicate that it never was. private readonly HashSet _keys = new(StringComparer.Ordinal); private readonly object _lock = new(); /// Current number of tracked keys. public int Count { get { lock (_lock) return _keys.Count; } } /// public Task Add(string key, CancellationToken ct = default) { lock (_lock) { return Task.FromResult(_keys.Add(key)); } } /// public Task Confirm(string key, CancellationToken ct = default) => Task.CompletedTask; /// public Task Remove(string key, CancellationToken ct = default) { lock (_lock) { _keys.Remove(key); } return Task.CompletedTask; } /// public Task Contains(string key, CancellationToken ct = default) { lock (_lock) { return Task.FromResult(_keys.Contains(key)); } } /// public Task Clear(CancellationToken ct = default) { lock (_lock) { _keys.Clear(); } return Task.CompletedTask; } /// /// Generates the default idempotent key for a file. /// Format: "{fullPath}|{lastModifiedUtc:O}|{length}" /// public static string DefaultKey(GenericFileInfo file) { ArgumentNullException.ThrowIfNull(file); return $"{file.FullPath}|{file.LastModified:O}|{file.Length}"; } } Path: redb-route/redb.Route.GenericFile/PollBackoff.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/PollBackoff.cs ---- namespace redb.Route.GenericFile; /// Outcome of a single poll, feeding the backoff counters. public enum PollOutcome { /// The poll itself threw (e.g. the server is unreachable, no directory permission). Error, /// The poll completed but created no exchange (empty directory, or every file was filtered out). Idle, /// The poll created at least one exchange. Success } /// Result of processing a single polled file, aggregated into the poll tally. public enum FileProcessResult { /// No exchange was created (age / done-file / read-lock / idempotent duplicate / unreadable). Skipped, /// An exchange was created and the route completed without an unhandled failure. Processed, /// An exchange was created but the route left an unhandled failure on it. Failed } /// Per-poll tally: how many exchanges were created and how many of those failed unhandled. public readonly record struct PollTally(int Created, int Failed); /// Set when a poll's outcome has just armed the skip countdown — for a single log line. public readonly record struct BackoffTrigger(bool ByError, int Skips); /// /// Apache Camel ScheduledPollConsumer-style poll backoff: after a threshold number of consecutive /// idle or error polls, skip the next multiplier polls, then reset and resume. Pure and timer-free — /// the caller drives the loop and applies the delay. /// /// Counters follow Camel: an error poll increments the error count and clears idle; an idle poll increments /// idle; a successful poll clears both. When a configured threshold is met the countdown is armed to /// multiplier; the countdown is consumed one skip at a time and resets the counters on its last unit. /// /// public sealed class PollBackoff { private readonly int _multiplier; private readonly int _idleThreshold; private readonly int _errorThreshold; private int _idle; private int _error; private int _countdown; /// Creates a backoff with the given multiplier and idle/error thresholds (0 = that part disabled). public PollBackoff(int multiplier, int idleThreshold, int errorThreshold) { _multiplier = multiplier; _idleThreshold = idleThreshold; _errorThreshold = errorThreshold; } /// True when a multiplier and at least one threshold are configured (otherwise a no-op). public bool Enabled => _multiplier > 0 && (_idleThreshold > 0 || _errorThreshold > 0); /// /// Classifies a completed (non-throwing) poll from its tally. No exchange → . /// When is set and every created exchange failed unhandled → /// (the Camel-superset behaviour); otherwise → . /// A poll whose own call threw is classified by the caller, not here. /// public static PollOutcome Classify(PollTally tally, bool backoffOnFailedExchanges) { if (tally.Created == 0) return PollOutcome.Idle; if (backoffOnFailedExchanges && tally.Failed == tally.Created) return PollOutcome.Error; return PollOutcome.Success; } /// /// Called before each cycle. Returns true when this cycle must be skipped (no poll). Consumes one unit /// of the armed countdown; on the last skip it resets the counters so polling resumes on the next cycle. /// public bool ShouldSkip() { if (_countdown <= 0) return false; _countdown--; if (_countdown == 0) { _idle = 0; _error = 0; } return true; } /// /// Records the outcome of an actual poll. Returns a when this outcome just /// armed the skip countdown (so the caller can log one line), otherwise null. /// public BackoffTrigger? Record(PollOutcome outcome) { if (!Enabled) return null; switch (outcome) { case PollOutcome.Error: _error++; _idle = 0; break; case PollOutcome.Idle: _idle++; break; case PollOutcome.Success: _idle = 0; _error = 0; break; } var errorHit = _errorThreshold > 0 && _error >= _errorThreshold; var idleHit = _idleThreshold > 0 && _idle >= _idleThreshold; if (errorHit || idleHit) { _countdown = _multiplier; return new BackoffTrigger(errorHit, _multiplier); } return null; } } Path: redb-route/redb.Route.GenericFile/README.md 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/README.md ---- # redb.Route.GenericFile > Documentation and articles: Shared base library for file-based transports in the [redb.Route](../README.md) ESB framework. Provides abstract consumer, producer, options, and file-operations interfaces that concrete transports (**File**, **FTP**, **SFTP**) inherit from. Not used directly — include one of the transport-specific packages instead. [![NuGet](https://img.shields.io/nuget/v/redb.Route.GenericFile?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.GenericFile) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Architecture ``` GenericFileEndpointOptions ← base options (polling, filtering, producer write) └─ RemoteFileEndpointOptions ← + host/port/auth/reconnect GenericFileConsumer ← template-method poll loop └─ RemoteFileConsumer ← + connect/reconnect lifecycle GenericFileProducer ← template-method write flow └─ RemoteFileProducer ← + connect/reconnect lifecycle IFileOperations ← protocol abstraction (list, read, write, move, delete) └─ IRemoteFileOperations ← + connect/disconnect ``` Transport implementations (`File`, `Ftp`, `Sftp`) provide concrete `IFileOperations` and transport-specific headers/DSL. All polling logic, filtering, idempotency, post-processing, atomic write, and file-exist strategies are implemented in this base library. ## Consumer Pipeline The `GenericFileConsumer` runs a poll loop with the following steps: 1. **List files** in the base directory (optionally recursive) 2. **Filter** — exclude temp/internal files (`.redb_*`, temp prefix), apply glob `include`/`exclude` patterns 3. **Sort** — by name, date, or size (ascending or descending) 4. **Limit** — apply `maxMessagesPerPoll` 5. **Eligibility checks** — `minAge`, `maxAge`, done-file presence 6. **Read lock** — transport-specific claim on the file (local file only) 7. **Idempotency** — skip files already in the repository 8. **Pre-move** — optionally move to a staging directory before processing 9. **Read body** — as `byte[]` (default) or `Stream` (`streamBody=true`) 10. **Invoke processor** — pass exchange to the downstream pipeline 11. **Post-process** — `Noop` (leave in place) / `Delete` / `MoveTo` 12. **Confirm** — mark idempotent key, delete done file The read lock is taken **before** the idempotency claim: a consumer that loses the lock race must not consume the idempotent key, or the file would never be picked up again by anyone. On processing failure: remove idempotent key, leave the file in place, move to `moveFailed` directory (if configured). A file that cannot be **read** is treated the same way — it is never delivered as an empty message. ## Producer Pipeline The `GenericFileProducer` writes files with atomic temp-then-rename: 1. **Resolve body** — from `exchange.Out` (if set) or `exchange.In` 2. **Resolve target path** — from `FileName` option / header / auto-generated GUID 3. **Validate path** — jail-directory check (transport-specific) 4. **Create directories** — if `autoCreate=true` 5. **Write to temp file** — using `tempPrefix` or `tempFileName` 6. **Handle existing** — apply `fileExist` strategy (Override / Append / Fail / Ignore / Move / TryRename) 7. **Atomic rename** — move temp file to target 8. **Cleanup** — delete temp file on failure ## Options Reference ### GenericFileEndpointOptions (Base) #### Consumer / Polling | Property | Type | Default | Description | |----------|------|---------|-------------| | `Delay` | `int` | `500` | Poll interval (ms) | | `InitialDelay` | `int` | `0` | Delay before first poll (ms) | | `Include` | `string` | `""` | Glob include pattern (`*.csv,*.xml`) — file name only | | `Exclude` | `string` | `""` | Glob exclude pattern — file name only | | `AntInclude` | `string` | `""` | Ant patterns over the path relative to the polled directory (`TYPE_A/outbox/*.csv`): `*` stops at a separator, `**` spans levels | | `AntExclude` | `string` | `""` | Ant patterns over the relative path that drop a file (`archive/**`) | | `AntFilterCaseSensitive` | `bool` | `true` | Whether the Ant patterns respect case | | `FilterDirectory` | `string` | `""` | Condition over a subdirectory, evaluated before it is listed | | `FilterFile` | `string` | `""` | Condition over a polled file, evaluated before it is read or moved | | `Filter` | `string` | `""` | Registry name of an `IGenericFileFilter` (`#myFilter`) | | `Recursive` | `bool` | `false` | Recurse subdirectories | | `MaxDepth` | `int` | `0` | Max recursion depth (0 = unlimited) | | `MinDepth` | `int` | `0` | Min depth for file selection | | `SortBy` | `GenericFileSortBy` | `None` | Sort: `Name`, `NameDesc`, `Modified`, `ModifiedDesc`, `Size`, `SizeDesc` | | `MaxMessagesPerPoll` | `int` | `0` | Max files per poll (0 = unlimited) | | `MinAge` | `long` | `0` | Min file age (ms) | | `BackoffMultiplier` | `int` | `0` | Skip this many polls once a threshold is hit (0 = backoff off) | | `BackoffIdleThreshold` | `int` | `0` | Consecutive idle polls (no exchange created) that arm the skip | | `BackoffErrorThreshold` | `int` | `0` | Consecutive failed polls (the poll itself threw) that arm the skip | | `BackoffOnFailedExchanges` | `bool` | `false` | Beyond Camel: count a poll whose every exchange failed as an error for `BackoffErrorThreshold` | **Poll backoff** follows Apache Camel `ScheduledPollConsumer`: after `BackoffIdleThreshold` idle polls or `BackoffErrorThreshold` error polls, the next `BackoffMultiplier` polls are skipped (no listing, no connect), then the counters reset. A skipped poll still waits `Delay`, so stopping the consumer during a skip resolves within `Delay`. Entering backoff logs one warning; resuming logs one info line. `BackoffMultiplier` requires at least one threshold, and a threshold requires a multiplier — otherwise the endpoint refuses the configuration. **A file that fails in the route.** By default (Camel parity) a poll that created exchanges counts as success even if the route failed them, so a deterministically-bad file, or every file while the downstream is down, is retried every `Delay`. Two remedies: - **Poison file** → `OnException().MaximumRedeliveries(n).RedeliveryDelay(...)` and/or `MoveFailed` to quarantine it out of the poll directory. - **Downstream down** (every file fails) → set `BackoffOnFailedExchanges = true` (with an error threshold + multiplier): a poll whose every created exchange failed unhandled then counts as an error and the consumer backs off instead of hammering the downstream. A poll with any success still counts as success. #### Consumer / Post-Processing | Property | Type | Default | Description | |----------|------|---------|-------------| | `Noop` | `bool` | `false` | Leave file in place after processing | | `Delete` | `bool` | `false` | Delete file after processing | | `MoveTo` | `string` | `""` | Move after processing. Supports the file keys (see below) | | `MoveExisting` | `GenericFileExistStrategy` | `Override` | Strategy at move target | | `PreMove` | `string` | `""` | Move before processing. Supports the file keys (see below) | Only one of `Noop`, `Delete`, `MoveTo` can be set. #### Consumer / Idempotency | Property | Type | Default | Description | |----------|------|---------|-------------| | `Idempotent` | `bool` | `false` | Enable idempotent consumer | | `IdempotentKey` | `string` | `""` | Custom key. Supports the file keys only (see below) | | `DoneFileName` | `string` | `""` | Done-file pattern (`${file:name}.done`) | Default idempotent key: `"{fullPath}|{lastModifiedUtc:O}|{length}"`. #### Consumer / Body | Property | Type | Default | Description | |----------|------|---------|-------------| | `StreamBody` | `bool` | `false` | `false` → `byte[]`, `true` → `Stream` | | `Charset` | `string` | `utf-8` | Character encoding | #### Producer | Property | Type | Default | Description | |----------|------|---------|-------------| | `FileName` | `DynamicValue?` | — | Target file name (expression) | | `FileExist` | `GenericFileExistStrategy` | `Override` | `Override`, `Append`, `Fail`, `Ignore`, `Move`, `TryRename` | | `TempPrefix` | `string` | — | Temp file prefix, put before the target name as written | | `TempFileName` | `string` | — | Full temp file name in the target directory; file keys read the file being written (`${file:name}.part`) | | `AutoCreate` | `bool` | `true` | Auto-create parent directories | | `AllowNullBody` | `bool` | `false` | Allow null body (empty file) | | `EagerDeleteTargetFile` | `bool` | `true` | Delete target before writing | | `AppendChars` | `string?` | — | Chars appended after each write | ### RemoteFileEndpointOptions (extends Base) #### Connection | Property | Type | Default | Description | |----------|------|---------|-------------| | `Host` | `string` | `localhost` | Server hostname | | `Port` | `int` | (transport-specific) | Server port | | `Username` | `string?` | — | Auth username | | `Password` | `string?` | — | Auth password | | `ConnectionTimeout` | `int` | `30000` | Connection timeout (ms) | | `OperationTimeout` | `int` | `60000` | Operation timeout (ms) | #### Reconnection | Property | Type | Default | Description | |----------|------|---------|-------------| | `MaximumReconnectAttempts` | `int` | `3` | Max reconnect attempts on failure | | `ReconnectDelay` | `int` | `1000` | Delay between attempts (ms) | | `Disconnect` | `bool` | `false` | Disconnect after each poll/write | #### Consumer-Specific | Property | Type | Default | Description | |----------|------|---------|-------------| | `MaxAge` | `long` | `0` | Max file age (ms, 0 = unlimited) | | `MoveFailed` | `string` | `""` | Move on failure. Supports the file keys (see below) | | `StartingDirectoryMustExist` | `bool` | `false` | Fail if base dir doesn't exist | | `SendEmptyMessageWhenIdle` | `bool` | `false` | Send empty exchange when no files | ## Enums ### GenericFileExistStrategy | Value | Description | |-------|-------------| | `Override` | Overwrite existing file | | `Append` | Append to existing file | | `Fail` | Throw exception | | `Ignore` | Skip silently | | `Move` | Rename existing file before writing | | `TryRename` | Try alternate names | ### GenericFileSortBy | Value | Description | |-------|-------------| | `None` | No sorting | | `Name` / `NameDesc` | Sort by name | | `Modified` / `ModifiedDesc` | Sort by last modified | | `Size` / `SizeDesc` | Sort by size | ## File Operations Interface Transport implementations provide `IFileOperations` (or `IRemoteFileOperations` for network transports): - `ListFilesAsync` — enumerate files in a directory - `ReadAllBytesAsync` / `OpenReadAsync` — read file contents - `WriteAsync` (byte[] / Stream) / `AppendAsync` / `AppendTextAsync` — write - `ExistsAsync` / `DeleteAsync` / `MoveAsync` — file operations - `CreateDirectoryAsync` / `DirectoryExistsAsync` — directory operations - Path helpers: `CombinePath`, `GetParentPath`, `GetFileName`, `GetExtension`, etc. ## Glob Patterns Include/exclude patterns support comma-separated values and `*`/`?` wildcards: ``` *.csv — all CSV files *.csv,*.xml — CSV and XML files report_* — files starting with "report_" data?.txt — data1.txt, dataA.txt, etc. ``` ## Path Filters A glob sees only the file name, so it cannot say *which directory* a recursive poll should take. Four options decide by path, in the order the poll applies them (Apache Camel parity): ``` antInclude=TYPE_A/outbox/*.csv,TYPE_B/outbox/*.csv — Ant patterns over the path relative to the antExclude=archive/** polled directory; '*' stops at a separator, '**' spans levels, ',' separates patterns filterDirectory=header.redbSftp.Name != 'archive' — asked per subdirectory BEFORE it is listed filterFile=header.redbSftp.Length > 1024 — asked per file before it is read or moved filter=#partnerFilter — an IGenericFileFilter from the registry, for both files and directories ``` `filterDirectory` and the bean's `AcceptDirectory` decide while the listing is still walking, so a directory they turn down costs nothing — no listing, no round trip. That is what makes one consumer over a partner tree of two hundred directories affordable, and it is the only way to keep one connection when the server allows only one. Everything these filters reject is left exactly as it was found: no exchange is created for it, so `delete`, `move` and `preMove` never touch it. Polling a parent recursively and sorting it out in the route does the opposite — the file is downloaded and post-processed first. ## File keys in the consumer options `moveTo`, `preMove`, `moveFailed`, `doneFileName` and `idempotentKey` take the keys of Apache Camel's file language, resolved against the file being handled. They are the keys of a route template (`${file:name}` over the `redbFile.*` headers), with the same values; here they match ignoring case (`${FILE:NAME}` works), in a template exactly. A key that is not in the table fails when the endpoint is created. | Key | Value | |-----|-------| | `${file:name}`, `${file:onlyname}` | File name with extension | | `${file:name.noext}`, `${file:onlyname.noext}` | File name without extension | | `${file:ext}`, `${file:name.ext}` | Extension without the dot, lowercased (`csv`) | | `${file:parent}` | Directory that holds the file | | `${file:path}`, `${file:absolute.path}` | Full path of the file | | `${file:relative.path}` | Path relative to the polled directory | | `${file:length}`, `${file:size}` | Size in bytes | | `${file:modified}` | Last write time, ISO 8601 | A subclass of `GenericFileConsumer` that moves files itself overrides `PostProcessAsync(GenericFileInfo, string, CancellationToken)` and `OnProcessingFailedAsync(GenericFileInfo, string, CancellationToken)`; the forms with `(filePath, fileName, basePath)` are still called for a subclass that overrides them, without the size and the time. ## Requirements - .NET 10.0 / 11.0. The 4.7 line stays on .NET 8, 9 and 10 for applications that cannot move yet. - `redb.Route` (core) — no external dependencies Path: redb-route/redb.Route.GenericFile/RemoteFileConnectionFactory.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/RemoteFileConnectionFactory.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.GenericFile; /// /// Base named connection factory for remote-file transports (FTP, SFTP). Register a concrete /// subclass in the route registry and reference it by name from the endpoint URI /// (connectionFactory=my-server) so server credentials never have to appear in the URI, /// and therefore can never reach logs, telemetry, or the Tsak dashboard. /// public abstract class RemoteFileConnectionFactory { /// Remote server hostname or IP. public string Host { get; set; } = "localhost"; /// Server port (0 = protocol default). public int Port { get; set; } /// Username for authentication. public string Username { get; set; } = ""; /// Password for authentication. [Sensitive] public string Password { get; set; } = ""; /// Connection timeout in milliseconds. public int ConnectionTimeout { get; set; } = 30_000; /// Operation timeout in milliseconds. public int OperationTimeout { get; set; } = 60_000; /// /// Copies the shared connection and credential settings onto the endpoint options, but only for /// parameters the endpoint URI did not set explicitly — an inline URI value always wins, so /// existing routes keep their behaviour. Subclasses override to add protocol-specific fields /// and must call base.ApplyTo(...) first. /// internal virtual void ApplyTo(RemoteFileEndpointOptions options, EndpointUri uri) { var supplied = uri.RawParameters; if (!supplied.ContainsKey(nameof(options.Host))) options.Host = Host; if (!supplied.ContainsKey(nameof(options.Port))) options.Port = Port; if (!supplied.ContainsKey(nameof(options.Username))) options.Username = Username; if (!supplied.ContainsKey(nameof(options.Password))) options.Password = Password; if (!supplied.ContainsKey(nameof(options.ConnectionTimeout))) options.ConnectionTimeout = ConnectionTimeout; if (!supplied.ContainsKey(nameof(options.OperationTimeout))) options.OperationTimeout = OperationTimeout; } } 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); } } } Path: redb-route/redb.Route.GenericFile/RemoteFileEndpointOptions.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/RemoteFileEndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.GenericFile; /// /// Base endpoint options for remote file-based transports (SFTP, FTP). /// Extends with connection parameters, /// reconnection logic, and remote-specific consumer features. /// public abstract class RemoteFileEndpointOptions : GenericFileEndpointOptions { // ═══════════════════════════════════════════════════════════════════ // CONNECTION // ═══════════════════════════════════════════════════════════════════ /// Remote server hostname or IP address. (default: localhost) public string Host { get; set; } = "localhost"; /// Remote server port. Subclass should set the protocol-specific default. public virtual int Port { get; set; } /// /// Named from the route registry. Lets server /// credentials live in the registry instead of the endpoint URI, so they never reach logs /// or dashboards. Typed as the common base, which every remote-file connector's factory derives from: the /// check gate refuses a bean of any other class; the connector itself asks for its own factory type. /// [RegistryReference(typeof(RemoteFileConnectionFactory))] public string? ConnectionFactory { get; set; } /// Username for authentication. public string Username { get; set; } = ""; /// Password for authentication. [Sensitive] public string Password { get; set; } = ""; /// TCP connection timeout in milliseconds. (default: 30000 = 30 s) public int ConnectionTimeout { get; set; } = 30_000; /// Operation timeout in milliseconds (read/write/list). (default: 60000 = 60 s) public int OperationTimeout { get; set; } = 60_000; // ═══════════════════════════════════════════════════════════════════ // RECONNECTION // ═══════════════════════════════════════════════════════════════════ /// Maximum number of automatic reconnect attempts after a disconnect. (default: 3) public int MaximumReconnectAttempts { get; set; } = 3; /// Delay in milliseconds between reconnect attempts. (default: 1000) public int ReconnectDelay { get; set; } = 1000; /// /// If true, disconnect after each poll cycle (consumer) or each upload (producer). /// Reduces open connections at the cost of latency. (default: false) /// public bool Disconnect { get; set; } // ═══════════════════════════════════════════════════════════════════ // CONSUMER: Remote-specific // ═══════════════════════════════════════════════════════════════════ /// Maximum file age in milliseconds. Files older than this are skipped. 0 = no limit. (default: 0) public long MaxAge { get; set; } /// Directory to move files to on processing failure. Empty = leave in place. public string MoveFailed { get; set; } = ""; /// /// If true, the starting (base) directory must exist on the remote server. /// Throws if it doesn't. (default: false) /// public bool StartingDirectoryMustExist { get; set; } /// /// If true, the consumer creates an empty exchange when a poll returns no files. /// Useful for heartbeat-style monitoring. (default: false) /// public bool SendEmptyMessageWhenIdle { get; set; } // ═══════════════════════════════════════════════════════════════════ // VALIDATION // ═══════════════════════════════════════════════════════════════════ /// /// Validates remote-specific options. Subclasses should call this from their Validate() method. /// protected void ValidateRemote() { ValidateCommon(); GenericFileUtils.ValidateFileKeys("moveFailed", MoveFailed); if (string.IsNullOrWhiteSpace(Host)) throw new ArgumentException("Host must be specified."); if (Port is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(Port), Port, "Port must be 1–65535."); if (MaxAge < 0) throw new ArgumentOutOfRangeException(nameof(MaxAge), MaxAge, "MaxAge cannot be negative."); if (ConnectionTimeout < 0) throw new ArgumentOutOfRangeException(nameof(ConnectionTimeout), ConnectionTimeout, "ConnectionTimeout cannot be negative."); if (OperationTimeout < 0) throw new ArgumentOutOfRangeException(nameof(OperationTimeout), OperationTimeout, "OperationTimeout cannot be negative."); if (MaximumReconnectAttempts < 0) throw new ArgumentOutOfRangeException(nameof(MaximumReconnectAttempts), MaximumReconnectAttempts, "MaximumReconnectAttempts cannot be negative."); if (ReconnectDelay < 0) throw new ArgumentOutOfRangeException(nameof(ReconnectDelay), ReconnectDelay, "ReconnectDelay cannot be negative."); } } Path: redb-route/redb.Route.GenericFile/RemoteFileProducer.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/RemoteFileProducer.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.GenericFile; /// /// Base class for remote file producers (SFTP, FTP). Extends /// with connection lifecycle management: auto-connect before write, reconnect on failure, /// disconnect after write if configured. /// /// Concrete options type inheriting . public abstract class RemoteFileProducer : GenericFileProducer where TOptions : RemoteFileEndpointOptions { private readonly IRemoteFileOperations _remoteOps; /// Remote file operations with connection lifecycle. protected IRemoteFileOperations RemoteOperations => _remoteOps; /// Creates a remote file producer. protected RemoteFileProducer(IEndpoint endpoint, TOptions options, IRemoteFileOperations operations) : base(endpoint, options, operations) { ArgumentNullException.ThrowIfNull(operations); _remoteOps = operations; } /// /// Connects to the remote server and auto-creates the target directory if configured. /// protected override async Task BeforeWriteAsync(string targetDir, CancellationToken ct) { await EnsureConnectedAsync(ct).ConfigureAwait(false); await base.BeforeWriteAsync(targetDir, ct).ConfigureAwait(false); } /// /// Disconnects from the remote server if the Disconnect option is set. /// protected override Task OnWriteCompletedAsync(IExchange exchange, string targetPath, CancellationToken ct) { if (Options.Disconnect) DisconnectClient(); return Task.CompletedTask; } /// public override async Task Stop(CancellationToken ct = default) { DisconnectClient(); await base.Stop(ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // 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, "Producer reconnect to {Host}:{Port} failed, attempt {Attempt}/{Max}", 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, "Producer: error during disconnect"); } } } Path: redb-route/redb.Route.GenericFile/redb.Route.GenericFile.csproj 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/redb.Route.GenericFile.csproj ---- redb.Route.GenericFile Shared base classes for file-based transports in redb.Route ESB (local file, SFTP, FTP). Provides GenericFileConsumer, GenericFileProducer, IFileOperations, and RemoteFile base classes following the template-method pattern. esb;messaging;file;sftp;ftp;base;redb README.md