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