Bundle: redb-route / redb.Route.File (redb.Route.File.txt), 13 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.File/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.File;
///
/// Extension methods for registering the File transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that
/// file:// URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteFile();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteFile(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.File/FileComponent.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/FileComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.GenericFile;
namespace redb.Route.File;
///
/// File component. Scheme: "file".
/// Provides file system polling (consumer) and atomic file writing (producer).
/// URI: file:///C:/input?include=*.csv&delay=5000&noop=true
/// URI: file:///C:/output?fileName=${header.orderId}.json&fileExist=Override
///
public class FileComponent : ComponentBase
{
///
public override string Scheme => "file";
/// Structured XML form: <file directory="out/orders"/>.
public override string? StructuredPathSynonym => "directory";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new FileEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.ResolveFilter(Context);
options.Validate();
return new FileEndpoint(uri, this, options);
}
}
///
/// File endpoint. Creates either a consumer (for polling) or a producer (for writing).
/// The path part of the URI is the base directory.
///
public class FileEndpoint : EndpointBase
{
/// Creates a file endpoint.
public FileEndpoint(EndpointUri uri, FileComponent component, FileEndpointOptions options)
: base(uri, component, options)
{
}
/// The base directory path derived from the endpoint URI.
public string DirectoryPath => NormalizeDirectoryPath(Uri.Path);
/// Gets the endpoint options for external access.
internal FileEndpointOptions EndpointOptions => Options;
///
public override IProducer CreateProducer()
{
return new FileProducer(this, Options);
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new FileConsumer(this, processor, Options);
}
private static string NormalizeDirectoryPath(string path)
{
// Handle URI-style paths: remove leading slash for Windows absolute paths
// e.g. "/C:/input" -> "C:/input", "/home/user/input" stays as-is on Linux
if (path.Length >= 3 && path[0] == '/' && char.IsLetter(path[1]) && path[2] == ':')
{
path = path[1..]; // Remove leading '/'
}
return Path.GetFullPath(path);
}
}
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);
}
Path: redb-route/redb.Route.File/FileEndpointOptions.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/FileEndpointOptions.cs
----
using redb.Route.GenericFile;
namespace redb.Route.File;
///
/// Options for file endpoints. Inherits shared options from
/// and adds local-file-specific read lock configuration.
/// URI: file:///C:/path?include=*.csv&delay=5000&noop=true
///
public class FileEndpointOptions : GenericFileEndpointOptions
{
// ── Read locking (local file only) ──────────────────────────────
/// Read lock strategy (default: None).
public ReadLockStrategy ReadLock { get; set; } = ReadLockStrategy.None;
/// Timeout in milliseconds for acquiring a read lock (default: 10000).
public long ReadLockTimeout { get; set; } = 10000;
/// Interval in milliseconds between read lock checks for 'Changed' strategy (default: 1000).
public int ReadLockCheckInterval { get; set; } = 1000;
/// Minimum age in milliseconds for 'Changed' strategy — file must be unchanged for this long (default: 1000).
public long ReadLockMinAge { get; set; } = 1000;
/// Extension used for marker file lock (default: ".redbLock").
public string ReadLockMarkerFileExtension { get; set; } = ".redbLock";
// ── Failure handling ────────────────────────────────────────────
///
/// Directory to move a file to when its processing fails (empty = disabled, the default).
/// Relative to the endpoint directory unless absolute; supports the same file tokens as
/// . Without it a failed file is left in place and
/// re-picked on the next poll; setting it quarantines poison files out of the poll directory.
///
public string MoveFailed { get; set; } = "";
// ── Producer safety ─────────────────────────────────────────────
///
/// If true, the producer refuses to write outside the endpoint directory (default: true).
/// File names usually arrive from the incoming message, so a "../" or absolute name would
/// otherwise escape the directory. Set to false only when writing outside is intended.
///
public bool JailStartingDirectory { get; set; } = true;
///
public override void Validate()
{
ValidateCommon();
GenericFileUtils.ValidateFileKeys("moveFailed", MoveFailed);
if (ReadLockCheckInterval <= 0)
throw new ArgumentOutOfRangeException(nameof(ReadLockCheckInterval), ReadLockCheckInterval,
"ReadLockCheckInterval must be positive.");
if (ReadLockMinAge < 0)
throw new ArgumentOutOfRangeException(nameof(ReadLockMinAge), ReadLockMinAge,
"ReadLockMinAge cannot be negative.");
if (ReadLockTimeout < 0)
throw new ArgumentOutOfRangeException(nameof(ReadLockTimeout), ReadLockTimeout,
"ReadLockTimeout cannot be negative.");
}
}
Path: redb-route/redb.Route.File/FileEnums.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/FileEnums.cs
----
namespace redb.Route.File;
///
/// Strategy for handling read locks on files being consumed.
/// Determines how the consumer ensures a file is not currently being written to.
///
public enum ReadLockStrategy
{
/// No read lock. File is picked up immediately.
None,
///
/// Creates a marker file (*.redbLock) next to the target file.
/// Other consumers skip files with an existing lock marker.
///
MarkerFile,
///
/// Waits until the file size stops changing for a configurable interval.
/// Good for large files being uploaded/written.
///
Changed,
///
/// Holds the file open without read or write sharing for the duration of processing.
/// If the open fails, the file is skipped until next poll.
/// Windows only: Linux and macOS locks are advisory, there another reader opens the file
/// anyway and the strategy keeps nobody out. Use ,
/// or there.
///
FileLock,
///
/// Attempts to rename the file. If rename fails, the file is locked by another process.
///
Rename
}
Path: redb-route/redb.Route.File/FileHeaders.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/FileHeaders.cs
----
namespace redb.Route.File;
///
/// Constants for exchange headers and properties set by the file component.
/// All prefixed with "redbFile." to avoid collisions.
///
public static class FileHeaders
{
/// Common prefix for all File component headers.
public const string Prefix = "redbFile.";
// ── Headers set on the In message by the consumer ────────────────
/// Full file name with extension (e.g. "order.csv").
public const string FileName = "redbFile.Name";
/// File name without the extension (e.g. "order").
public const string FileNameOnly = "redbFile.NameOnly";
/// File extension including the dot (e.g. ".csv").
public const string FileExtension = "redbFile.Extension";
/// Full absolute path of the file.
public const string FileAbsolutePath = "redbFile.AbsolutePath";
/// Path relative to the polling directory.
public const string FileRelativePath = "redbFile.RelativePath";
/// Parent directory of the file.
public const string FileParent = "redbFile.Parent";
/// File size in bytes.
public const string FileLength = "redbFile.Length";
/// Last modified date/time as DateTimeOffset.
public const string FileLastModified = "redbFile.LastModified";
// ── Headers set by the producer after writing ────────────────────
/// Absolute path of the file that was actually written by the producer.
public const string FileNameProduced = "redbFile.NameProduced";
}
Path: redb-route/redb.Route.File/FileProducer.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/FileProducer.cs
----
using redb.Route.Abstractions;
using redb.Route.GenericFile;
namespace redb.Route.File;
///
/// File producer. Inherits the complete write flow from
/// (temp file, atomic rename, file-exist strategies).
/// Adds content-type inference for the produced file.
///
public class FileProducer : GenericFileProducer
{
private readonly FileEndpoint _endpoint;
///
protected override string BasePath => _endpoint.DirectoryPath;
///
protected override string FileNameProducedHeader => FileHeaders.FileNameProduced;
/// Creates a file producer.
public FileProducer(FileEndpoint endpoint, FileEndpointOptions options)
: base(endpoint, options, new LocalFileOperations())
{
_endpoint = endpoint;
}
///
///
/// The file name usually comes from an incoming message, so it is not trusted: a relative
/// "../" name or an absolute path would otherwise write outside the endpoint directory
/// ( silently discards the base for absolute paths).
/// Set to false to allow it.
///
protected override void ValidatePath(string targetPath)
{
if (!Options.JailStartingDirectory)
return;
var fullTarget = Path.GetFullPath(targetPath);
var root = Path.GetFullPath(BasePath);
var comparison = OperatingSystem.IsWindows()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
if (!GenericFileUtils.IsWithinDirectory(root, fullTarget, Path.DirectorySeparatorChar, comparison))
{
throw new UnauthorizedAccessException(
$"Producer path '{targetPath}' resolves to '{fullTarget}', outside the endpoint directory '{root}'. " +
"Set jailStartingDirectory=false to allow writing outside the base directory.");
}
}
///
protected override 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(FileHeaders.FileName, out var hfn)
? hfn?.ToString()
: null;
fileName = headerFileName ?? $"redb-{Guid.NewGuid():N}";
}
return Operations.CombinePath(BasePath, fileName);
}
}
Path: redb-route/redb.Route.File/Fluent/FileDsl.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/Fluent/FileDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.File;
///
/// Fluent API for File endpoints.
///
/// .From(FileDsl.Read("/data/input").Include("*.csv").Recursive().Noop())
/// .To(FileDsl.Write("/data/output").Charset("utf-8"))
///
///
public static class FileDsl
{
/// Poll a directory for files (consumer).
public static FileBuilder Read(string directory) => new(directory);
/// Write files to a directory (producer).
public static FileBuilder Write(string directory) => new(directory);
}
///
/// Fluent builder for File endpoint URIs.
///
public sealed class FileBuilder
{
private readonly string _directory;
// Consumer (polling)
private string? _delay;
private string? _initialDelay;
private string? _include;
private string? _exclude;
private string? _antInclude;
private string? _antExclude;
private bool? _antFilterCaseSensitive;
private string? _filterDirectory;
private string? _filterFile;
private string? _filter;
private bool _recursive;
private string? _sortBy;
private string? _maxMessagesPerPoll;
private string? _backoffMultiplier;
private string? _backoffIdleThreshold;
private string? _backoffErrorThreshold;
private bool _backoffOnFailedExchanges;
private string? _minAge;
// Post-processing
private bool _noop;
private bool _delete;
private string? _moveTo;
private string? _moveExisting;
private string? _moveFailed;
private string? _preMove;
// Idempotency
private bool _idempotent;
private string? _idempotentKey;
// Read locking
private string? _readLock;
private string? _readLockTimeout;
private string? _readLockCheckInterval;
private string? _readLockMinAge;
private string? _readLockMarkerFileExtension;
// Done file
private string? _doneFileName;
private bool _streamBody;
// Producer (write)
private string? _fileName;
private string? _fileExist;
private string? _tempPrefix;
private string? _tempFileName;
private string? _charset;
private bool? _autoCreate;
private bool _allowNullBody;
private string? _appendChars;
private bool? _eagerDeleteTargetFile;
private bool? _jailStartingDirectory;
internal FileBuilder(string directory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(directory);
_directory = directory;
}
// ── Consumer ──────────────────────────────────────────────────────
/// Poll delay in milliseconds. Default 500.
public FileBuilder Delay(int ms) { _delay = ms.ToString(); return this; }
/// Poll delay from an expression.
public FileBuilder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; }
/// Initial delay before first poll. Default 0.
public FileBuilder InitialDelay(int ms) { _initialDelay = ms.ToString(); return this; }
/// Initial delay from an expression.
public FileBuilder InitialDelay(IExpression ms) { _initialDelay = ms.ToTemplateString(); return this; }
/// Skip this many polls once a backoff threshold is hit (0 = disabled; needs a threshold).
public FileBuilder BackoffMultiplier(int value) { _backoffMultiplier = value.ToString(); return this; }
/// Backoff multiplier from an expression.
public FileBuilder BackoffMultiplier(IExpression value) { _backoffMultiplier = value.ToTemplateString(); return this; }
/// Consecutive idle polls (no exchange created) that arm the backoff skip (0 = disabled).
public FileBuilder BackoffIdleThreshold(int value) { _backoffIdleThreshold = value.ToString(); return this; }
/// Backoff idle threshold from an expression.
public FileBuilder BackoffIdleThreshold(IExpression value) { _backoffIdleThreshold = value.ToTemplateString(); return this; }
/// Consecutive failed polls (the poll itself threw) that arm the backoff skip (0 = disabled).
public FileBuilder BackoffErrorThreshold(int value) { _backoffErrorThreshold = value.ToString(); return this; }
/// Backoff error threshold from an expression.
public FileBuilder BackoffErrorThreshold(IExpression value) { _backoffErrorThreshold = value.ToTemplateString(); return this; }
/// Count a poll whose every created exchange failed as an error for backoff (needs BackoffErrorThreshold).
public FileBuilder BackoffOnFailedExchanges() { _backoffOnFailedExchanges = true; return this; }
/// File name pattern to include (e.g. "*.csv").
public FileBuilder Include(string pattern) { _include = pattern; return this; }
/// File name pattern to exclude.
public FileBuilder Exclude(string pattern) { _exclude = pattern; return this; }
/// Ant-style patterns over the path relative to the polled directory, several separated by commas ("TYPE_A/outbox/*.csv"). Sees directories, which Include does not.
public FileBuilder AntInclude(string patterns) { _antInclude = patterns; return this; }
/// Ant-style patterns over the relative path that drop a file ("archive/**").
public FileBuilder AntExclude(string patterns) { _antExclude = patterns; return this; }
/// Whether the Ant patterns respect case (default true).
public FileBuilder AntFilterCaseSensitive(bool value = true) { _antFilterCaseSensitive = value; return this; }
/// Condition deciding whether a subdirectory is walked into at all — evaluated before it is listed.
public FileBuilder FilterDirectory(string condition) { _filterDirectory = condition; return this; }
/// Condition deciding whether a polled file is taken, evaluated before it is read or moved.
public FileBuilder FilterFile(string condition) { _filterFile = condition; return this; }
/// Name of an IGenericFileFilter in the route registry ("#myFilter") deciding for files and directories.
public FileBuilder Filter(string registryName) { _filter = registryName; return this; }
/// Recurse into subdirectories.
public FileBuilder Recursive() { _recursive = true; return this; }
/// Sort order: None, Name, NameDesc, Modified, ModifiedDesc, Size, SizeDesc.
public FileBuilder SortBy(string sortBy) { _sortBy = sortBy; return this; }
/// Max files per poll. Default 0 (unlimited).
public FileBuilder MaxMessagesPerPoll(int max) { _maxMessagesPerPoll = max.ToString(); return this; }
/// Max files per poll from an expression.
public FileBuilder MaxMessagesPerPoll(IExpression max) { _maxMessagesPerPoll = max.ToTemplateString(); return this; }
/// Minimum file age in milliseconds before processing.
public FileBuilder MinAge(long ms) { _minAge = ms.ToString(); return this; }
/// Minimum file age from an expression.
public FileBuilder MinAge(IExpression ms) { _minAge = ms.ToTemplateString(); return this; }
// ── Post-processing ───────────────────────────────────────────────
/// Do nothing after processing (leave file in place).
public FileBuilder Noop() { _noop = true; return this; }
/// Delete file after processing.
public FileBuilder Delete() { _delete = true; return this; }
/// Move processed file to this directory.
public FileBuilder MoveTo(IExpression directory) { _moveTo = directory.ToTemplateString(); return this; }
///
/// Move processed file to this directory. Supports the file keys
/// (${file:name}, ${file:name.noext}, ${file:ext} and the rest of ); exchange expressions are not
/// available here, the directory is resolved from file metadata alone.
///
public FileBuilder MoveTo(string directory) { _moveTo = directory; return this; }
/// Strategy when file exists in move target: Override, Append, Fail, Ignore, Move, TryRename.
public FileBuilder MoveExisting(string strategy) { _moveExisting = strategy; return this; }
/// Move a file whose processing failed to this directory (quarantine for poison files).
public FileBuilder MoveFailed(IExpression directory) { _moveFailed = directory.ToTemplateString(); return this; }
///
/// Move a file whose processing failed to this directory. Without it a failed file is left in place
/// and re-picked on the next poll. Supports the file keys (${file:name}, ${file:ext}
/// and the rest of ).
///
public FileBuilder MoveFailed(string directory) { _moveFailed = directory; return this; }
/// Pre-move directory (temporary move before processing).
public FileBuilder PreMove(IExpression directory) { _preMove = directory.ToTemplateString(); return this; }
///
/// Pre-move directory (temporary move before processing). Supports the file keys
/// (${file:name}, ${file:name.noext}, ${file:ext} and the rest of ).
///
public FileBuilder PreMove(string directory) { _preMove = directory; return this; }
// ── Idempotency ───────────────────────────────────────────────────
/// Enable idempotent consumer with an optional key expression.
public FileBuilder Idempotent(IExpression? key = null) { _idempotent = true; _idempotentKey = key?.ToTemplateString(); return this; }
///
/// Enable idempotent consumer with a custom key. Supports the file keys
/// (${file:name}, ${file:name.noext}, ${file:ext} and the rest of ); the key is computed before the
/// exchange exists, so header and body expressions cannot be used.
/// Without a key the default is path + last modified + size.
///
public FileBuilder Idempotent(string key) { _idempotent = true; _idempotentKey = key; return this; }
// ── Read locking ──────────────────────────────────────────────────
/// Read lock strategy: None, MarkerFile, Changed, FileLock, Rename.
public FileBuilder ReadLock(string strategy) { _readLock = strategy; return this; }
/// Read lock timeout in milliseconds. Default 10000.
public FileBuilder ReadLockTimeout(long ms) { _readLockTimeout = ms.ToString(); return this; }
/// Read lock timeout from an expression.
public FileBuilder ReadLockTimeout(IExpression ms) { _readLockTimeout = ms.ToTemplateString(); return this; }
/// Read lock check interval in milliseconds. Default 1000.
public FileBuilder ReadLockCheckInterval(int ms) { _readLockCheckInterval = ms.ToString(); return this; }
/// Read lock check interval from an expression.
public FileBuilder ReadLockCheckInterval(IExpression ms) { _readLockCheckInterval = ms.ToTemplateString(); return this; }
/// Minimum file age for Changed read lock. Default 1000.
public FileBuilder ReadLockMinAge(long ms) { _readLockMinAge = ms.ToString(); return this; }
/// Read lock min age from an expression.
public FileBuilder ReadLockMinAge(IExpression ms) { _readLockMinAge = ms.ToTemplateString(); return this; }
/// Marker file extension for MarkerFile read lock. Default ".redbLock".
public FileBuilder ReadLockMarkerFileExtension(string ext) { _readLockMarkerFileExtension = ext; return this; }
// ── Done file ─────────────────────────────────────────────────────
/// Done file name pattern. If set, only files with a matching done file are processed.
public FileBuilder DoneFileName(IExpression name) { _doneFileName = name.ToTemplateString(); return this; }
/// Done file name pattern (template string, supports ${...}).
public FileBuilder DoneFileName(string name) { _doneFileName = name; return this; }
/// Set exchange body to a FileStream instead of byte[]. Stream is closed by Exchange.DisposeAsync.
public FileBuilder StreamBody() { _streamBody = true; return this; }
// ── Producer ──────────────────────────────────────────────────────
/// Output file name or expression (e.g. Header("CamelFileName")).
public FileBuilder FileName(IExpression name) { _fileName = name.ToTemplateString(); return this; }
/// Output file name (template string, supports ${...}).
public FileBuilder FileName(string name) { _fileName = name; return this; }
/// Strategy when target file exists: Override, Append, Fail, Ignore, Move, TryRename.
public FileBuilder FileExist(string strategy) { _fileExist = strategy; return this; }
/// Temporary file prefix during write.
public FileBuilder TempPrefix(IExpression prefix) { _tempPrefix = prefix.ToTemplateString(); return this; }
/// Temporary file prefix during write (template string, supports ${...}).
public FileBuilder TempPrefix(string prefix) { _tempPrefix = prefix; return this; }
/// Temporary file name during write.
public FileBuilder TempFileName(IExpression name) { _tempFileName = name.ToTemplateString(); return this; }
/// Temporary file name during write (template string, supports ${...}).
public FileBuilder TempFileName(string name) { _tempFileName = name; return this; }
/// Character encoding. Default "utf-8".
public FileBuilder Charset(string charset) { _charset = charset; return this; }
/// Auto-create target directory. Default true.
public FileBuilder AutoCreate(bool autoCreate = true) { _autoCreate = autoCreate; return this; }
/// Allow sending null body (creates empty file).
public FileBuilder AllowNullBody() { _allowNullBody = true; return this; }
/// Characters to append after writing (e.g. newline).
public FileBuilder AppendChars(string chars) { _appendChars = chars; return this; }
/// Eagerly delete target file before writing. Default true.
public FileBuilder EagerDeleteTargetFile(bool eager = true) { _eagerDeleteTargetFile = eager; return this; }
///
/// Whether the producer refuses to write outside this directory. Default true.
/// Turn it off only when a "../" or absolute target file name is intended.
///
public FileBuilder JailStartingDirectory(bool jail = true) { _jailStartingDirectory = jail; return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the File endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("file:///");
sb.Append(_directory.TrimStart('/'));
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (!string.IsNullOrEmpty(value)) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolExplicit(string key, bool? value)
{
if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant());
}
// Consumer
AppendIf("delay", _delay);
AppendIf("initialDelay", _initialDelay);
AppendIf("include", _include);
AppendIf("exclude", _exclude);
AppendIf("antInclude", _antInclude);
AppendIf("antExclude", _antExclude);
if (_antFilterCaseSensitive is { } cs) AppendIf("antFilterCaseSensitive", cs ? "true" : "false");
AppendIf("filterDirectory", _filterDirectory);
AppendIf("filterFile", _filterFile);
AppendIf("filter", _filter);
AppendBool("recursive", _recursive);
AppendIf("sortBy", _sortBy);
AppendIf("maxMessagesPerPoll", _maxMessagesPerPoll);
AppendIf("backoffMultiplier", _backoffMultiplier);
AppendIf("backoffIdleThreshold", _backoffIdleThreshold);
AppendIf("backoffErrorThreshold", _backoffErrorThreshold);
AppendBool("backoffOnFailedExchanges", _backoffOnFailedExchanges);
AppendIf("minAge", _minAge);
// Post-processing
AppendBool("noop", _noop);
AppendBool("delete", _delete);
AppendIf("moveTo", _moveTo);
AppendIf("moveExisting", _moveExisting);
AppendIf("moveFailed", _moveFailed);
AppendIf("preMove", _preMove);
// Idempotency
AppendBool("idempotent", _idempotent);
AppendIf("idempotentKey", _idempotentKey);
// Read locking
AppendIf("readLock", _readLock);
AppendIf("readLockTimeout", _readLockTimeout);
AppendIf("readLockCheckInterval", _readLockCheckInterval);
AppendIf("readLockMinAge", _readLockMinAge);
AppendIf("readLockMarkerFileExtension", _readLockMarkerFileExtension);
// Done file
AppendIf("doneFileName", _doneFileName);
// Body
AppendBool("streamBody", _streamBody);
// Producer
AppendIf("fileName", _fileName);
AppendIf("fileExist", _fileExist);
AppendIf("tempPrefix", _tempPrefix);
AppendIf("tempFileName", _tempFileName);
AppendIf("charset", _charset);
AppendBoolExplicit("autoCreate", _autoCreate);
AppendBool("allowNullBody", _allowNullBody);
AppendIf("appendChars", _appendChars);
AppendBoolExplicit("eagerDeleteTargetFile", _eagerDeleteTargetFile);
AppendBoolExplicit("jailStartingDirectory", _jailStartingDirectory);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(FileBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.File/LocalFileOperations.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/LocalFileOperations.cs
----
using System.Text;
using redb.Route.GenericFile;
namespace redb.Route.File;
///
/// Local file system implementation of .
/// Adapts System.IO APIs to the generic file operations interface.
///
internal sealed class LocalFileOperations : IFileOperations
{
public Task> ListFilesAsync(
string directory, bool recursive, int maxDepth, int minDepth,
Func? directoryFilter = null, CancellationToken ct = default)
{
var dir = new DirectoryInfo(directory);
if (!dir.Exists)
return Task.FromResult(new List());
var result = new List();
Walk(dir, 0);
return Task.FromResult(result);
// Walks level by level instead of asking the framework for the whole tree at once: a
// directory the filter turns down is not entered, and maxDepth stops the descent rather
// than discarding what was already enumerated.
void Walk(DirectoryInfo current, int depth)
{
try
{
foreach (var file in current.EnumerateFiles())
{
ct.ThrowIfCancellationRequested();
if (minDepth > 0 && depth < minDepth)
continue;
result.Add(new GenericFileInfo
{
Name = file.Name,
FullPath = file.FullName,
BasePath = directory,
Length = file.Length,
LastModified = new DateTimeOffset(file.LastWriteTimeUtc, TimeSpan.Zero),
Depth = depth
});
}
if (!recursive || (maxDepth > 0 && depth >= maxDepth))
return;
foreach (var sub in current.EnumerateDirectories())
{
ct.ThrowIfCancellationRequested();
if (directoryFilter != null &&
!directoryFilter(sub.FullName, Path.GetRelativePath(directory, sub.FullName)))
continue;
Walk(sub, depth + 1);
}
}
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
}
}
public Task ReadAllBytesAsync(string path, CancellationToken ct)
=> System.IO.File.ReadAllBytesAsync(path, ct);
public Task OpenReadAsync(string path, CancellationToken ct)
{
var stream = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.Read, bufferSize: 4096, FileOptions.SequentialScan);
return Task.FromResult(stream);
}
public Task WriteAsync(string path, byte[] data, CancellationToken ct)
=> System.IO.File.WriteAllBytesAsync(path, data, ct);
public async Task WriteAsync(string path, Stream data, CancellationToken ct)
{
await using var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
await data.CopyToAsync(fs, ct).ConfigureAwait(false);
}
public async Task AppendAsync(string path, byte[] data, CancellationToken ct)
{
await using var fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
await fs.WriteAsync(data, ct).ConfigureAwait(false);
}
public async Task AppendTextAsync(string path, string text, Encoding encoding, CancellationToken ct)
{
await using var fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
await using var writer = new StreamWriter(fs, encoding);
await writer.WriteAsync(text).ConfigureAwait(false);
await writer.FlushAsync(ct).ConfigureAwait(false);
}
public Task ExistsAsync(string path, CancellationToken ct)
=> Task.FromResult(System.IO.File.Exists(path));
public Task DeleteAsync(string path, CancellationToken ct)
{
System.IO.File.Delete(path);
return Task.CompletedTask;
}
public Task MoveAsync(string source, string destination, bool overwrite, CancellationToken ct)
{
System.IO.File.Move(source, destination, overwrite);
return Task.CompletedTask;
}
public Task CreateDirectoryAsync(string path, CancellationToken ct)
{
Directory.CreateDirectory(path);
return Task.CompletedTask;
}
public Task DirectoryExistsAsync(string path, CancellationToken ct)
=> Task.FromResult(Directory.Exists(path));
public string CombinePath(string basePath, string relativePath)
=> Path.Combine(basePath, relativePath);
public string GetParentPath(string path)
=> Path.GetDirectoryName(path) ?? path;
public string GetFileName(string path)
=> Path.GetFileName(path);
public string GetFileNameWithoutExtension(string name)
=> Path.GetFileNameWithoutExtension(name);
public string GetExtension(string name)
=> Path.GetExtension(name);
public string GetRelativePath(string basePath, string fullPath)
=> Path.GetRelativePath(basePath, fullPath);
public bool IsAbsolutePath(string path)
=> Path.IsPathRooted(path);
}
Path: redb-route/redb.Route.File/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.File/README.md
----
# redb.Route.File
> Documentation and articles:
File system transport for redb.Route. Polling consumer with glob filtering, read locking, and idempotency. Atomic file producer with temp-file writes, append, and conflict strategies.
[](https://www.nuget.org/packages/redb.Route.File)
[](../../LICENSE)
## Installation
```bash
dotnet add package redb.Route.File
```
No additional dependencies.
## Usage
### Fluent DSL
```csharp
using redb.Route.File;
// Poll directory for new files
From(FileDsl.Read("/data/incoming")
.Include("*.csv")
.Delay(5000)
.SortBy("Modified")
.MoveTo("/data/processed")
.Idempotent())
.Log("Processing: ${header.redbFile.Name}")
.To("direct://parse");
// Write files atomically
From("direct://export")
.To(FileDsl.Write("/data/outgoing")
.TempPrefix(".tmp-")
.FileExist("Override")
.AutoCreate());
// Binary + append
From("direct://logs")
.To(FileDsl.Write("/var/log/app")
.FileExist("Append")
.AppendChars("\n"));
```
## Fluent Builder API
| Category | Methods |
|----------|---------|
| **Consumer** | `FileDsl.Read(dir)`, `.Delay()`, `.InitialDelay()`, `.Include()`, `.Exclude()`, `.Recursive()`, `.SortBy()`, `.MaxMessagesPerPoll()`, `.MinAge()` |
| **Path filters** | `.AntInclude()`, `.AntExclude()`, `.AntFilterCaseSensitive()`, `.FilterDirectory()`, `.FilterFile()`, `.Filter()` — see [the base package](../redb.Route.GenericFile/README.md#path-filters) |
| **Poll backoff** | `.BackoffMultiplier()`, `.BackoffIdleThreshold()`, `.BackoffErrorThreshold()`, `.BackoffOnFailedExchanges()` |
| **Post-process** | `.Noop()`, `.Delete()`, `.MoveTo()`, `.MoveExisting()`, `.PreMove()` |
| **Idempotency** | `.Idempotent()`, `.DoneFileName()` |
| **Read Lock** | `.ReadLock(strategy)`, `.ReadLockTimeout()`, `.ReadLockCheckInterval()`, `.ReadLockMinAge()`, `.ReadLockMarkerFileExtension()` |
| **Producer** | `FileDsl.Write(dir)`, `.FileExist()`, `.TempPrefix()`, `.TempFileName()`, `.Charset()`, `.AutoCreate()`, `.AllowNullBody()`, `.AppendChars()`, `.EagerDeleteTargetFile()`, `.JailStartingDirectory()` |
## Read Lock Strategies
| Strategy | Description |
|----------|-------------|
| `None` | No locking |
| `MarkerFile` | Creates a `.redbLock` marker file next to the target |
| `Changed` | Waits until file size stops changing |
| `FileLock` | OS-level exclusive handle, held for the duration of processing. Windows only, see below |
| `Rename` | Renames the file while it is being processed |
`FileLock` relies on Windows share modes: while the consumer holds the file, no other process can open it, and a
file another program still holds open for writing is skipped until the next poll. Linux and macOS have advisory locks
only, so there the strategy keeps nobody out: another reader or a second consumer opens the file anyway, and a file
still being written is picked up. On Linux, the system of the Tsak worker images, use `Rename`, `MarkerFile` or
`Changed`.
## Expressions in options
Two groups, resolved at different moments:
| Option | What resolves |
|--------|---------------|
| `FileName` (producer) | Full expression engine against the exchange — `${header.x}`, `${body}`, functions |
| `MoveTo`, `PreMove`, `MoveFailed`, `IdempotentKey`, `DoneFileName` (consumer) | The file keys only: `${file:name}`, `${file:name.noext}`, `${file:ext}` and the rest of the table in the redb.Route.GenericFile README; an unknown key fails when the endpoint is created |
| `TempFileName` (producer) | The same file keys, read from the file being written: `${file:name}.part` is `order.xml.part` for `order.xml` |
The consumer options are resolved from file metadata because they are needed before the
exchange exists (idempotency, pre-move) or while it is being disposed (post-processing).
## Producer safety
The target file name usually comes from the incoming message, so by default the producer
refuses to write outside its endpoint directory: a `../` name or an absolute path throws
`UnauthorizedAccessException`. Pass `.JailStartingDirectory(false)` when writing outside
is intended.
## Part of
[redb.Route](../README.md) — ESB & EIP Framework for .NET
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `redb.route.endpoint`. The same holds for every
file-based connector built on `redb.Route.GenericFile` (`ftp`, `sftp`):
- **Consumer.** One `Consumer` span, `file read {scheme}`, per routed file. A file carries no trace context, so the span
is a root, never a child of the activity the poll loop inherited from whoever started the routes. An empty poll opens
none. A failed route, a timeout inside it included, marks it an error; our own stop does not.
- **Producer.** One `Producer` span per write, `file write {scheme}`; an error when the write fails, unless our own token
cancelled it.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span.
Path: redb-route/redb.Route.File/ReadLockStrategies.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/ReadLockStrategies.cs
----
namespace redb.Route.File;
///
/// Abstraction for read lock strategies used by the file consumer.
/// Each strategy determines how to acquire and release locks on files being polled,
/// preventing the consumer from reading a file that is still being written.
///
public interface IReadLockStrategy
{
///
/// Attempts to acquire a read lock on the file.
///
/// The file to lock.
/// Endpoint options with lock configuration.
/// Cancellation token.
/// True if the lock was acquired; false if the file should be skipped.
Task AcquireLock(FileInfo file, FileEndpointOptions options, CancellationToken ct);
///
/// Releases the read lock on the file after processing.
///
/// The file to unlock.
/// Endpoint options with lock configuration.
void ReleaseLock(FileInfo file, FileEndpointOptions options);
///
/// Path the file occupies while this lock is held. Strategies that relocate the file
/// (see ) report the new location here so the
/// consumer reads and post-processes the right path.
///
/// Path the file had before the lock was acquired.
/// The effective path. Default: unchanged.
string GetWorkPath(string originalPath) => originalPath;
///
/// Read stream already held by this lock, if any. Strategies that keep an exclusive
/// handle (see ) expose it here: reopening such a
/// file would fail against the lock this very consumer holds.
///
/// Path the file had before the lock was acquired.
/// The open stream, or null when the consumer should open the file itself.
Stream? GetLockedStream(string originalPath) => null;
}
///
/// No read lock — file is picked up immediately.
///
internal sealed class NoReadLock : IReadLockStrategy
{
public static readonly NoReadLock Instance = new();
public Task AcquireLock(FileInfo file, FileEndpointOptions options, CancellationToken ct)
=> Task.FromResult(true);
public void ReleaseLock(FileInfo file, FileEndpointOptions options) { }
}
///
/// Marker file lock strategy. Creates a *.redbLock file next to the target.
/// Other consumers skip files with an existing lock marker.
///
internal sealed class MarkerFileReadLock : IReadLockStrategy
{
public static readonly MarkerFileReadLock Instance = new();
public Task AcquireLock(FileInfo file, FileEndpointOptions options, CancellationToken ct)
{
var markerPath = file.FullName + options.ReadLockMarkerFileExtension;
if (System.IO.File.Exists(markerPath))
return Task.FromResult(false); // Another consumer holds the lock
try
{
// Create marker file atomically — if it already exists, FileMode.CreateNew throws
using var fs = new FileStream(markerPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
return Task.FromResult(true);
}
catch (IOException)
{
// Race condition: another process created the marker first
return Task.FromResult(false);
}
}
public void ReleaseLock(FileInfo file, FileEndpointOptions options)
{
var markerPath = file.FullName + options.ReadLockMarkerFileExtension;
try
{
System.IO.File.Delete(markerPath);
}
catch (IOException)
{
// Best effort
}
}
}
///
/// Changed-size read lock. Waits until the file size stops changing for
/// milliseconds.
/// Detects files still being written by monitoring size stability.
///
internal sealed class ChangedReadLock : IReadLockStrategy
{
public static readonly ChangedReadLock Instance = new();
public async Task AcquireLock(FileInfo file, FileEndpointOptions options, CancellationToken ct)
{
var timeout = options.ReadLockTimeout;
var checkInterval = options.ReadLockCheckInterval;
var minAge = options.ReadLockMinAge;
var sw = System.Diagnostics.Stopwatch.StartNew();
var lastSize = file.Length;
var lastModified = file.LastWriteTimeUtc;
var stableStart = sw.ElapsedMilliseconds;
while (sw.ElapsedMilliseconds < timeout)
{
ct.ThrowIfCancellationRequested();
await Task.Delay(checkInterval, ct).ConfigureAwait(false);
file.Refresh();
if (!file.Exists)
return false; // File was deleted while waiting
if (file.Length != lastSize || file.LastWriteTimeUtc != lastModified)
{
// File changed — reset stability timer
lastSize = file.Length;
lastModified = file.LastWriteTimeUtc;
stableStart = sw.ElapsedMilliseconds;
}
else if (sw.ElapsedMilliseconds - stableStart >= minAge)
{
// File has been stable for minAge
return true;
}
}
return false; // Timeout
}
public void ReleaseLock(FileInfo file, FileEndpointOptions options) { }
}
///
/// OS-level file lock using FileShare.None. If the file cannot be opened exclusively,
/// it means another process has it locked.
///
internal sealed class FileLockReadLock : IReadLockStrategy
{
// Holds active lock streams keyed by absolute path
private readonly System.Collections.Concurrent.ConcurrentDictionary _locks = new();
public Task AcquireLock(FileInfo file, FileEndpointOptions options, CancellationToken ct)
{
try
{
// FileShare.Delete and nothing else: other processes can neither read nor write the
// file while we hold it, but this process can still delete or move it during
// post-processing (Windows requires FILE_SHARE_DELETE on the open handle for that).
var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Delete);
_locks[file.FullName] = fs;
return Task.FromResult(true);
}
catch (IOException)
{
return Task.FromResult(false); // File is locked by another process
}
catch (UnauthorizedAccessException)
{
return Task.FromResult(false);
}
}
public void ReleaseLock(FileInfo file, FileEndpointOptions options)
{
if (_locks.TryRemove(file.FullName, out var fs))
{
fs.Dispose();
}
}
///
/// The exclusive handle acquired by this strategy. The consumer must read through it:
/// opening the file a second time would be denied by our own lock.
///
public Stream? GetLockedStream(string originalPath)
=> _locks.TryGetValue(originalPath, out var fs) ? fs : null;
}
///
/// Rename lock strategy. Tries to rename the file to a temp name; if rename fails,
/// the file is locked by another process. Renames back after processing.
///
internal sealed class RenameReadLock : IReadLockStrategy
{
private readonly System.Collections.Concurrent.ConcurrentDictionary _renames = new();
///
/// While the lock is held the file lives under the temporary name, so that is where the
/// consumer must read from and post-process.
///
public string GetWorkPath(string originalPath)
=> _renames.TryGetValue(originalPath, out var temp) ? temp : originalPath;
public Task AcquireLock(FileInfo file, FileEndpointOptions options, CancellationToken ct)
{
var tempName = file.FullName + ".redbRename";
try
{
System.IO.File.Move(file.FullName, tempName);
_renames[file.FullName] = tempName;
return Task.FromResult(true);
}
catch (IOException)
{
return Task.FromResult(false); // File in use
}
}
public void ReleaseLock(FileInfo file, FileEndpointOptions options)
{
if (_renames.TryRemove(file.FullName, out var tempName))
{
try
{
if (System.IO.File.Exists(tempName))
{
System.IO.File.Move(tempName, file.FullName);
}
}
catch (IOException)
{
// Best effort — file may have been moved/deleted during processing
}
}
}
}
///
/// Factory for creating read lock strategy instances based on configuration.
///
internal static class ReadLockFactory
{
/// Creates the appropriate read lock strategy for the given configuration.
public static IReadLockStrategy Create(ReadLockStrategy strategy) => strategy switch
{
ReadLockStrategy.None => NoReadLock.Instance,
ReadLockStrategy.MarkerFile => MarkerFileReadLock.Instance,
ReadLockStrategy.Changed => ChangedReadLock.Instance,
ReadLockStrategy.FileLock => new FileLockReadLock(),
ReadLockStrategy.Rename => new RenameReadLock(),
_ => throw new ArgumentOutOfRangeException(nameof(strategy), strategy, "Unknown read lock strategy.")
};
}
Path: redb-route/redb.Route.File/Repositories/FileClaimCheckRepository.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/Repositories/FileClaimCheckRepository.cs
----
using System;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using redb.Route.Abstractions;
namespace redb.Route.File.Repositories;
///
/// File-system-backed implementation of .
/// Each claim is stored as a binary file with a companion metadata file for TTL tracking.
/// Suitable for very large payloads and shared filesystem (NFS/SMB) scenarios.
///
public sealed class FileClaimCheckRepository : IClaimCheckRepository
{
private const string DataExtension = ".claim";
private const string MetaExtension = ".meta";
private readonly string _directory;
private readonly TimeSpan _defaultTtl;
///
/// Creates a new file-based claim check repository.
///
/// Directory to store claim files in. Created if it does not exist.
/// Default TTL for entries. Zero or null means no expiry.
public FileClaimCheckRepository(string directory, TimeSpan? defaultTtl = null)
{
ArgumentNullException.ThrowIfNull(directory);
_directory = directory;
_defaultTtl = defaultTtl ?? TimeSpan.Zero;
Directory.CreateDirectory(directory);
}
///
public async Task Store(ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default)
{
var key = Guid.NewGuid().ToString("N");
await StoreInternal(key, data, ttl, ct).ConfigureAwait(false);
return key;
}
///
public async Task Store(string key, ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await StoreInternal(key, data, ttl, ct).ConfigureAwait(false);
}
///
public async Task Retrieve(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
var dataPath = GetDataPath(key);
if (!System.IO.File.Exists(dataPath))
return null;
if (IsExpired(key))
{
DeleteFiles(key);
return null;
}
return await System.IO.File.ReadAllBytesAsync(dataPath, ct).ConfigureAwait(false);
}
///
public async Task RetrieveAndRemove(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
var dataPath = GetDataPath(key);
if (!System.IO.File.Exists(dataPath))
return null;
if (IsExpired(key))
{
DeleteFiles(key);
return null;
}
var data = await System.IO.File.ReadAllBytesAsync(dataPath, ct).ConfigureAwait(false);
DeleteFiles(key);
return data;
}
///
public Task Remove(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
DeleteFiles(key);
return Task.CompletedTask;
}
private async Task StoreInternal(string key, ReadOnlyMemory data, TimeSpan? ttl, CancellationToken ct)
{
var dataPath = GetDataPath(key);
var metaPath = GetMetaPath(key);
await System.IO.File.WriteAllBytesAsync(dataPath, data.ToArray(), ct).ConfigureAwait(false);
var effectiveTtl = ttl ?? _defaultTtl;
var meta = new ClaimMetadata
{
CreatedAt = DateTimeOffset.UtcNow,
ExpiresAt = effectiveTtl > TimeSpan.Zero
? DateTimeOffset.UtcNow + effectiveTtl
: null
};
var json = JsonSerializer.SerializeToUtf8Bytes(meta);
await System.IO.File.WriteAllBytesAsync(metaPath, json, ct).ConfigureAwait(false);
}
private bool IsExpired(string key)
{
var metaPath = GetMetaPath(key);
if (!System.IO.File.Exists(metaPath))
return false;
try
{
var json = System.IO.File.ReadAllBytes(metaPath);
var meta = JsonSerializer.Deserialize(json);
return meta?.ExpiresAt.HasValue == true && DateTimeOffset.UtcNow >= meta.ExpiresAt.Value;
}
catch
{
return false;
}
}
private void DeleteFiles(string key)
{
TryDelete(GetDataPath(key));
TryDelete(GetMetaPath(key));
}
private static void TryDelete(string path)
{
try { System.IO.File.Delete(path); }
catch (IOException) { /* best effort */ }
}
private string GetDataPath(string key) => GetSafePath(key, DataExtension);
private string GetMetaPath(string key) => GetSafePath(key, MetaExtension);
private string GetSafePath(string key, string extension)
{
var fullPath = Path.GetFullPath(Path.Combine(_directory, key + extension));
var normalizedDir = Path.GetFullPath(_directory);
var comparison = OperatingSystem.IsWindows()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
// Compare on the directory boundary: a bare prefix test would accept a sibling
// directory whose name merely starts the same way ("/claims2" against "/claims").
if (!GenericFile.GenericFileUtils.IsWithinDirectory(
normalizedDir, fullPath, Path.DirectorySeparatorChar, comparison))
{
throw new ArgumentException($"Key '{key}' resolves outside the claim check directory.", nameof(key));
}
return fullPath;
}
private sealed class ClaimMetadata
{
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? ExpiresAt { get; set; }
}
}
Path: redb-route/redb.Route.File/redb.Route.File.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.File/redb.Route.File.csproj
----
redb.Route.File
File system transport for redb.Route ESB framework. Provides polling consumer and atomic file producer with locking, idempotency, and glob filtering.
esb;messaging;file;filesystem;polling;redb
README.md