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();
}