Path: redb-route/redb.Route.File/FileConsumer.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.File/FileConsumer.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.GenericFile; namespace redb.Route.File; /// /// File consumer. Inherits the complete poll loop from /// and adds local-file-specific behavior: read locking, lock-file exclusion, content-type inference. /// public class FileConsumer : GenericFileConsumer { private readonly FileEndpoint _endpoint; private readonly IReadLockStrategy _readLock; /// protected override string ConsumerName => $"file:{_endpoint.DirectoryPath}"; /// protected override string BasePath => _endpoint.DirectoryPath; /// Creates a file consumer. public FileConsumer(FileEndpoint endpoint, IProcessor processor, FileEndpointOptions options) : base(endpoint, processor, options, new LocalFileOperations()) { _endpoint = endpoint; _readLock = ReadLockFactory.Create(options.ReadLock); } /// The idempotent repository (null if idempotency is disabled). internal new InMemoryGenericFileIdempotentRepository? IdempotentRepository => base.IdempotentRepository; // ═══════════════════════════════════════════════════════════════════ // OVERRIDES // ═══════════════════════════════════════════════════════════════════ /// protected override IEnumerable ApplyFilters(IEnumerable files) { // Exclude lock/rename marker files (local-file-specific) files = files.Where(f => !f.Name.EndsWith(Options.ReadLockMarkerFileExtension, StringComparison.OrdinalIgnoreCase) && !f.Name.EndsWith(".redbRename", StringComparison.OrdinalIgnoreCase)); return base.ApplyFilters(files); } /// protected override void SetExchangeHeaders(IMessage message, GenericFileInfo file, string workPath) { var ext = Operations.GetExtension(file.Name).ToLowerInvariant(); message.ContentType = ext switch { ".json" => "application/json", ".xml" => "application/xml", ".txt" or ".log" or ".csv" => "text/plain", ".html" or ".htm" => "text/html", _ => null }; message.Headers[FileHeaders.FileName] = file.Name; message.Headers[FileHeaders.FileNameOnly] = Operations.GetFileNameWithoutExtension(file.Name); message.Headers[FileHeaders.FileExtension] = ext; message.Headers[FileHeaders.FileAbsolutePath] = workPath; message.Headers[FileHeaders.FileRelativePath] = Operations.GetRelativePath(file.BasePath, workPath); message.Headers[FileHeaders.FileParent] = Operations.GetParentPath(workPath); message.Headers[FileHeaders.FileLength] = file.Length; message.Headers[FileHeaders.FileLastModified] = file.LastModified; } /// protected override async Task AcquireReadLockAsync(GenericFileInfo file, CancellationToken ct) { var info = new FileInfo(file.FullPath); return await _readLock.AcquireLock(info, Options, ct).ConfigureAwait(false); } /// /// The rename strategy moves the file aside while it holds the lock. protected override string ResolveWorkPath(GenericFileInfo file) => _readLock.GetWorkPath(file.FullPath); /// /// /// When the strategy holds an exclusive handle (), /// the body is read through that handle. Opening the file a second time would be refused /// by the very lock this consumer holds. /// protected override async Task CreateExchangeAsync(GenericFileInfo file, string workPath, CancellationToken ct) { var locked = _readLock.GetLockedStream(file.FullPath); if (locked == null) return await base.CreateExchangeAsync(file, workPath, ct).ConfigureAwait(false); if (locked.CanSeek) locked.Seek(0, SeekOrigin.Begin); object body; if (Options.StreamBody) { body = locked; } else { using var buffer = new MemoryStream(); await locked.CopyToAsync(buffer, ct).ConfigureAwait(false); body = buffer.ToArray(); } var message = new Message { Body = body }; SetExchangeHeaders(message, file, workPath); return Exchange.Create(message, Endpoint.ScopeFactory); } /// protected override Task ReleaseReadLockAsync(GenericFileInfo file, CancellationToken ct) { var info = new FileInfo(file.FullPath); _readLock.ReleaseLock(info, Options); return Task.CompletedTask; } /// /// /// Moves a failed file to when configured, so a poison /// file is quarantined out of the poll directory instead of being re-picked on every poll. No-op when /// unset (the file is left in place). Best-effort: a move failure is logged, not thrown. /// 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); } } /// /// Simple glob matching supporting * and ? wildcards. /// Converts glob to regex for matching. /// internal static bool GlobMatch(string input, string pattern) => GenericFileUtils.GlobMatch(input, pattern); }