Path: redb-route/redb.Route.Sftp/Fluent/SftpDsl.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.Sftp/Fluent/SftpDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.Sftp;
///
/// Fluent API for SFTP endpoints.
///
/// .From(Sftp.Directory("/incoming").Host("sftp.example.com").Username("admin").Password("secret")
/// .Include("*.csv").Recursive().Delete())
/// .To(Sftp.Directory("/outgoing").Host("sftp.example.com").Username("admin").Password("secret")
/// .AutoCreate())
///
///
public static class Sftp
{
/// Creates an SFTP endpoint for the given remote directory path.
public static SftpBuilder Directory(string remotePath) => new(remotePath);
}
///
/// Fluent builder for SFTP endpoint URIs.
///
public sealed class SftpBuilder
{
private readonly string _remotePath;
// Connection
private string? _host;
private string? _port;
private string? _username;
private string? _password;
private string? _connectionFactory;
private string? _privateKeyPath;
private string? _privateKeyPassphrase;
private bool _useKeyboardInteractive;
private string? _preferredAuthentications;
private string? _serverFingerprint;
private bool _strictHostKeyChecking;
private string? _knownHostsFile;
private string? _connectionTimeout;
private string? _operationTimeout;
private string? _keepAliveInterval;
private string? _bufferSize;
private bool _compression;
// Proxy
private string? _proxyType;
private string? _proxyHost;
private string? _proxyPort;
private string? _proxyUsername;
private string? _proxyPassword;
// Reconnection
private string? _maximumReconnectAttempts;
private string? _reconnectDelay;
private bool _disconnect;
// Consumer
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? _maxDepth;
private string? _minDepth;
private string? _sortBy;
private string? _maxMessagesPerPoll;
private string? _backoffMultiplier;
private string? _backoffIdleThreshold;
private string? _backoffErrorThreshold;
private bool _backoffOnFailedExchanges;
private string? _minAge;
private string? _maxAge;
// Post-processing
private bool _noop;
private bool _delete;
private string? _moveTo;
private string? _moveExisting;
private string? _preMove;
private string? _moveFailed;
// Idempotency
private bool _idempotent;
private string? _idempotentKey;
private string? _doneFileName;
// Transfer
private bool _streamBody;
private string? _charset;
private string? _separator;
private bool _ignoreFileNotFoundOrPermissionError;
private bool? _startingDirectoryMustExist;
private bool _directoryMustExist;
private bool _sendEmptyMessageWhenIdle;
// Producer
private string? _fileName;
private string? _fileExist;
private string? _moveExistingFileStrategy;
private string? _tempPrefix;
private string? _tempFileName;
private string? _chmod;
private string? _chmodDirectory;
private bool? _autoCreate;
private bool _allowNullBody;
private bool? _eagerDeleteTargetFile;
private bool _keepLastModified;
private bool _flatten;
private bool? _jailStartingDirectory;
private string? _appendChars;
internal SftpBuilder(string remotePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(remotePath);
_remotePath = remotePath;
}
// ── Connection ────────────────────────────────────────────────────
/// SFTP server hostname. Default "localhost".
public SftpBuilder Host(IExpression host) { _host = host.ToTemplateString(); return this; }
/// SFTP server hostname (template string, supports ${...}).
public SftpBuilder Host(string host) { _host = host; return this; }
/// SFTP server port. Default 22.
public SftpBuilder Port(int port) { _port = port.ToString(); return this; }
/// SFTP server port from an expression.
public SftpBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; }
/// Username for authentication.
public SftpBuilder Username(IExpression username) { _username = username.ToTemplateString(); return this; }
/// Username for authentication (template string, supports ${...}).
public SftpBuilder Username(string username) { _username = username; return this; }
/// Password for authentication.
public SftpBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; }
/// Password for authentication (template string, supports ${...}).
public SftpBuilder Password(string password) { _password = password; return this; }
///
/// References a named from the route registry instead of
/// putting the password / key passphrase / proxy password in the URI.
///
public SftpBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Path to private key file.
public SftpBuilder PrivateKey(IExpression path, IExpression? passphrase = null)
{
_privateKeyPath = path.ToTemplateString(); _privateKeyPassphrase = passphrase?.ToTemplateString(); return this;
}
/// Enable keyboard-interactive authentication.
public SftpBuilder UseKeyboardInteractive() { _useKeyboardInteractive = true; return this; }
/// Preferred authentication methods, comma-separated.
public SftpBuilder PreferredAuthentications(string methods) { _preferredAuthentications = methods; return this; }
/// Expected server host key fingerprint.
public SftpBuilder ServerFingerprint(IExpression fingerprint) { _serverFingerprint = fingerprint.ToTemplateString(); return this; }
/// Expected server host key fingerprint (template string, supports ${...}).
public SftpBuilder ServerFingerprint(string fingerprint) { _serverFingerprint = fingerprint; return this; }
/// Enable strict host key checking.
public SftpBuilder StrictHostKeyChecking() { _strictHostKeyChecking = true; return this; }
/// Path to known_hosts file.
public SftpBuilder KnownHostsFile(string path) { _knownHostsFile = path; return this; }
/// Connection timeout in milliseconds. Default 30000.
public SftpBuilder ConnectionTimeout(int ms) { _connectionTimeout = ms.ToString(); return this; }
/// Connection timeout from an expression.
public SftpBuilder ConnectionTimeout(IExpression ms) { _connectionTimeout = ms.ToTemplateString(); return this; }
/// Operation timeout in milliseconds. Default 60000.
public SftpBuilder OperationTimeout(int ms) { _operationTimeout = ms.ToString(); return this; }
/// Operation timeout from an expression.
public SftpBuilder OperationTimeout(IExpression ms) { _operationTimeout = ms.ToTemplateString(); return this; }
/// Keep-alive interval in milliseconds. 0 = disabled.
public SftpBuilder KeepAliveInterval(int ms) { _keepAliveInterval = ms.ToString(); return this; }
/// Keep-alive interval from an expression.
public SftpBuilder KeepAliveInterval(IExpression ms) { _keepAliveInterval = ms.ToTemplateString(); return this; }
/// Buffer size for transfers. Default 32768.
public SftpBuilder BufferSize(int bytes) { _bufferSize = bytes.ToString(); return this; }
/// Buffer size from an expression.
public SftpBuilder BufferSize(IExpression bytes) { _bufferSize = bytes.ToTemplateString(); return this; }
/// Enable SSH compression.
public SftpBuilder Compression() { _compression = true; return this; }
// ── Proxy ─────────────────────────────────────────────────────────
/// Proxy configuration: type (None, Socks4, Socks5, Http), host, and port.
public SftpBuilder Proxy(string type, IExpression host, int port = 1080)
{
_proxyType = type; _proxyHost = host.ToTemplateString(); _proxyPort = port.ToString(); return this;
}
/// Proxy authentication.
public SftpBuilder ProxyAuth(IExpression username, IExpression password)
{
_proxyUsername = username.ToTemplateString(); _proxyPassword = password.ToTemplateString(); return this;
}
// ── Reconnection ──────────────────────────────────────────────────
/// Maximum reconnect attempts. Default 3.
public SftpBuilder MaximumReconnectAttempts(int attempts) { _maximumReconnectAttempts = attempts.ToString(); return this; }
/// Maximum reconnect attempts from an expression.
public SftpBuilder MaximumReconnectAttempts(IExpression attempts) { _maximumReconnectAttempts = attempts.ToTemplateString(); return this; }
/// Reconnect delay in milliseconds. Default 1000.
public SftpBuilder ReconnectDelay(int ms) { _reconnectDelay = ms.ToString(); return this; }
/// Reconnect delay from an expression.
public SftpBuilder ReconnectDelay(IExpression ms) { _reconnectDelay = ms.ToTemplateString(); return this; }
/// Disconnect after each operation.
public SftpBuilder Disconnect() { _disconnect = true; return this; }
// ── Consumer ──────────────────────────────────────────────────────
/// Poll delay in milliseconds. Default 60000.
public SftpBuilder Delay(int ms) { _delay = ms.ToString(); return this; }
/// Poll delay from an expression.
public SftpBuilder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; }
/// Initial delay before first poll. Default 1000.
public SftpBuilder InitialDelay(int ms) { _initialDelay = ms.ToString(); return this; }
/// Initial delay from an expression.
public SftpBuilder InitialDelay(IExpression ms) { _initialDelay = ms.ToTemplateString(); return this; }
/// Skip this many polls once a backoff threshold is hit (0 = disabled; needs a threshold).
public SftpBuilder BackoffMultiplier(int value) { _backoffMultiplier = value.ToString(); return this; }
/// Backoff multiplier from an expression.
public SftpBuilder BackoffMultiplier(IExpression value) { _backoffMultiplier = value.ToTemplateString(); return this; }
/// Consecutive idle polls (no exchange created) that arm the backoff skip (0 = disabled).
public SftpBuilder BackoffIdleThreshold(int value) { _backoffIdleThreshold = value.ToString(); return this; }
/// Backoff idle threshold from an expression.
public SftpBuilder BackoffIdleThreshold(IExpression value) { _backoffIdleThreshold = value.ToTemplateString(); return this; }
/// Consecutive failed polls (the poll itself threw) that arm the backoff skip (0 = disabled).
public SftpBuilder BackoffErrorThreshold(int value) { _backoffErrorThreshold = value.ToString(); return this; }
/// Backoff error threshold from an expression.
public SftpBuilder BackoffErrorThreshold(IExpression value) { _backoffErrorThreshold = value.ToTemplateString(); return this; }
/// Count a poll whose every created exchange failed as an error for backoff (needs BackoffErrorThreshold).
public SftpBuilder BackoffOnFailedExchanges() { _backoffOnFailedExchanges = true; return this; }
/// File name pattern to include (e.g. "*.csv").
public SftpBuilder Include(string pattern) { _include = pattern; return this; }
/// File name pattern to exclude.
public SftpBuilder 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 SftpBuilder AntInclude(string patterns) { _antInclude = patterns; return this; }
/// Ant-style patterns over the relative path that drop a file ("archive/**").
public SftpBuilder AntExclude(string patterns) { _antExclude = patterns; return this; }
/// Whether the Ant patterns respect case (default true).
public SftpBuilder AntFilterCaseSensitive(bool value = true) { _antFilterCaseSensitive = value; return this; }
/// Condition deciding whether a subdirectory is walked into at all — evaluated before it is listed.
public SftpBuilder FilterDirectory(string condition) { _filterDirectory = condition; return this; }
/// Condition deciding whether a polled file is taken, evaluated before it is read or moved.
public SftpBuilder FilterFile(string condition) { _filterFile = condition; return this; }
/// Name of an IGenericFileFilter in the route registry ("#myFilter") deciding for files and directories.
public SftpBuilder Filter(string registryName) { _filter = registryName; return this; }
/// Recurse into subdirectories.
public SftpBuilder Recursive() { _recursive = true; return this; }
/// Maximum recursion depth. 0 = unlimited.
public SftpBuilder MaxDepth(int depth) { _maxDepth = depth.ToString(); return this; }
/// Maximum recursion depth from an expression.
public SftpBuilder MaxDepth(IExpression depth) { _maxDepth = depth.ToTemplateString(); return this; }
/// Minimum recursion depth before yielding files.
public SftpBuilder MinDepth(int depth) { _minDepth = depth.ToString(); return this; }
/// Minimum recursion depth from an expression.
public SftpBuilder MinDepth(IExpression depth) { _minDepth = depth.ToTemplateString(); return this; }
/// Sort order: None, Name, NameDesc, Modified, ModifiedDesc, Size, SizeDesc.
public SftpBuilder SortBy(string sort) { _sortBy = sort; return this; }
/// Max files per poll. 0 = unlimited.
public SftpBuilder MaxMessagesPerPoll(int max) { _maxMessagesPerPoll = max.ToString(); return this; }
/// Max files per poll from an expression.
public SftpBuilder MaxMessagesPerPoll(IExpression max) { _maxMessagesPerPoll = max.ToTemplateString(); return this; }
/// Minimum file age in milliseconds before processing.
public SftpBuilder MinAge(long ms) { _minAge = ms.ToString(); return this; }
/// Minimum file age from an expression.
public SftpBuilder MinAge(IExpression ms) { _minAge = ms.ToTemplateString(); return this; }
/// Maximum file age in milliseconds.
public SftpBuilder MaxAge(long ms) { _maxAge = ms.ToString(); return this; }
/// Maximum file age from an expression.
public SftpBuilder MaxAge(IExpression ms) { _maxAge = ms.ToTemplateString(); return this; }
// ── Post-processing ───────────────────────────────────────────────
/// Do nothing after processing (leave file in place).
public SftpBuilder Noop() { _noop = true; return this; }
/// Delete file after processing.
public SftpBuilder Delete() { _delete = true; return this; }
/// Move processed file to this directory.
public SftpBuilder MoveTo(IExpression directory) { _moveTo = directory.ToTemplateString(); return this; }
/// Move processed file to this directory (template string, supports ${...}).
public SftpBuilder MoveTo(string directory) { _moveTo = directory; return this; }
/// Strategy when file exists in move target: Override, Append, Fail, Ignore, Move, TryRename.
public SftpBuilder MoveExisting(string strategy) { _moveExisting = strategy; return this; }
/// Pre-move directory (temporary move before processing).
public SftpBuilder PreMove(IExpression directory) { _preMove = directory.ToTemplateString(); return this; }
/// Pre-move directory (template string, supports ${...}).
public SftpBuilder PreMove(string directory) { _preMove = directory; return this; }
/// Directory for files that failed processing.
public SftpBuilder MoveFailed(IExpression directory) { _moveFailed = directory.ToTemplateString(); return this; }
/// Directory for files that failed processing (template string, supports ${...}).
public SftpBuilder MoveFailed(string directory) { _moveFailed = directory; return this; }
// ── Idempotency ───────────────────────────────────────────────────
/// Enable idempotent consumer with optional key expression.
public SftpBuilder Idempotent(IExpression? key = null) { _idempotent = true; _idempotentKey = key?.ToTemplateString(); return this; }
/// Enable idempotent consumer with a key (template string, supports ${...}).
public SftpBuilder Idempotent(string key) { _idempotent = true; _idempotentKey = key; return this; }
/// Done file name pattern.
public SftpBuilder DoneFileName(IExpression name) { _doneFileName = name.ToTemplateString(); return this; }
/// Done file name pattern (template string, supports ${...}).
public SftpBuilder DoneFileName(string name) { _doneFileName = name; return this; }
// ── Transfer ──────────────────────────────────────────────────────
/// Set exchange body to SftpFileStream instead of byte[] (consumer only).
public SftpBuilder StreamBody() { _streamBody = true; return this; }
/// Character encoding for text mode. Default "utf-8".
public SftpBuilder Charset(string charset) { _charset = charset; return this; }
/// Input path normalization: Auto (backslashes become "/") or Unix (byte-for-byte).
public SftpBuilder Separator(string sep) { _separator = sep; return this; }
/// Ignore file-not-found or permission errors.
public SftpBuilder IgnoreFileNotFoundOrPermissionError() { _ignoreFileNotFoundOrPermissionError = true; return this; }
/// Starting directory must exist. Default true.
public SftpBuilder StartingDirectoryMustExist(bool must = true) { _startingDirectoryMustExist = must; return this; }
/// Target directory must exist (producer).
public SftpBuilder DirectoryMustExist() { _directoryMustExist = true; return this; }
/// Send empty message when poll finds no files.
public SftpBuilder SendEmptyMessageWhenIdle() { _sendEmptyMessageWhenIdle = true; return this; }
// ── Producer ──────────────────────────────────────────────────────
/// Output file name or expression (e.g. Header("CamelFileName")).
public SftpBuilder FileName(IExpression name) { _fileName = name.ToTemplateString(); return this; }
/// Output file name (template string, supports ${...}).
public SftpBuilder FileName(string name) { _fileName = name; return this; }
/// Strategy when target file exists: Override, Append, Fail, Ignore, Move, TryRename.
public SftpBuilder FileExist(string strategy) { _fileExist = strategy; return this; }
/// Strategy for moving existing files: Backup, Timestamp, Guid.
public SftpBuilder MoveExistingFileStrategy(string strategy) { _moveExistingFileStrategy = strategy; return this; }
/// Temporary file prefix during write.
public SftpBuilder TempPrefix(IExpression prefix) { _tempPrefix = prefix.ToTemplateString(); return this; }
/// Temporary file prefix during write (template string, supports ${...}).
public SftpBuilder TempPrefix(string prefix) { _tempPrefix = prefix; return this; }
/// Temporary file name during write.
public SftpBuilder TempFileName(IExpression name) { _tempFileName = name.ToTemplateString(); return this; }
/// Temporary file name during write (template string, supports ${...}).
public SftpBuilder TempFileName(string name) { _tempFileName = name; return this; }
/// File permissions (e.g. "644").
public SftpBuilder Chmod(string permissions) { _chmod = permissions; return this; }
/// Directory permissions (e.g. "755").
public SftpBuilder ChmodDirectory(string permissions) { _chmodDirectory = permissions; return this; }
/// Auto-create target directory. Default true.
public SftpBuilder AutoCreate(bool autoCreate = true) { _autoCreate = autoCreate; return this; }
/// Allow sending null body.
public SftpBuilder AllowNullBody() { _allowNullBody = true; return this; }
/// Eagerly delete target file before writing. Default true.
public SftpBuilder EagerDeleteTargetFile(bool eager = true) { _eagerDeleteTargetFile = eager; return this; }
/// Preserve last modified timestamp.
public SftpBuilder KeepLastModified() { _keepLastModified = true; return this; }
/// Flatten directory structure (single directory).
public SftpBuilder Flatten() { _flatten = true; return this; }
/// Jail operations within the starting directory. Default true.
public SftpBuilder JailStartingDirectory(bool jail = true) { _jailStartingDirectory = jail; return this; }
/// Characters to append after writing.
public SftpBuilder AppendChars(string chars) { _appendChars = chars; return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the SFTP endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("sftp:///");
sb.Append(_remotePath.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());
}
// Connection
AppendIf("host", _host);
AppendIf("port", _port);
AppendIf("username", _username);
AppendIf("password", _password);
AppendIf("connectionFactory", _connectionFactory);
AppendIf("privateKeyPath", _privateKeyPath);
AppendIf("privateKeyPassphrase", _privateKeyPassphrase);
AppendBool("useKeyboardInteractive", _useKeyboardInteractive);
AppendIf("preferredAuthentications", _preferredAuthentications);
AppendIf("serverFingerprint", _serverFingerprint);
AppendBool("strictHostKeyChecking", _strictHostKeyChecking);
AppendIf("knownHostsFile", _knownHostsFile);
AppendIf("connectionTimeout", _connectionTimeout);
AppendIf("operationTimeout", _operationTimeout);
AppendIf("keepAliveInterval", _keepAliveInterval);
AppendIf("bufferSize", _bufferSize);
AppendBool("compression", _compression);
// Proxy
AppendIf("proxyType", _proxyType);
AppendIf("proxyHost", _proxyHost);
AppendIf("proxyPort", _proxyPort);
AppendIf("proxyUsername", _proxyUsername);
AppendIf("proxyPassword", _proxyPassword);
// Reconnection
AppendIf("maximumReconnectAttempts", _maximumReconnectAttempts);
AppendIf("reconnectDelay", _reconnectDelay);
AppendBool("disconnect", _disconnect);
// 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("maxDepth", _maxDepth);
AppendIf("minDepth", _minDepth);
AppendIf("sortBy", _sortBy);
AppendIf("maxMessagesPerPoll", _maxMessagesPerPoll);
AppendIf("backoffMultiplier", _backoffMultiplier);
AppendIf("backoffIdleThreshold", _backoffIdleThreshold);
AppendIf("backoffErrorThreshold", _backoffErrorThreshold);
AppendBool("backoffOnFailedExchanges", _backoffOnFailedExchanges);
AppendIf("minAge", _minAge);
AppendIf("maxAge", _maxAge);
// Post-processing
AppendBool("noop", _noop);
AppendBool("delete", _delete);
AppendIf("moveTo", _moveTo);
AppendIf("moveExisting", _moveExisting);
AppendIf("preMove", _preMove);
AppendIf("moveFailed", _moveFailed);
// Idempotency
AppendBool("idempotent", _idempotent);
AppendIf("idempotentKey", _idempotentKey);
AppendIf("doneFileName", _doneFileName);
// Transfer
AppendBool("streamBody", _streamBody);
AppendIf("charset", _charset);
AppendIf("separator", _separator);
AppendBool("ignoreFileNotFoundOrPermissionError", _ignoreFileNotFoundOrPermissionError);
AppendBoolExplicit("startingDirectoryMustExist", _startingDirectoryMustExist);
AppendBool("directoryMustExist", _directoryMustExist);
AppendBool("sendEmptyMessageWhenIdle", _sendEmptyMessageWhenIdle);
// Producer
AppendIf("fileName", _fileName);
AppendIf("fileExist", _fileExist);
AppendIf("moveExistingFileStrategy", _moveExistingFileStrategy);
AppendIf("tempPrefix", _tempPrefix);
AppendIf("tempFileName", _tempFileName);
AppendIf("chmod", _chmod);
AppendIf("chmodDirectory", _chmodDirectory);
AppendBoolExplicit("autoCreate", _autoCreate);
AppendBool("allowNullBody", _allowNullBody);
AppendBoolExplicit("eagerDeleteTargetFile", _eagerDeleteTargetFile);
AppendBool("keepLastModified", _keepLastModified);
AppendBool("flatten", _flatten);
AppendBoolExplicit("jailStartingDirectory", _jailStartingDirectory);
AppendIf("appendChars", _appendChars);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(SftpBuilder b) => b.Build();
///
public override string ToString() => Build();
}