Bundle: redb-route / redb.Route.Ftp (redb.Route.Ftp.txt), 12 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.Ftp/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.Ftp/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; namespace redb.Route.Ftp; /// /// Extension methods for registering the FTP transport in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers the in the route context so that /// ftp:// URIs are resolved. /// /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteFtp(); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// /// public static IServiceCollection AddRedbRouteFtp(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.Ftp/Fluent/FtpDsl.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.Ftp/Fluent/FtpDsl.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Ftp; /// /// Fluent API for FTP endpoints. /// /// .From(Ftp.Directory("/incoming").Host("ftp.example.com").Username("admin").Password("secret") /// .Include("*.csv").Recursive().Delete()) /// .To(Ftp.Directory("/outgoing").Host("ftp.example.com").Username("admin").Password("secret") /// .AutoCreate()) /// /// public static class Ftp { /// Creates an FTP endpoint for the given remote directory path. public static FtpBuilder Directory(string remotePath) => new(remotePath); } /// /// Fluent builder for FTP endpoint URIs. /// public sealed class FtpBuilder { private readonly string _remotePath; // Connection private string? _host; private string? _port; private string? _username; private string? _password; private string? _connectionFactory; private string? _connectionTimeout; private string? _operationTimeout; private bool _passiveMode = true; private bool _passiveModeExplicit; // TLS private bool _useFtps; private bool? _validateCertificate; // Transfer private string? _transferType; private bool _streamBody; private string? _charset; private bool _ignoreFileNotFoundOrPermissionError; private bool? _startingDirectoryMustExist; private bool _sendEmptyMessageWhenIdle; // 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; // Producer private string? _fileName; private string? _fileExist; private string? _moveExistingFileStrategy; private string? _tempPrefix; private string? _tempFileName; private bool? _autoCreate; private bool _allowNullBody; private bool? _eagerDeleteTargetFile; private bool _flatten; private bool? _jailStartingDirectory; private string? _appendChars; internal FtpBuilder(string remotePath) { ArgumentException.ThrowIfNullOrWhiteSpace(remotePath); _remotePath = remotePath; } // ── Connection ──────────────────────────────────────────────────── /// FTP server hostname. public FtpBuilder Host(IExpression host) { _host = host.ToTemplateString(); return this; } /// FTP server hostname (template string, supports ${...}). public FtpBuilder Host(string host) { _host = host; return this; } /// FTP server port. Default 21. public FtpBuilder Port(int port) { _port = port.ToString(); return this; } /// FTP server port from an expression. public FtpBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; } /// Username for authentication. public FtpBuilder Username(IExpression username) { _username = username.ToTemplateString(); return this; } /// Username for authentication (template string, supports ${...}). public FtpBuilder Username(string username) { _username = username; return this; } /// Password for authentication. public FtpBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; } /// Password for authentication (template string, supports ${...}). public FtpBuilder Password(string password) { _password = password; return this; } /// /// References a named from the route registry instead of /// putting server credentials in the URI. /// public FtpBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } /// Connection timeout in milliseconds. Default 30000. public FtpBuilder ConnectionTimeout(int ms) { _connectionTimeout = ms.ToString(); return this; } /// Connection timeout from an expression. public FtpBuilder ConnectionTimeout(IExpression ms) { _connectionTimeout = ms.ToTemplateString(); return this; } /// Operation timeout in milliseconds. Default 60000. public FtpBuilder OperationTimeout(int ms) { _operationTimeout = ms.ToString(); return this; } /// Operation timeout from an expression. public FtpBuilder OperationTimeout(IExpression ms) { _operationTimeout = ms.ToTemplateString(); return this; } /// Use passive mode for data connections. Default true. public FtpBuilder PassiveMode(bool passive = true) { _passiveMode = passive; _passiveModeExplicit = true; return this; } /// Use active mode for data connections. public FtpBuilder ActiveMode() { _passiveMode = false; _passiveModeExplicit = true; return this; } // ── TLS ─────────────────────────────────────────────────────────── /// Enable FTP over TLS (FTPS). public FtpBuilder UseFtps() { _useFtps = true; return this; } /// Validate server certificate. Default true. public FtpBuilder ValidateCertificate(bool validate = true) { _validateCertificate = validate; return this; } // ── Reconnection ────────────────────────────────────────────────── /// Maximum reconnect attempts. Default 3. public FtpBuilder MaximumReconnectAttempts(int attempts) { _maximumReconnectAttempts = attempts.ToString(); return this; } /// Reconnect delay in milliseconds. Default 1000. public FtpBuilder ReconnectDelay(int ms) { _reconnectDelay = ms.ToString(); return this; } /// Disconnect after each operation. public FtpBuilder Disconnect() { _disconnect = true; return this; } // ── Consumer ────────────────────────────────────────────────────── /// Poll delay in milliseconds. Default 60000. public FtpBuilder Delay(int ms) { _delay = ms.ToString(); return this; } /// Poll delay from an expression. public FtpBuilder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; } /// Initial delay before first poll. Default 1000. public FtpBuilder InitialDelay(int ms) { _initialDelay = ms.ToString(); return this; } /// Initial delay from an expression. public FtpBuilder InitialDelay(IExpression ms) { _initialDelay = ms.ToTemplateString(); return this; } /// Skip this many polls once a backoff threshold is hit (0 = disabled; needs a threshold). public FtpBuilder BackoffMultiplier(int value) { _backoffMultiplier = value.ToString(); return this; } /// Backoff multiplier from an expression. public FtpBuilder BackoffMultiplier(IExpression value) { _backoffMultiplier = value.ToTemplateString(); return this; } /// Consecutive idle polls (no exchange created) that arm the backoff skip (0 = disabled). public FtpBuilder BackoffIdleThreshold(int value) { _backoffIdleThreshold = value.ToString(); return this; } /// Backoff idle threshold from an expression. public FtpBuilder BackoffIdleThreshold(IExpression value) { _backoffIdleThreshold = value.ToTemplateString(); return this; } /// Consecutive failed polls (the poll itself threw) that arm the backoff skip (0 = disabled). public FtpBuilder BackoffErrorThreshold(int value) { _backoffErrorThreshold = value.ToString(); return this; } /// Backoff error threshold from an expression. public FtpBuilder BackoffErrorThreshold(IExpression value) { _backoffErrorThreshold = value.ToTemplateString(); return this; } /// Count a poll whose every created exchange failed as an error for backoff (needs BackoffErrorThreshold). public FtpBuilder BackoffOnFailedExchanges() { _backoffOnFailedExchanges = true; return this; } /// File name pattern to include (e.g. "*.csv"). public FtpBuilder Include(string pattern) { _include = pattern; return this; } /// File name pattern to exclude. public FtpBuilder 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 FtpBuilder AntInclude(string patterns) { _antInclude = patterns; return this; } /// Ant-style patterns over the relative path that drop a file ("archive/**"). public FtpBuilder AntExclude(string patterns) { _antExclude = patterns; return this; } /// Whether the Ant patterns respect case (default true). public FtpBuilder AntFilterCaseSensitive(bool value = true) { _antFilterCaseSensitive = value; return this; } /// Condition deciding whether a subdirectory is walked into at all — evaluated before it is listed. public FtpBuilder FilterDirectory(string condition) { _filterDirectory = condition; return this; } /// Condition deciding whether a polled file is taken, evaluated before it is read or moved. public FtpBuilder FilterFile(string condition) { _filterFile = condition; return this; } /// Name of an IGenericFileFilter in the route registry ("#myFilter") deciding for files and directories. public FtpBuilder Filter(string registryName) { _filter = registryName; return this; } /// Recurse into subdirectories. public FtpBuilder Recursive() { _recursive = true; return this; } /// Maximum recursion depth. 0 = unlimited. public FtpBuilder MaxDepth(int depth) { _maxDepth = depth.ToString(); return this; } /// Minimum recursion depth before yielding files. public FtpBuilder MinDepth(int depth) { _minDepth = depth.ToString(); return this; } /// Sort order: None, Name, NameDesc, Modified, ModifiedDesc, Size, SizeDesc. public FtpBuilder SortBy(string sort) { _sortBy = sort; return this; } /// Max files per poll. 0 = unlimited. public FtpBuilder MaxMessagesPerPoll(int max) { _maxMessagesPerPoll = max.ToString(); return this; } /// Minimum file age in milliseconds before processing. public FtpBuilder MinAge(long ms) { _minAge = ms.ToString(); return this; } /// Maximum file age in milliseconds. public FtpBuilder MaxAge(long ms) { _maxAge = ms.ToString(); return this; } // ── Post-processing ─────────────────────────────────────────────── /// Do nothing after processing (leave file in place). public FtpBuilder Noop() { _noop = true; return this; } /// Delete file after processing. public FtpBuilder Delete() { _delete = true; return this; } /// Move processed file to this directory. public FtpBuilder MoveTo(IExpression directory) { _moveTo = directory.ToTemplateString(); return this; } /// Move processed file to this directory (template string, supports ${...}). public FtpBuilder MoveTo(string directory) { _moveTo = directory; return this; } /// Strategy when file exists in move target: Override, Append, Fail, Ignore, Move, TryRename. public FtpBuilder MoveExisting(string strategy) { _moveExisting = strategy; return this; } /// Pre-move directory (temporary move before processing). public FtpBuilder PreMove(IExpression directory) { _preMove = directory.ToTemplateString(); return this; } /// Pre-move directory (temporary move before processing) (template string, supports ${...}). public FtpBuilder PreMove(string directory) { _preMove = directory; return this; } /// Directory for files that failed processing. public FtpBuilder MoveFailed(IExpression directory) { _moveFailed = directory.ToTemplateString(); return this; } /// Directory for files that failed processing (template string, supports ${...}). public FtpBuilder MoveFailed(string directory) { _moveFailed = directory; return this; } // ── Idempotency ─────────────────────────────────────────────────── /// Enable idempotent consumer with optional key expression. public FtpBuilder Idempotent(IExpression? key = null) { _idempotent = true; _idempotentKey = key?.ToTemplateString(); return this; } /// Enable idempotent consumer with a key (template string, supports ${...}). public FtpBuilder Idempotent(string key) { _idempotent = true; _idempotentKey = key; return this; } /// Done file name pattern. public FtpBuilder DoneFileName(IExpression name) { _doneFileName = name.ToTemplateString(); return this; } /// Done file name pattern (template string, supports ${...}). public FtpBuilder DoneFileName(string name) { _doneFileName = name; return this; } // ── Transfer ────────────────────────────────────────────────────── /// Transfer type: Binary or Ascii. public FtpBuilder TransferType(string type) { _transferType = type; return this; } /// Set exchange body to stream instead of byte[] (consumer only). public FtpBuilder StreamBody() { _streamBody = true; return this; } /// Character encoding for text mode. Default "utf-8". public FtpBuilder Charset(string charset) { _charset = charset; return this; } /// Ignore file-not-found or permission errors. public FtpBuilder IgnoreFileNotFoundOrPermissionError() { _ignoreFileNotFoundOrPermissionError = true; return this; } /// Starting directory must exist. Default true. public FtpBuilder StartingDirectoryMustExist(bool must = true) { _startingDirectoryMustExist = must; return this; } /// Send empty message when poll finds no files. public FtpBuilder SendEmptyMessageWhenIdle() { _sendEmptyMessageWhenIdle = true; return this; } // ── Producer ────────────────────────────────────────────────────── /// Output file name or expression. public FtpBuilder FileName(IExpression name) { _fileName = name.ToTemplateString(); return this; } /// Output file name (template string, supports ${...}). public FtpBuilder FileName(string name) { _fileName = name; return this; } /// Strategy when target file exists: Override, Append, Fail, Ignore, Move, TryRename. public FtpBuilder FileExist(string strategy) { _fileExist = strategy; return this; } /// Strategy for moving existing files: Backup, Timestamp, Guid. public FtpBuilder MoveExistingFileStrategy(string strategy) { _moveExistingFileStrategy = strategy; return this; } /// Temporary file prefix during write. public FtpBuilder TempPrefix(IExpression prefix) { _tempPrefix = prefix.ToTemplateString(); return this; } /// Temporary file prefix during write (template string, supports ${...}). public FtpBuilder TempPrefix(string prefix) { _tempPrefix = prefix; return this; } /// Temporary file name during write. public FtpBuilder TempFileName(IExpression name) { _tempFileName = name.ToTemplateString(); return this; } /// Temporary file name during write (template string, supports ${...}). public FtpBuilder TempFileName(string name) { _tempFileName = name; return this; } /// Auto-create target directory. Default true. public FtpBuilder AutoCreate(bool autoCreate = true) { _autoCreate = autoCreate; return this; } /// Allow sending null body. public FtpBuilder AllowNullBody() { _allowNullBody = true; return this; } /// Eagerly delete target file before writing. Default true. public FtpBuilder EagerDeleteTargetFile(bool eager = true) { _eagerDeleteTargetFile = eager; return this; } /// Flatten directory structure (single directory). public FtpBuilder Flatten() { _flatten = true; return this; } /// Jail operations within the starting directory. Default true. public FtpBuilder JailStartingDirectory(bool jail = true) { _jailStartingDirectory = jail; return this; } /// Characters to append after writing. public FtpBuilder AppendChars(string chars) { _appendChars = chars; return this; } // ── Build ───────────────────────────────────────────────────────── /// Builds the FTP endpoint URI string. public string Build() { var sb = new StringBuilder(); sb.Append("ftp:///"); 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("connectionTimeout", _connectionTimeout); AppendIf("operationTimeout", _operationTimeout); if (_passiveModeExplicit) Append("passiveMode", _passiveMode.ToString().ToLowerInvariant()); // TLS AppendBool("useFtps", _useFtps); AppendBoolExplicit("validateCertificate", _validateCertificate); // Transfer AppendIf("transferType", _transferType); AppendBool("streamBody", _streamBody); AppendIf("charset", _charset); AppendBool("ignoreFileNotFoundOrPermissionError", _ignoreFileNotFoundOrPermissionError); AppendBoolExplicit("startingDirectoryMustExist", _startingDirectoryMustExist); AppendBool("sendEmptyMessageWhenIdle", _sendEmptyMessageWhenIdle); // 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); // Producer AppendIf("fileName", _fileName); AppendIf("fileExist", _fileExist); AppendIf("moveExistingFileStrategy", _moveExistingFileStrategy); AppendIf("tempPrefix", _tempPrefix); AppendIf("tempFileName", _tempFileName); AppendBoolExplicit("autoCreate", _autoCreate); AppendBool("allowNullBody", _allowNullBody); AppendBoolExplicit("eagerDeleteTargetFile", _eagerDeleteTargetFile); AppendBool("flatten", _flatten); AppendBoolExplicit("jailStartingDirectory", _jailStartingDirectory); AppendIf("appendChars", _appendChars); return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(FtpBuilder b) => b.Build(); /// public override string ToString() => Build(); } Path: redb-route/redb.Route.Ftp/FtpComponent.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.Ftp/FtpComponent.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; using redb.Route.GenericFile; namespace redb.Route.Ftp; /// /// FTP transport component for redb.Route. /// Scheme: ftp. /// /// URI format: ftp:///remote/path?host=server&port=21&username=admin&password=secret /// /// /// Provides FTP integration powered by FluentFTP: /// polling consumer with glob filtering, idempotency, pre/post-move; /// atomic producer with temp-file upload and auto-create directories. /// Supports passive/active mode and FTPS (FTP over TLS). /// /// public sealed class FtpComponent : ComponentBase { /// public override string Scheme => "ftp"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new FtpEndpointOptions(); options.BindFromUri(uri.RawParameters); options.ResolveFilter(Context); // Named ConnectionFactory keeps the server password out of the route URI. if (!string.IsNullOrEmpty(options.ConnectionFactory)) { // A set-but-unknown name fails loud -- never a silent fallback to URI params. var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory); factory.ApplyTo(options, uri); } options.Validate(); return new FtpEndpoint(uri, this, options); } } /// /// FTP endpoint. Creates either a consumer (for polling a remote directory) /// or a producer (for uploading files). The path part of the URI is the remote base directory. /// public sealed class FtpEndpoint : EndpointBase { /// Creates an FTP endpoint. public FtpEndpoint(EndpointUri uri, FtpComponent component, FtpEndpointOptions options) : base(uri, component, options) { } /// The remote base directory path derived from the endpoint URI. public string RemotePath => NormalizeRemotePath(Uri.Path); /// Gets the endpoint options for external access. internal FtpEndpointOptions EndpointOptions => Options; /// public override IProducer CreateProducer() { return new FtpProducer(this, Options, new FtpFileOperations(Options)); } /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new FtpConsumer(this, processor, Options, new FtpFileOperations(Options)); } private static string NormalizeRemotePath(string path) { if (string.IsNullOrEmpty(path)) return "/"; while (path.Contains("//")) path = path.Replace("//", "/"); if (!path.StartsWith('/')) path = "/" + path; if (path.Length > 1 && path.EndsWith('/')) path = path[..^1]; return path; } } Path: redb-route/redb.Route.Ftp/FtpConnectionFactory.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.Ftp/FtpConnectionFactory.cs ---- using redb.Route.Abstractions; using redb.Route.GenericFile; namespace redb.Route.Ftp; /// /// Named connection factory for FTP/FTPS. Register it in the route registry and reference it by /// name from the endpoint URI (connectionFactory=my-ftp) so the server password never has /// to appear in the URI, and therefore can never reach logs, telemetry, or the dashboard. /// /// Example: /// /// context.AddToRegistry("partner-ftp", new FtpConnectionFactory /// { /// Host = "ftp.partner.com", Port = 21, UseFtps = true, /// Username = "svc-drop", /// Password = Environment.GetEnvironmentVariable("FTP_PASSWORD")! /// }); /// /// r.From("ftp://inbox?connectionFactory=partner-ftp") // no credentials in the route /// /// /// public sealed class FtpConnectionFactory : RemoteFileConnectionFactory { /// Use passive mode (default true). public bool PassiveMode { get; set; } = true; /// Use FTPS (TLS). public bool UseFtps { get; set; } /// Validate the server TLS certificate (default true). public bool ValidateCertificate { get; set; } = true; /// internal override void ApplyTo(RemoteFileEndpointOptions options, EndpointUri uri) { base.ApplyTo(options, uri); if (options is not FtpEndpointOptions ftp) return; var supplied = uri.RawParameters; if (!supplied.ContainsKey(nameof(ftp.PassiveMode))) ftp.PassiveMode = PassiveMode; if (!supplied.ContainsKey(nameof(ftp.UseFtps))) ftp.UseFtps = UseFtps; if (!supplied.ContainsKey(nameof(ftp.ValidateCertificate))) ftp.ValidateCertificate = ValidateCertificate; } } Path: redb-route/redb.Route.Ftp/FtpConsumer.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.Ftp/FtpConsumer.cs ---- using redb.Route.Abstractions; using redb.Route.GenericFile; namespace redb.Route.Ftp; /// /// FTP consumer. Polls a remote directory at regular intervals via FluentFTP, /// applies glob filters, idempotency, pre/post-move, and processes each file via the route processor. /// After successful processing, applies the configured post-processing strategy (noop/delete/move). /// Supports recursive directory scanning, min/max age filtering, done-file markers, /// and automatic reconnection. /// public sealed class FtpConsumer : RemoteFileConsumer { private readonly FtpEndpoint _endpoint; /// protected override string BasePath => _endpoint.RemotePath; /// protected override string ConsumerName => $"ftp:{Options.Host}:{Options.Port}{_endpoint.Uri.Path}"; /// Creates an FTP consumer. internal FtpConsumer(FtpEndpoint endpoint, IProcessor processor, FtpEndpointOptions options, FtpFileOperations operations) : base(endpoint, processor, options, operations) { _endpoint = endpoint; } /// protected override void SetExchangeHeaders(IMessage message, GenericFileInfo file, string workPath) { var relativePath = Operations.GetRelativePath(file.BasePath, workPath); var parentDir = Operations.GetParentPath(workPath); message.Headers[FtpHeaders.FileName] = file.Name; message.Headers[FtpHeaders.FileNameOnly] = Operations.GetFileNameWithoutExtension(file.Name); message.Headers[FtpHeaders.FileExtension] = Operations.GetExtension(file.Name); message.Headers[FtpHeaders.RemotePath] = workPath; message.Headers[FtpHeaders.RelativePath] = relativePath; message.Headers[FtpHeaders.RemoteParent] = parentDir; message.Headers[FtpHeaders.FileLength] = file.Length; message.Headers[FtpHeaders.FileLastModified] = file.LastModified; message.Headers[FtpHeaders.Host] = Options.Host; message.Headers[FtpHeaders.Port] = Options.Port; message.Headers[FtpHeaders.Username] = Options.Username; } } Path: redb-route/redb.Route.Ftp/FtpEndpointOptions.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.Ftp/FtpEndpointOptions.cs ---- using redb.Route.GenericFile; namespace redb.Route.Ftp; /// /// Endpoint options for FTP transport. All properties are auto-bound from URI query parameters. /// /// URI format: ftp:///remote/path?host=server&port=21&username=admin&password=secret&... /// /// /// Inherits shared polling, post-processing, idempotency, and producer options from /// . Adds FTP-specific: passive mode, FTPS/TLS, /// transfer type, and more. /// /// public class FtpEndpointOptions : RemoteFileEndpointOptions { /// Creates FTP endpoint options with protocol-specific defaults. public FtpEndpointOptions() { Delay = 60_000; InitialDelay = 1000; StartingDirectoryMustExist = true; } // ═══════════════════════════════════════════════════════════════════ // CONNECTION: FTP-specific // ═══════════════════════════════════════════════════════════════════ /// FTP server port. (default: 21) public override int Port { get; set; } = 21; /// /// Use passive mode for data connections. Most firewalls/NATs require passive mode. /// (default: true) /// public bool PassiveMode { get; set; } = true; // ═══════════════════════════════════════════════════════════════════ // TLS / FTPS // ═══════════════════════════════════════════════════════════════════ /// /// Enable FTP over TLS (FTPS). When true, uses explicit TLS negotiation. /// (default: false) /// public bool UseFtps { get; set; } /// /// If true, accept any server certificate (useful for self-signed certs in dev/test). /// If false, validate server certificate against system trust store. (default: true) /// public bool ValidateCertificate { get; set; } = true; // ═══════════════════════════════════════════════════════════════════ // TRANSFER OPTIONS // ═══════════════════════════════════════════════════════════════════ /// /// Transfer type: Binary (raw bytes, default) or Ascii (line-ending conversion). /// public FtpTransferType TransferType { get; set; } = FtpTransferType.Binary; /// /// If true, silently ignore file-not-found or permission errors during listing. /// (default: false) /// public bool IgnoreFileNotFoundOrPermissionError { get; set; } // ═══════════════════════════════════════════════════════════════════ // PRODUCER: FTP-specific // ═══════════════════════════════════════════════════════════════════ /// /// Strategy for moving existing files when FileExist=Move. (default: Timestamp) /// public FtpMoveExistingStrategy MoveExistingFileStrategy { get; set; } = FtpMoveExistingStrategy.Timestamp; /// /// If true, flatten nested directory structures — all files are uploaded to the base directory. /// (default: false) /// public bool Flatten { get; set; } /// /// If true, prevent the producer from writing outside the base directory. /// FileName expressions that navigate with ".." are rejected. (default: true) /// public bool JailStartingDirectory { get; set; } = true; // ═══════════════════════════════════════════════════════════════════ // VALIDATION // ═══════════════════════════════════════════════════════════════════ /// public override void Validate() { ValidateRemote(); if (string.IsNullOrWhiteSpace(Host)) throw new ArgumentException("FTP Host must be specified."); } } Path: redb-route/redb.Route.Ftp/FtpEnums.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.Ftp/FtpEnums.cs ---- namespace redb.Route.Ftp; /// /// FTP data transfer type. /// public enum FtpTransferType { /// Binary transfer — no conversion (default). Binary, /// ASCII transfer — line-ending conversion. Ascii } /// /// Strategy for moving the existing file at the producer target path before upload. /// Used when is selected. /// public enum FtpMoveExistingStrategy { /// Rename to {name}.bak (overwrite previous backup). Backup, /// Rename with timestamp suffix: {name}.yyyyMMddHHmmssfff Timestamp, /// Rename with GUID suffix: {name}.{guid} Guid } Path: redb-route/redb.Route.Ftp/FtpFileOperations.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.Ftp/FtpFileOperations.cs ---- using System.Text; using FluentFTP; using redb.Route.GenericFile; namespace redb.Route.Ftp; /// /// Implements for FTP via FluentFTP. /// Manages lifecycle through Connect/Disconnect. /// All path operations use forward-slash convention. /// internal sealed class FtpFileOperations : IRemoteFileOperations { private readonly FtpEndpointOptions _options; private AsyncFtpClient? _client; /// Creates FTP file operations for the given endpoint options. public FtpFileOperations(FtpEndpointOptions options) { ArgumentNullException.ThrowIfNull(options); _options = options; } /// The underlying FluentFTP client (null until connected). internal AsyncFtpClient? Client => _client; // ═══════════════════════════════════════════════════════════════════ // CONNECTION LIFECYCLE // ═══════════════════════════════════════════════════════════════════ /// public bool IsConnected => _client is { IsConnected: true }; /// public async Task ConnectAsync(CancellationToken ct = default) { if (_client != null) { if (_client.IsConnected) await _client.Disconnect(ct).ConfigureAwait(false); _client.Dispose(); _client = null; } _client = new AsyncFtpClient(_options.Host, _options.Username, _options.Password, _options.Port); _client.Config.DataConnectionType = _options.PassiveMode ? FtpDataConnectionType.AutoPassive : FtpDataConnectionType.AutoActive; _client.Config.ConnectTimeout = _options.ConnectionTimeout; _client.Config.DataConnectionConnectTimeout = _options.ConnectionTimeout; _client.Config.ReadTimeout = _options.OperationTimeout; _client.Config.TransferChunkSize = 65536; // transferType: Ascii asks the server for line-ending conversion, Binary moves raw bytes. // Declared and documented from day one, wired to nothing until the options sweep. var dataType = _options.TransferType == FtpTransferType.Ascii ? FtpDataType.ASCII : FtpDataType.Binary; _client.Config.UploadDataType = dataType; _client.Config.DownloadDataType = dataType; if (_options.UseFtps) { _client.Config.EncryptionMode = FtpEncryptionMode.Explicit; if (!_options.ValidateCertificate) _client.ValidateCertificate += (_, e) => e.Accept = true; } await _client.Connect(ct).ConfigureAwait(false); } /// public async Task DisconnectAsync(CancellationToken ct = default) { if (_client != null) { try { if (_client.IsConnected) await _client.Disconnect(ct).ConfigureAwait(false); } finally { _client.Dispose(); _client = null; } } } // ═══════════════════════════════════════════════════════════════════ // ENUMERATION // ═══════════════════════════════════════════════════════════════════ /// public async Task> ListFilesAsync( string directory, bool recursive, int maxDepth, int minDepth, Func? directoryFilter = null, CancellationToken ct = default) { var client = RequireClient(); var result = new List(); await EnumerateFilesAsync(client, directory, directory, 0, recursive, maxDepth, minDepth, directoryFilter, result, ct) .ConfigureAwait(false); return result; } private async Task EnumerateFilesAsync( AsyncFtpClient client, string dirPath, string basePath, int depth, bool recursive, int maxDepth, int minDepth, Func? directoryFilter, List result, CancellationToken ct) { FtpListItem[] items; try { items = await client.GetListing(dirPath, FtpListOption.Modify, ct).ConfigureAwait(false); } catch (Exception) when (_options.IgnoreFileNotFoundOrPermissionError) { return; } foreach (var item in items) { if (item.Type == FtpObjectType.Directory) { if (recursive && (maxDepth == 0 || depth < maxDepth)) { var subPath = CombinePath(dirPath, item.Name); // Asked before the descent: a directory turned down here costs no listing. if (directoryFilter != null && !directoryFilter(subPath, GetRelativePath(basePath, subPath))) continue; await EnumerateFilesAsync(client, subPath, basePath, depth + 1, recursive, maxDepth, minDepth, directoryFilter, result, ct) .ConfigureAwait(false); } } else if (item.Type == FtpObjectType.File) { if (minDepth > 0 && depth < minDepth) continue; result.Add(new GenericFileInfo { Name = item.Name, FullPath = item.FullName, BasePath = basePath, Length = item.Size, LastModified = new DateTimeOffset(item.Modified.ToUniversalTime(), TimeSpan.Zero), Depth = depth }); } } } // ═══════════════════════════════════════════════════════════════════ // READ // ═══════════════════════════════════════════════════════════════════ /// public async Task ReadAllBytesAsync(string path, CancellationToken ct = default) { var client = RequireClient(); using var ms = new MemoryStream(); await client.DownloadStream(ms, path, token: ct).ConfigureAwait(false); return ms.ToArray(); } /// public async Task OpenReadAsync(string path, CancellationToken ct = default) { var client = RequireClient(); var ms = new MemoryStream(); await client.DownloadStream(ms, path, token: ct).ConfigureAwait(false); ms.Position = 0; return ms; } // ═══════════════════════════════════════════════════════════════════ // WRITE // ═══════════════════════════════════════════════════════════════════ /// public async Task WriteAsync(string path, byte[] data, CancellationToken ct = default) { var client = RequireClient(); using var ms = new MemoryStream(data); var status = await client.UploadStream(ms, path, FtpRemoteExists.Overwrite, true, null, ct) .ConfigureAwait(false); if (status == FtpStatus.Failed) throw new IOException($"FTP upload failed: {path}"); } /// public async Task WriteAsync(string path, Stream data, CancellationToken ct = default) { var client = RequireClient(); using var ms = new MemoryStream(); await data.CopyToAsync(ms, ct).ConfigureAwait(false); ms.Position = 0; var status = await client.UploadStream(ms, path, FtpRemoteExists.Overwrite, true, null, ct) .ConfigureAwait(false); if (status == FtpStatus.Failed) throw new IOException($"FTP upload failed: {path}"); } /// public async Task AppendAsync(string path, byte[] data, CancellationToken ct = default) { var client = RequireClient(); using var ms = new MemoryStream(data); var status = await client.UploadStream(ms, path, FtpRemoteExists.AddToEnd, true, null, ct) .ConfigureAwait(false); if (status == FtpStatus.Failed) throw new IOException($"FTP append failed: {path}"); } /// public async Task AppendTextAsync(string path, string text, Encoding encoding, CancellationToken ct = default) { var data = encoding.GetBytes(text); await AppendAsync(path, data, ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // FILE OPERATIONS // ═══════════════════════════════════════════════════════════════════ /// public async Task ExistsAsync(string path, CancellationToken ct = default) { var client = RequireClient(); return await client.FileExists(path, ct).ConfigureAwait(false); } /// public async Task DeleteAsync(string path, CancellationToken ct = default) { var client = RequireClient(); await client.DeleteFile(path, ct).ConfigureAwait(false); } /// public async Task MoveAsync(string source, string destination, bool overwrite, CancellationToken ct = default) { var client = RequireClient(); if (overwrite && await client.FileExists(destination, ct).ConfigureAwait(false)) { await client.DeleteFile(destination, ct).ConfigureAwait(false); } await client.MoveFile(source, destination, FtpRemoteExists.Overwrite, ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // DIRECTORY OPERATIONS // ═══════════════════════════════════════════════════════════════════ /// public async Task CreateDirectoryAsync(string path, CancellationToken ct = default) { var client = RequireClient(); await client.CreateDirectory(path, true, ct).ConfigureAwait(false); } /// public async Task DirectoryExistsAsync(string path, CancellationToken ct = default) { var client = RequireClient(); return await client.DirectoryExists(path, ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // PATH HELPERS // ═══════════════════════════════════════════════════════════════════ /// public string CombinePath(string basePath, string relativePath) { if (string.IsNullOrEmpty(basePath)) return "/" + relativePath; if (string.IsNullOrEmpty(relativePath)) return basePath; return basePath.TrimEnd('/') + "/" + relativePath.TrimStart('/'); } /// public string GetParentPath(string path) { var lastSlash = path.LastIndexOf('/'); return lastSlash <= 0 ? "/" : path[..lastSlash]; } /// public string GetFileName(string path) { var lastSlash = path.LastIndexOf('/'); return lastSlash >= 0 ? path[(lastSlash + 1)..] : path; } /// public string GetFileNameWithoutExtension(string name) { var fileName = GetFileName(name); var dotIndex = fileName.LastIndexOf('.'); return dotIndex > 0 ? fileName[..dotIndex] : fileName; } /// public string GetExtension(string name) { var fileName = GetFileName(name); var dotIndex = fileName.LastIndexOf('.'); return dotIndex >= 0 ? fileName[dotIndex..] : ""; } /// public string GetRelativePath(string basePath, string fullPath) { if (fullPath.StartsWith(basePath, StringComparison.Ordinal)) { var relative = fullPath[basePath.Length..].TrimStart('/'); return string.IsNullOrEmpty(relative) ? fullPath : relative; } return fullPath; } /// public bool IsAbsolutePath(string path) { return path.StartsWith('/'); } // ═══════════════════════════════════════════════════════════════════ // INTERNAL // ═══════════════════════════════════════════════════════════════════ private AsyncFtpClient RequireClient() { return _client ?? throw new InvalidOperationException("FTP client is not connected. Call ConnectAsync first."); } } Path: redb-route/redb.Route.Ftp/FtpHeaders.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.Ftp/FtpHeaders.cs ---- namespace redb.Route.Ftp; /// /// Constants for exchange headers set by the FTP component. /// All prefixed with "redbFtp." to avoid collisions with other components. /// public static class FtpHeaders { /// Common prefix for all FTP component headers. public const string Prefix = "redbFtp."; // ── Headers set on the In message by the consumer ──────────────── /// Full file name with extension (e.g. "report.csv"). public const string FileName = "redbFtp.Name"; /// File name without the extension (e.g. "report"). public const string FileNameOnly = "redbFtp.NameOnly"; /// File extension including the dot (e.g. ".csv"). public const string FileExtension = "redbFtp.Extension"; /// Full remote path on the FTP server (e.g. "/upload/report.csv"). public const string RemotePath = "redbFtp.RemotePath"; /// Path relative to the polling base directory. public const string RelativePath = "redbFtp.RelativePath"; /// Parent directory on the remote server. public const string RemoteParent = "redbFtp.RemoteParent"; /// File size in bytes. public const string FileLength = "redbFtp.Length"; /// Last modified date/time as DateTimeOffset (UTC). public const string FileLastModified = "redbFtp.LastModified"; /// FTP server host that the file was retrieved from. public const string Host = "redbFtp.Host"; /// FTP server port. public const string Port = "redbFtp.Port"; /// Username used for the FTP connection. public const string Username = "redbFtp.Username"; // ── Headers set by the producer after uploading ────────────────── /// Full remote path of the file that was actually written by the producer. public const string FileNameProduced = "redbFtp.NameProduced"; } Path: redb-route/redb.Route.Ftp/FtpProducer.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.Ftp/FtpProducer.cs ---- using redb.Route.Abstractions; using redb.Route.GenericFile; namespace redb.Route.Ftp; /// /// FTP producer. Uploads exchange body to a remote file on the FTP server. /// Supports atomic upload via temp files (TempPrefix/TempFileName → rename), /// multiple file-exist strategies, dynamic file names via expressions, /// automatic directory creation, and jail-path validation. /// public sealed class FtpProducer : RemoteFileProducer { private readonly FtpEndpoint _endpoint; /// protected override string BasePath => _endpoint.RemotePath; /// protected override string FileNameProducedHeader => FtpHeaders.FileNameProduced; /// Creates an FTP producer. internal FtpProducer(FtpEndpoint endpoint, FtpEndpointOptions options, FtpFileOperations operations) : base(endpoint, options, operations) { _endpoint = endpoint; } /// 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 (FTP-specific first) var headerFileName = exchange.In.Headers.TryGetValue(FtpHeaders.FileName, out var hfn) ? hfn?.ToString() : null; // Fallback to generic file header if (string.IsNullOrEmpty(headerFileName)) { headerFileName = exchange.In.Headers.TryGetValue("redbFile.Name", out var ffn) ? ffn?.ToString() : null; } fileName = headerFileName ?? $"redb-{Guid.NewGuid():N}"; } if (Options.Flatten) { var lastSlash = fileName.LastIndexOf('/'); if (lastSlash >= 0) fileName = fileName[(lastSlash + 1)..]; } return Operations.CombinePath(BasePath, fileName); } /// protected override void ValidatePath(string targetPath) { if (!Options.JailStartingDirectory) return; var normalizedTarget = NormalizePath(targetPath); if (!GenericFileUtils.IsWithinDirectory(BasePath, normalizedTarget, '/', StringComparison.Ordinal)) { throw new InvalidOperationException( $"Producer path '{targetPath}' escapes the jail directory '{BasePath}'. " + "Set JailStartingDirectory=false to allow writing outside the base directory."); } } /// protected override async Task MoveExistingFile(string path, CancellationToken ct) { var suffix = Options.MoveExistingFileStrategy switch { FtpMoveExistingStrategy.Backup => ".bak", FtpMoveExistingStrategy.Timestamp => "." + DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmssfff"), FtpMoveExistingStrategy.Guid => "." + Guid.NewGuid().ToString("N"), _ => "." + DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmssfff") }; var backupPath = path + suffix; await Operations.MoveAsync(path, backupPath, false, ct).ConfigureAwait(false); } // ── Helpers ────────────────────────────────────────────────────── private static string NormalizePath(string path) { var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries); var stack = new Stack(); foreach (var part in parts) { if (part == "..") { if (stack.Count > 0) stack.Pop(); } else if (part != ".") { stack.Push(part); } } return "/" + string.Join("/", stack.Reverse()); } } Path: redb-route/redb.Route.Ftp/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.Ftp/README.md ---- # redb.Route.Ftp > Documentation and articles: FTP/FTPS transport for the [redb.Route](../README.md) ESB framework. Polling consumer and atomic producer powered by FluentFTP — passive/active mode, FTPS (TLS), glob filtering, idempotency, temp-file upload, recursive directories, and jail-path protection. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Ftp?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Ftp) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Quick Start ```csharp // Poll remote FTP directory .From(Ftp.Directory("/inbox") .Host("ftp.example.com") .Username("user").Password("secret") .Include("*.csv") .Delay(30000) .MoveTo("/inbox/archive") .Recursive() .Idempotent()) // Upload files atomically .To(Ftp.Directory("/outbox") .Host("ftp.example.com") .Username("user").Password("secret") .TempPrefix(".uploading-") .AutoCreate()) // FTPS with passive mode .From(Ftp.Directory("/secure") .Host("ftp.example.com") .UseFtps() .ValidateCertificate(false) .PassiveMode()) ``` ## URI Format ``` ftp:///remote/path?host=server&port=21&username=admin&password=secret¶m=value ``` The path part of the URI is the remote base directory. All other parameters go in the query string. ## Consumer The consumer polls a remote FTP directory at a configurable interval, delivers each file as an exchange, and then applies post-processing (delete / move / noop). ### Polling Pipeline 1. Connect to FTP server 2. List files in the remote directory (optionally recursive) 3. Apply filters: glob include/exclude, min/max age, idempotency, done-file check 4. Sort results (by name, date, or size) 5. For each file: pre-move → read body → invoke processor → post-process 6. On failure: move file to `moveFailed` directory (if configured) ### Consumer Headers | Header | Type | Description | |--------|------|-------------| | `redbFtp.Name` | `string` | Full file name (with extension) | | `redbFtp.NameOnly` | `string` | File name without extension | | `redbFtp.Extension` | `string` | File extension (e.g. `.csv`) | | `redbFtp.RemotePath` | `string` | Full remote path of the file | | `redbFtp.RelativePath` | `string` | Path relative to the base directory | | `redbFtp.RemoteParent` | `string` | Parent directory path | | `redbFtp.Length` | `long` | File size in bytes | | `redbFtp.LastModified` | `DateTimeOffset` | Last modified timestamp | | `redbFtp.Host` | `string` | FTP host | | `redbFtp.Port` | `int` | FTP port | | `redbFtp.Username` | `string` | FTP username | ### Post-Processing Modes | Mode | Description | |------|-------------| | `Noop()` | Leave the file in place (default) | | `Delete()` | Delete after successful processing | | `MoveTo("/archive")` | Move to another directory after processing | Only one mode can be active at a time. ### Idempotency Prevents re-processing the same file. Default key: `"{fullPath}|{lastModifiedUtc}|{length}"`. ```csharp .From(Ftp.Directory("/inbox") .Host("ftp.example.com") .Idempotent() // default key .Idempotent(Constant("${file.name}"))) // custom key expression ``` ### Done Files Only process a file when a companion "done" marker exists: ```csharp .From(Ftp.Directory("/inbox") .DoneFileName(Constant("${file:name}.done"))) ``` Supports `${file:name}` and `${file:name.noext}` substitutions. ## Producer The producer uploads files to the FTP server using an atomic temp-file-then-rename strategy. ### Write Pipeline 1. Resolve target file name (from options, header, or auto-generated GUID) 2. Validate path against jail directory 3. Create parent directories if `autoCreate=true` 4. Write body to a temp file (configurable prefix/name) 5. Handle existing file (Override / Append / Fail / Ignore / Move / TryRename) 6. Atomically rename temp file to target ### File Name Resolution Priority order: 1. `FileName` option (dynamic expression) 2. `redbFtp.Name` header 3. `redbFile.Name` header (generic file header) 4. Auto-generated: `redb-{GUID}` ### File Exist Strategies | Strategy | Description | |----------|-------------| | `Override` | Overwrite existing file (default) | | `Append` | Append to existing file | | `Fail` | Throw exception | | `Ignore` | Skip silently | | `Move` | Rename existing file before writing | | `TryRename` | Try alternate names | ### Move Existing Strategies When `FileExist=Move`, the existing file is renamed with a suffix: | Strategy | Suffix Example | |----------|---------------| | `Timestamp` | `.20260405143022567` (default) | | `Backup` | `.bak` | | `Guid` | `.a1b2c3d4e5f6...` | ### Jail Path Protection By default (`jailStartingDirectory=true`), the producer rejects any path that resolves outside the base directory via `..` traversal. Set `JailStartingDirectory(false)` to disable. ### Flatten When `flatten=true`, directory components in the file name are stripped — only the base name is used for the target path. ### Producer Header | Header | Description | |--------|-------------| | `redbFtp.NameProduced` | Full path of the written file | ## FTPS (FTP over TLS) ```csharp .From(Ftp.Directory("/secure") .Host("ftp.example.com") .UseFtps() // Explicit TLS .ValidateCertificate(false)) // Skip certificate validation ``` Uses `FtpEncryptionMode.Explicit`. Certificate validation is enabled by default. ## Data Connection Mode ```csharp .From(Ftp.Directory("/data") .PassiveMode()) // default — AutoPassive .From(Ftp.Directory("/data") .ActiveMode()) // AutoActive ``` ## Fluent Builder API | Category | Methods | |----------|---------| | **Connection** | `.Host()`, `.Port()`, `.Username()`, `.Password()`, `.ConnectionTimeout()`, `.OperationTimeout()`, `.PassiveMode()`, `.ActiveMode()` | | **TLS** | `.UseFtps()`, `.ValidateCertificate()` | | **Reconnect** | `.MaximumReconnectAttempts()`, `.ReconnectDelay()`, `.Disconnect()` | | **Consumer** | `.Delay()`, `.InitialDelay()`, `.Include()`, `.Exclude()`, `.Recursive()`, `.MaxDepth()`, `.MinDepth()`, `.SortBy()`, `.MaxMessagesPerPoll()`, `.MinAge()`, `.MaxAge()` | | **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()`, `.MoveFailed()` | | **Idempotency** | `.Idempotent()`, `.DoneFileName()` | | **Transfer** | `.TransferType()` (Binary/Ascii), `.StreamBody()`, `.Charset()`, `.IgnoreFileNotFoundOrPermissionError()`, `.StartingDirectoryMustExist()`, `.SendEmptyMessageWhenIdle()` | | **Producer** | `.FileName()`, `.FileExist()`, `.MoveExistingFileStrategy()`, `.TempPrefix()`, `.TempFileName()`, `.AutoCreate()`, `.AllowNullBody()`, `.EagerDeleteTargetFile()`, `.Flatten()`, `.JailStartingDirectory()`, `.AppendChars()` | Most builder methods accept both constant values and `IExpression` for runtime resolution. ## Configuration Reference ### Connection | Parameter | Default | Description | |-----------|---------|-------------| | `host` | `localhost` | FTP server hostname | | `port` | `21` | FTP server port | | `username` | — | FTP username | | `password` | — | FTP password | | `connectionTimeout` | `30000` | Connection timeout (ms) | | `operationTimeout` | `60000` | Operation timeout (ms) | | `passiveMode` | `true` | Use passive data connection | | `useFtps` | `false` | Enable FTPS (Explicit TLS) | | `validateCertificate` | `true` | Validate server certificate | | `transferType` | `Binary` | `Binary` or `Ascii` | ### Reconnection | Parameter | Default | Description | |-----------|---------|-------------| | `maximumReconnectAttempts` | `3` | Max reconnect attempts | | `reconnectDelay` | `1000` | Delay between reconnect attempts (ms) | | `disconnect` | `false` | Disconnect after each poll/write | ### Consumer / Polling | Parameter | Default | Description | |-----------|---------|-------------| | `delay` | `60000` | Poll interval (ms) | | `initialDelay` | `1000` | Delay before first poll (ms) | | `include` | — | Glob include pattern (e.g. `*.csv,*.xml`) | | `exclude` | — | Glob exclude pattern | | `antInclude` | — | Ant patterns over the path relative to the polled directory (`TYPE_A/outbox/*.csv`): `*` stops at a separator, `**` spans levels. This is what picks directories out of a recursive poll | | `antExclude` | — | Ant patterns over the relative path that drop a file (`archive/**`) | | `antFilterCaseSensitive` | `true` | Whether the Ant patterns respect case | | `filterDirectory` | — | Condition over a subdirectory, evaluated before it is listed; false leaves it and everything below unread | | `filterFile` | — | Condition over a polled file, evaluated before it is read, moved or deleted | | `filter` | — | Name of an `IGenericFileFilter` in the registry (`#myFilter`) deciding for files and directories | | `recursive` | `false` | Recurse into subdirectories | | `maxDepth` | `0` | Max recursion depth (0 = unlimited) | | `minDepth` | `0` | Min depth for file selection | | `sortBy` | `None` | Sort order: `Name`, `NameDesc`, `Modified`, `ModifiedDesc`, `Size`, `SizeDesc` | | `maxMessagesPerPoll` | `0` | Max files per poll (0 = unlimited) | | `minAge` | `0` | Min file age (ms) | | `maxAge` | `0` | Max file age (ms, 0 = unlimited) | | `startingDirectoryMustExist` | `true` | Fail if base directory doesn't exist | | `sendEmptyMessageWhenIdle` | `false` | Send empty exchange when no files found | ### Consumer / Post-Processing | Parameter | Default | Description | |-----------|---------|-------------| | `noop` | `false` | Leave file in place | | `delete` | `false` | Delete after processing | | `moveTo` | — | Move after processing (expression) | | `preMove` | — | Move before processing (expression) | | `moveFailed` | — | Move on failure (expression) | | `moveExisting` | `Override` | How to handle existing file at move target | ### Consumer / Idempotency | Parameter | Default | Description | |-----------|---------|-------------| | `idempotent` | `false` | Enable idempotent consumer | | `idempotentKey` | — | Custom idempotency key expression | | `doneFileName` | — | Done-file pattern (e.g. `${file:name}.done`) | ### Consumer / Body | Parameter | Default | Description | |-----------|---------|-------------| | `streamBody` | `false` | `true` → body is `Stream`, `false` → `byte[]` | | `charset` | `utf-8` | Character encoding | ### Producer | Parameter | Default | Description | |-----------|---------|-------------| | `fileName` | — | Target file name (expression) | | `fileExist` | `Override` | Strategy: `Override`, `Append`, `Fail`, `Ignore`, `Move`, `TryRename` | | `moveExistingFileStrategy` | `Timestamp` | Rename strategy for existing files: `Backup`, `Timestamp`, `Guid` | | `tempPrefix` | — | Temp file prefix (expression) | | `tempFileName` | — | Temp file name in the target directory; file keys read the file being written (`${file:name}.part`) | | `autoCreate` | `true` | Auto-create parent directories | | `allowNullBody` | `false` | Allow null body (creates empty file) | | `eagerDeleteTargetFile` | `true` | Delete target before writing | | `flatten` | `false` | Strip directory components from file name | | `jailStartingDirectory` | `true` | Reject paths outside the base directory | | `appendChars` | — | Characters to append after each write | | `ignoreFileNotFoundOrPermissionError` | `false` | Ignore listing errors for missing/inaccessible dirs | ## DI Registration ```csharp services.AddRedbRouteFtp(); ``` ## Requirements - .NET 10.0 / 11.0. The 4.7 line stays on .NET 8, 9 and 10 for applications that cannot move yet. - `FluentFTP` 54.1.0 - `redb.Route.GenericFile` (shared file transport abstractions) ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new FtpConnectionFactory { Host = "ftp.partner.com", Username = "exchange", Password = secrets.FtpPassword, }); // ftp://inbox?connectionFactory=prod ``` ## Tracing As every connector built on `redb.Route.GenericFile` (see the `redb.Route.File` README): a root `Consumer` span, `file read ftp`, per routed file, none for an empty poll, an error when the route fails; a `Producer` span per upload, `file write ftp`, an error when it fails. `RouteEngineOptions.EnableTelemetry = false` opens neither. Path: redb-route/redb.Route.Ftp/redb.Route.Ftp.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.Ftp/redb.Route.Ftp.csproj ---- redb.Route.Ftp FTP/FTPS transport for redb.Route ESB framework. Polling consumer and atomic producer with FluentFTP — passive/active mode, TLS, glob filtering, idempotency, temp-file upload, recursive directories. esb;messaging;ftp;ftps;file-transfer;polling;redb README.md