Bundle: redb-route / root files (_root.txt), 18 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/.editorconfig 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/.editorconfig ---- # editorconfig.org root = true [*] indent_style = space indent_size = 4 end_of_line = crlf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.{csproj,props,targets,xml,json,yml,yaml}] indent_size = 2 [*.md] trim_trailing_whitespace = false [*.cs] # Organize usings dotnet_sort_system_directives_first = true dotnet_separate_import_directive_groups = false # this. qualification dotnet_style_qualification_for_field = false:suggestion dotnet_style_qualification_for_property = false:suggestion dotnet_style_qualification_for_method = false:suggestion dotnet_style_qualification_for_event = false:suggestion # Language keywords vs BCL types dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion dotnet_style_predefined_type_for_member_access = true:suggestion # var preferences csharp_style_var_for_built_in_types = false:suggestion csharp_style_var_when_type_is_apparent = true:suggestion csharp_style_var_elsewhere = true:suggestion # Expression-bodied members csharp_style_expression_bodied_methods = when_on_single_line:suggestion csharp_style_expression_bodied_constructors = false:suggestion csharp_style_expression_bodied_properties = true:suggestion csharp_style_expression_bodied_accessors = true:suggestion csharp_style_expression_bodied_lambdas = true:suggestion # Pattern matching csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion csharp_style_pattern_matching_over_as_with_null_check = true:suggestion # Null checking csharp_style_throw_expression = true:suggestion csharp_style_conditional_delegate_call = true:suggestion # Braces csharp_prefer_braces = when_multiline:suggestion # New line preferences csharp_new_line_before_open_brace = all csharp_new_line_before_else = true csharp_new_line_before_catch = true csharp_new_line_before_finally = true # Indentation csharp_indent_case_contents = true csharp_indent_switch_labels = true # Spacing csharp_space_after_cast = false csharp_space_after_keywords_in_control_flow_statements = true # Naming conventions dotnet_naming_rule.interfaces_should_begin_with_i.severity = suggestion dotnet_naming_rule.interfaces_should_begin_with_i.symbols = interface dotnet_naming_rule.interfaces_should_begin_with_i.style = begins_with_i dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_style.begins_with_i.required_prefix = I dotnet_naming_style.begins_with_i.capitalization = pascal_case dotnet_naming_rule.private_fields_should_be_camel_case.severity = suggestion dotnet_naming_rule.private_fields_should_be_camel_case.symbols = private_fields dotnet_naming_rule.private_fields_should_be_camel_case.style = underscore_camel_case dotnet_naming_symbols.private_fields.applicable_kinds = field dotnet_naming_symbols.private_fields.applicable_accessibilities = private dotnet_naming_style.underscore_camel_case.required_prefix = _ dotnet_naming_style.underscore_camel_case.capitalization = camel_case Path: redb-route/CHANGELOG.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/CHANGELOG.md ---- # Changelog All notable changes to redb.Route will be documented in this file. This changelog covers the **NuGet-published packages**: | Package | Description | |---------|-------------| | `redb.Route` | Core engine: DSL, processors, expressions, telemetry | | `redb.Route.Amqp` | AMQP 1.0 transport | | `redb.Route.As2` | AS2 (RFC 4130) B2B/EDI transport — signed/encrypted S/MIME over HTTP with MDN receipts | | `redb.Route.AzureServiceBus` | Azure Service Bus transport | | `redb.Route.Cache` | Caching as an EIP — a `.Cache(key, ttl)` scope and the `cache:` component | | `redb.Route.Controllers` | Transport-agnostic controller dispatch | | `redb.Route.Core` | Bridge to redb.Core props storage | | `redb.Route.DataFormats.Avro` | Apache Avro data format (Chr.Avro) — binary marshal/unmarshal | | `redb.Route.DataFormats.Csv` | CSV data format (CsvHelper) — POCO collections, dictionaries, raw rows | | `redb.Route.DataFormats.Protobuf` | Protocol Buffers data format (Google.Protobuf), optional Confluent Schema Registry | | `redb.Route.DataFormats.Yaml` | YAML data format (YamlDotNet) — POCOs and dynamic documents | | `redb.Route.Elasticsearch` | Elasticsearch 8.x transport | | `redb.Route.Exec` | Local process execution transport (`exec:` scheme) | | `redb.Route.File` | File system transport | | `redb.Route.Firebase` | Firebase (Firestore, Cloud Storage, FCM) transport | | `redb.Route.Ftp` | FTP/FTPS transport | | `redb.Route.GenericFile` | Base library for file-based transports | | `redb.Route.Grpc` | gRPC transport | | `redb.Route.Http` | HTTP/HTTPS transport | | `redb.Route.Http.Hosting` | Shared Kestrel HTTP hosting (`SharedHttpServerManager`) reused by HTTP-based transports | | `redb.Route.IbmMq` | IBM MQ transport | | `redb.Route.JsonTransform` | Declarative JSON-to-JSON transformation (JSONata) | | `redb.Route.Kafka` | Apache Kafka transport | | `redb.Route.Ldap` | LDAP / Active Directory transport | | `redb.Route.Llm` | LLM transport — universal OpenAI-compatible provider + native AnthropicProvider | | `redb.Route.Llm.Abstractions` | LLM tool-capability contracts (`ILlmToolDescriptor`, `LlmToolCapability`, `.AsLlmTool()` DSL) | | `redb.Route.Llm.Mcp` | MCP-client connector (`mcp:` scheme) — spawns external Model Context Protocol servers, auto-discovers tools via `tools/list` | | `redb.Route.Llm.Tools` | Utility LLM tools — HttpFetch / JsonPath / XPath / MathEval / RegexExtract / Tavily web search | | `redb.Route.Mail` | Email transport (SMTP, IMAP, POP3) | | `redb.Route.MqttNet` | MQTT 5.0 transport | | `redb.Route.Quartz` | Quartz.NET scheduling transport | | `redb.Route.RabbitMQ` | RabbitMQ transport | | `redb.Route.Redis` | Redis transport | | `redb.Route.S3` | AWS S3 / MinIO transport | | `redb.Route.Sftp` | SFTP transport | | `redb.Route.SignalR` | SignalR transport | | `redb.Route.Sql` | SQL database transport | | `redb.Route.Soap` | SOAP 1.1/1.2 transport — WS-Security, MTOM attachments, WSDL-first services | | `redb.Route.Sqs` | Amazon SQS + SNS transport | | `redb.Route.Tcp` | Raw TCP transport | | `redb.Route.Telegram` | Telegram Bot transport | | `redb.Route.Templates` | Payload templates (Scriban) — the PayloadFactory analog | | `redb.Route.TestKit` | Test kit — AdviceWith, mock expectations, NotifyBuilder | | `redb.Route.Validation.Adapters` | FluentValidation + DataAnnotations adapters | | `redb.Route.WebSocket` | WebSocket transport | | `redb.Route.XPath2` | XPath 2.0 expressions (regex, sequences, dates, `for`/`some`/`every`) on XPath2.Net | | `redb.Route.Xml` | Declarative XML routes — `.route.xml` files load into the same fluent DSL | | `redb.Route.Xml.CodeGen` | `redb-route-xml` .NET tool — fluent C#, Mermaid diagrams and the XSD from `.route.xml`; not part of the runtime | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). > **Note on version history:** redb.Route has been running in production since version 1.0.0. > Versions 1.0.0 – 1.0.3 were not published to NuGet (internal deployments only). > The first public NuGet release is **1.0.4**. ## [Unreleased] Pending changes live in `changelog/unreleased/` until the release; `pwsh scripts/changelog.ps1 -Preview` shows them. ## [4.8.0] — 2026-12-01 ### Breaking - **A consumer that failed to start with its context is started again.** A broker or server not up yet used to leave the route `Errored` until a manual start; the context now retries in the background (2 s doubling to 1 min, no limit, `RouteEngineOptions.ConsumerStartRetry`) and the route becomes `Started` once its consumer starts. The start-up log names the `Errored` routes instead of reporting every endpoint operational. Packages: `redb.Route`. Upgrade: [UPGRADING.md](UPGRADING.md#a-consumer-that-failed-to-start-is-started-again). - **An `OnCompletion` block runs in the caller, which waits for it**, as in Apache Camel; `.ParallelProcessing()` or `.ExecutorService("name")` runs it on a bounded pool of its own instead. Before, every block after the consumer started as unbounded background work. Packages: `redb.Route`. Upgrade: [UPGRADING.md](UPGRADING.md#an-oncompletion-block-runs-in-the-caller-which-waits-for-it). - **A Wire Tap runs on a bounded pool** built from a thread pool profile, as in Apache Camel: 20 copies at a time and 1000 waiting by default, and the route's own thread runs a copy that finds both full. A slow tap target used to pile up background work without limit. Profiles: `RouteEngineOptions.DefaultThreadPoolProfile`, named ones picked with `.WireTap(uri, executorService: "name")`. Packages: `redb.Route`. Upgrade: [UPGRADING.md](UPGRADING.md#a-wire-tap-runs-on-a-bounded-pool). - **An idempotent claim carries an id, so a node whose claim was taken over no longer settles the new holder's claim.** The SQL repository adds a `claim_id` column by itself. With `CreateTable = false`, add the column before starting 4.8.0 nodes; the ALTER statement for each database is in UPGRADING. Packages: `redb.Route`, `redb.Route.Core`, `redb.Route.Sql`, `redb.Route.As2`, `redb.Route.As4`. Upgrade: [UPGRADING.md](UPGRADING.md#the-sql-idempotent-table-has-a-claim_id-column). - **`InterceptSendToEndpoint` publishes the target in the exchange property `CamelToEndpoint`**, as in Apache Camel; the headers `redb.toEndpoint` and `CamelToEndpoint` are gone. Read `${property.CamelToEndpoint}` instead. Packages: `redb.Route`. Upgrade: [UPGRADING.md](UPGRADING.md#the-intercepted-target-is-the-cameltoendpoint-property). - **`Split` metadata are exchange properties, and an `IMessage` part keeps its own headers**, as in Apache Camel. `CamelSplitIndex`, `CamelSplitSize` and `CamelSplitComplete` move from headers to properties (`${property.CamelSplitIndex}`); a part that is an `IMessage` becomes the part's message, a copy without the parent's headers. A streaming split reads one part ahead, as Camel's does: a source that waits for its next element holds the current part back until it arrives. Packages: `redb.Route`. Upgrade: [UPGRADING.md](UPGRADING.md#split-metadata-are-exchange-properties-and-a-message-part-keeps-its-own-headers). - **A copy that goes on as an exchange of its own has a new id, as in Apache Camel**: `seda:`, `vm:`, `Multicast`, `RecipientList`, `ScatterGather`, `Enrich` and `OnCompletion` copies get a new `ExchangeId` and `CamelCorrelationId` set to the original's id; `WireTap` and `PollEnrich` copies a new id without it. Each copy is its own in-flight entry, in its own route; join hops on `CamelCorrelationId`, not `ExchangeId`. Packages: `redb.Route`. Upgrade: [UPGRADING.md](UPGRADING.md#a-copy-that-goes-on-as-an-exchange-of-its-own-has-a-new-id). - **A parallel `ScatterGather` or `RecipientList` inside a transaction runs each branch under a dependent clone of it**, as a parallel `Split` and `Multicast` do, instead of on the route's transaction from several threads at once. A failed branch now rolls the whole block back, best-effort mode included; before, the other branches committed and sent. Packages: `redb.Route`. Upgrade: [UPGRADING.md](UPGRADING.md#a-failed-branch-of-a-parallel-scattergather-or-recipientlist-rolls-the-transaction-back). - **The AMQP fluent entry point is `AmqpDsl`**, as `TimerDsl`, `GrpcDsl`, `TcpDsl` and `LdapDsl`. The class was named `Amqp`, which the root namespace of AMQPNetLite shadows, so `Amqp.Address(...)` never compiled in a consumer's file; code that wrote the full name `redb.Route.Amqp.Amqp.Address(...)` now writes `AmqpDsl.Address(...)`. Packages: `redb.Route.Amqp`. Upgrade: [UPGRADING.md](UPGRADING.md#the-amqp-fluent-entry-point-is-amqpdsl). - **An AS2 receiver is bounded by default: 32 requests at once and 32 waiting** (`maxConcurrentRequests=32`, `requestQueueLimit=32`), where it admitted every request; a burst past that is refused and resent by the partner. `maxConcurrentRequests=0` keeps unlimited admission. Packages: `redb.Route.As2`. Upgrade: [UPGRADING.md](UPGRADING.md#an-as2-receiver-refuses-with-503-and-retry-after-30-and-bounds-its-asynchronous-mdns). - **An AS2 receiver answers a refused request with 503 and `Retry-After: 30`** (was 429 and 1), and **bounds its asynchronous MDNs**: a message asking for one when all `asyncMdnPoolSize` (20) slots are taken is refused before any work, and a receipt the partner does not take is posted again up to `asyncMdnAttempts` (3) times instead of once. Packages: `redb.Route.As2`. Upgrade: [UPGRADING.md](UPGRADING.md#an-as2-receiver-refuses-with-503-and-retry-after-30-and-bounds-its-asynchronous-mdns). - **An encrypted unsigned AS2 message has its MIC over the decrypted part with its MIME headers** (RFC 4130 §7.3.1), on send and on receive, as OpenAS2 computes it; such a message to a conforming partner was reported as a MIC mismatch. An old and a new redb paired on such an agreement report `mismatch` until both are upgraded. Packages: `redb.Route.As2`. Upgrade: [UPGRADING.md](UPGRADING.md#an-encrypted-unsigned-as2-message-has-its-mic-over-the-part-with-its-headers). - **Service Bus `enableBatch` and `batchMaxMessages` are gone.** Any list body is sent as one Service Bus batch, one message per element, as in Apache Camel: a list of `IMessage` with each element's own body and properties, any other list with each value under the exchange's headers. A list used to be one message unless `enableBatch=true`. Packages: `redb.Route.AzureServiceBus`. Upgrade: [UPGRADING.md](UPGRADING.md#a-service-bus-list-body-goes-out-as-one-batch-enablebatch-is-gone). - **IBM MQ batch mode: `batching=true` reads a batch under syncpoint and commits it once**, a `List` per batch; the option `batchSize`, which did nothing, is gone. A request in a batch goes to `backoutQueue` unless `disableReplyTo=true`, which also stops a single consumer from replying. Packages: `redb.Route.IbmMq`. Upgrade: [UPGRADING.md](UPGRADING.md#ibm-mq-batchsize-is-gone-batch-mode-is-batchingtrue). - **Kafka batch mode is `batching=true`, sized by `maxBatchMessages`**, as every broker's batch: `maxPollRecords` is gone, `pollTimeoutMs` is the idle timeout of a batch and `batchingIntervalMs` its hard limit, and the `redbKafka.BatchSize` header is gone (the size is `body.Count`). Replace `maxPollRecords=N` with `batching=true&maxBatchMessages=N`. Packages: `redb.Route.Kafka`. Upgrade: [UPGRADING.md](UPGRADING.md#kafka-batch-mode-is-batchingtrue-with-maxbatchmessages). - **Kafka headers take Apache Camel's names and types** (`CamelKafkaTopic`, `CamelKafkaPartition`, `CamelKafkaOffset`, `CamelKafkaTimestamp`, `CamelKafkaKey`, and `CamelKafkaRecordMeta` for the four `Sent.*` headers); the old names are not read. A record's partition is `partitionKey`, else the new `CamelKafkaPartitionKey` header, else the key; the key is kept with an explicit partition. `keyFromHeader` is gone, and a producer refuses `partitionNumber`. The producer reads `CamelKafkaOverrideTopic` and `CamelKafkaOverrideTimestamp` per message, as Camel does, and removes them before the send. Packages: `redb.Route.Kafka`. Upgrade: [UPGRADING.md](UPGRADING.md#kafka-headers-take-apache-camels-names-and-a-records-partition-is-chosen-as-in-camel). - **An LLM store called without an exchange inside `ExecuteAtomicAsync` or `BeginTransaction` on the context's shared `IRedbService` is no longer part of that transaction.** It commits on its own and stays when the transaction rolls back. Pass the exchange, or use a `TransactionScope`, which the call still joins. Packages: `redb.Route.Llm`. Upgrade: [UPGRADING.md](UPGRADING.md#an-llm-store-called-without-an-exchange-opens-a-redb-scope-of-its-own). - **The reservation of a tool's idempotency key is kept next to the tool's output, in the agent's redb**: the `?redb=` instance, else the `AddRedbLlmStorage("name")` one, else the context's default. `AddRedbLlmStorage()` alone is enough; a host's `IIdempotentRepository` in DI is no longer used for it, and `RedbToolIdempotencyStore(context, name)` lost its repository parameter. Let agent runs finish before the upgrade: a run in flight may run a tool once more. Packages: `redb.Route.Llm`. Upgrade: [UPGRADING.md](UPGRADING.md#the-tool-idempotency-reservation-of-an-agent-is-kept-in-the-agents-redb). - **The IMAP and POP3 consumers take Apache Camel's `searchTerm`**: `searchTerm.subject`, `.from`, `.to`, `.body`, `.subjectOrBody`, `.unseen` and the sent and received date bounds (`now-24h` or `yyyy-MM-dd HH:mm:ss`), or `searchTerm=#name` for a MailKit search query from the registry. `searchQuery`, which was never applied, is gone: a URI that names it fails to start. Packages: `redb.Route.Mail`. Upgrade: [UPGRADING.md](UPGRADING.md#the-mail-consumer-selects-mails-by-camels-searchterm-searchquery-is-gone). - **An MQTT message the route fails on is settled by one rule in serial and concurrent mode**, Apache Camel's paho-mqtt5 rule as corrected by CAMEL-25793 (not yet in a Camel release): on a session the broker keeps (`cleanSession=false`, `sessionExpiryInterval` above 0) it stays unacknowledged and the consumer reconnects after a backoff, so the broker sends it again; otherwise it is acknowledged and logged as an error. Serial mode used to acknowledge a failure; concurrent mode left it unacknowledged until the consumer stalled. Packages: `redb.Route.MqttNet`. Upgrade: [UPGRADING.md](UPGRADING.md#an-mqtt-message-the-route-fails-on-is-settled-by-one-rule). - **A RabbitMQ send fails when the broker does not confirm it within `confirmTimeout`** (5000 ms by default, as in Apache Camel) with `RabbitMQPublishTimeoutException`, a `TimeoutException`. A broker that blocks its publishers under a memory or disk alarm used to hold every send, and its thread, for as long as the alarm lasted. Packages: `redb.Route.RabbitMQ`. Upgrade: [UPGRADING.md](UPGRADING.md#a-rabbitmq-send-fails-when-the-broker-does-not-confirm-it-in-5-seconds). - **An ordinary send no longer carries a sender's reply-to on**, as in Apache Camel's JMS: a message consumed with a reply-to and forwarded to RabbitMQ, IBM MQ or AMQP goes out without it. Set `preserveMessageQos=true` on the endpoint to keep it; the correlation id is carried as before. Packages: `redb.Route.RabbitMQ`, `redb.Route.IbmMq`, `redb.Route.Amqp`. Upgrade: [UPGRADING.md](UPGRADING.md#a-forwarded-reply-to-is-not-carried-on). - **A RabbitMQ delivery the route fails on is tried 5 times, 1 s apart, then rejected without requeue**, as in Apache Camel (`maximumRetryAttempts`, `retryDelay`, `rejectAndDontRequeue`); it used to be requeued forever. Give the queue a dead letter exchange, or the broker drops such a message. Packages: `redb.Route.RabbitMQ`. Upgrade: [UPGRADING.md](UPGRADING.md#a-failed-rabbitmq-message-is-tried-5-times-then-rejected-to-the-dead-letter-exchange). - **The S3 and Firebase Storage consumers keep an object whose exchange the route marked rollback-only** (`.RollbackAll()`), as they keep one that failed: no delete, no move, offered again on the next poll; Firebase's `moveFailed` takes it. It used to be deleted or moved as if it had succeeded. Packages: `redb.Route.S3`, `redb.Route.Firebase`. Upgrade: [UPGRADING.md](UPGRADING.md#an-s3-or-firebase-storage-object-is-kept-when-the-route-rolls-back). - **SQS `enableBatch` and `batchMaxMessages` are gone.** A list of `IMessage` goes out one SQS message per element by `SendMessageBatch`, each with its own body and attributes; refused entries are counted in headers, not thrown. Any other list is one message, its JSON. Packages: `redb.Route.Sqs`. Upgrade: [UPGRADING.md](UPGRADING.md#an-sqs-list-of-imessage-goes-out-by-sendmessagebatch-enablebatch-is-gone). - **The redb.Route packages target .NET 10 and .NET 11; .NET 8 and .NET 9 are no longer targets.** Both reached end of support on 10 November 2026. An application on .NET 8 or 9 stays on 4.7.x or moves to .NET 10. The `redb-route-xml` tool and the project `redb-route-xml new` creates now need .NET 10. Upgrade: [UPGRADING.md](UPGRADING.md#net-10-and-net-11-only). ### Added - **`Base64Text` reads base64 the same way on .NET 10 and .NET 11.** .NET 11 refuses a value whose last character has non-zero unused bits, .NET 10 ignores them. `Decode` accepts such a value on both runtimes, `TryDecodeCanonical` refuses it on both. The Base64 data format and the AS2 MIC comparison accept it, as before. Packages: `redb.Route`, `redb.Route.As2`. - **`IIdempotentRepository.Claim` tells a key in flight from a confirmed one and takes over an abandoned claim.** The redb, SQL and in-memory repositories implement it from the state they keep; the in-memory one now keeps a confirmed flag. A repository of your own keeps its behaviour (every held key is confirmed) until it overrides `Claim`; the AS2 receiver uses it to answer a resend in flight with `503` instead of a duplicate MDN. The SQL repository ages a claim by the database's clock; with the redb repository keep the timeout far above the clock skew between nodes. Packages: `redb.Route`, `redb.Route.Core`, `redb.Route.Sql`. - **One batch contract for broker consumers in `redb.Route.Batching`**: `BatchOptions` (`batching`, `maxBatchMessages`, `pollTimeoutMs` as an idle timeout, `batchingIntervalMs` as a hard limit), `BatchCollector`, `BatchDispatcher` (body a `List`, one route run, one settlement) and `IBatchSettlement` for a connector of your own. Packages: `redb.Route`. - **EIPs publish Apache Camel's exchange properties**, named in `ExchangePropertyKeys`: `CamelLoopIndex` and `CamelLoopSize`, `CamelMulticastIndex` and `CamelMulticastComplete`, `CamelAggregatedSize`, `CamelAggregatedCompletedBy` and `CamelAggregatedCorrelationKey`, `CamelRecipientListEndpoint`, and `CamelCorrelationId` on Split and Multicast copies, which the route span now reads as its `redb.correlation.id` tag. An aggregate's completion predicate is now evaluated on the arrival that reaches `completionSize` too. Packages: `redb.Route`. - **Option groups**: an endpoint option marked `[OptionGroup]` is written `group.member=value` on the URI and as attributes of the same names in route XML, as Camel's prefixed options; an unknown member fails at start naming the group's members, and `[Sensitive]` members are masked. `EndpointOptions.BindableOptions` lists the options as the URI writes them. Packages: `redb.Route`. - **The nested-lambda `Choice` branch, `OnWhen` and `RetryWhile` take an `IPredicate`.** `.Choice(c => c.When(Header("type").isEqualTo("order"), r => r.To(...)))` now compiles, as the one-argument `.When(IPredicate)` already did; an exception handler's `OnWhen(...)` and `RetryWhile(...)` take the same predicate form next to the lambda and the string. Packages: `redb.Route`. - **`ConsumerStartRetry.UnhealthyOnRestarting` and `UnhealthyOnExhausted`**, Apache Camel's switches of the same names with Camel's defaults (`true`): an `Errored` route waiting for a start retry, or one no retry waits for any more, is Unhealthy; `false` reports that phase Degraded, so a broker that is down does not take the node out of readiness. `RouteContext.IsErroredRouteUnhealthy` tells a health check of its own the same. Packages: `redb.Route`. - **AMQP 1.0 batch mode**: `batching=true` with `maxBatchMessages` (at most `credit`), `pollTimeoutMs` and `batchingIntervalMs` hands the route a `List`, accepted after the route and released on failure. A delivery with a reply-to is rejected from a batch; `disableReplyTo=true` (Apache Camel's name, single mode too) takes it without a reply. Packages: `redb.Route.Amqp`. - **Service Bus batch mode**: `batching=true` with `maxBatchMessages`, `pollTimeoutMs` and `batchingIntervalMs` hands the route a `List` received with `ReceiveMessagesAsync`, completed after the route, abandoned (or dead-lettered with `autoDeadLetter`) on failure, its locks renewed while the route runs. Not with `enableSessions`. Packages: `redb.Route.AzureServiceBus`. - **IBM MQ `temporaryModel`** names the model queue of the dynamic reply queue of request-reply (IBM MQ's `TEMPMODEL`), on `IbmMqConnectionFactory` and inline on the endpoint; the default stays `SYSTEM.DEFAULT.MODEL.QUEUE`. The IBM MQ developer image grants its `app` user `DEV.APP.MODEL.QUEUE`. Packages: `redb.Route.IbmMq`. - **An agent run inside a transaction warns when it uses the in-memory conversation or tool idempotency store.** These stores do not roll back with the route, so a redelivered message may not call the tool again; the warning, logged once per route and connection factory, names both fixes: `AddRedbLlmStorage()`, or `llm:` outside `.Transacted()`. Packages: `redb.Route.Llm`. - **MQTT `sessionExpiryInterval` and `maxReconnectDelay`**, as in Apache Camel's paho-mqtt5: how long the broker keeps the session after a disconnect (seconds, default 0: it ends with the connection, MQTT 5), and the longest pause before the consumer reconnects after a failed message (milliseconds, default 128000). Packages: `redb.Route.MqttNet`. - **RabbitMQ batch consumer**: `batching=true` with `maxBatchMessages`, `pollTimeoutMs` and `batchingIntervalMs` hands the route a `List` per batch, settled once after the route, on `concurrentConsumers` workers. A delivery with a reply-to is rejected from a batch unless `disableReplyTo=true`, which also stops a single consumer from replying. Packages: `redb.Route.RabbitMQ`. - **Redis stream batch mode**: `batching=true` on an `XREAD` or `XGROUP` consumer with `maxBatchMessages` (default `streamReadCount`), `pollTimeoutMs` and `batchingIntervalMs` hands the route a `List`; with a group it is acknowledged in one `XACK` after the route and stays pending on failure, for `streamClaimMinIdleMs` to claim again. Packages: `redb.Route.Redis`. - **SQS batch consumer**: `batching=true` with `maxBatchMessages`, `pollTimeoutMs` and `batchingIntervalMs` hands the route a `List` per batch, collected over receives of up to 10 and deleted once after the route; a failed batch comes back by the visibility timeout and reaches the dead letter queue through the redrive policy. Packages: `redb.Route.Sqs`. ### Changed - **`RouteHealthCheck` also reports the endpoints the routes send to.** One that knows it cannot send (a RabbitMQ endpoint whose broker blocks it under a memory or disk alarm, any endpoint at a high error rate) makes the result Degraded, never Unhealthy, and is listed under `endpoints` with its masked URI and reason. A readiness probe that fails on Degraded takes the node out of readiness while it lasts. Packages: `redb.Route`, `redb.Route.RabbitMQ`. - **The "Compiled route" and "Endpoint started" log lines show a long endpoint URI in a short form.** A URI longer than 120 characters (a SQL statement, a long query string) is cut at a parameter boundary, never inside a masked secret, and ends with `... [+N chars #hash]`, a hash of the whole masked URI that tells endpoints apart. With Debug on, the same lines carry the whole masked URI. `EndpointUri.ForLog` gives the same form for your own logs. Packages: `redb.Route`. - **`AddComponents` registers a component whose constructor has only optional parameters** (such as `HttpComponent`), as the XML catalog already lists it: one rule for both. A scanned component it cannot create, for want of such a constructor or because the constructor throws, is now named in a warning instead of left out in silence. Packages: `redb.Route`. - **Connector start and stop lines use the short URI form too**, as the "Compiled route" and "Endpoint started" lines already do: a URI longer than 120 characters is cut with `... [+N chars #hash]`, and the whole masked URI is on the same line when Debug is on. `EndpointUri.ForLog(uri, logger)` gives that choice to custom components. Packages: `redb.Route`, `redb.Route.Amqp`, `redb.Route.Elasticsearch`, `redb.Route.GenericFile`, `redb.Route.IbmMq`, `redb.Route.Ldap`, `redb.Route.RabbitMQ`, `redb.Route.Redis`, `redb.Route.S3`, `redb.Route.Sqs`. - **`log:` `level=` takes Apache Camel's names and refuses any other.** `INFO`, `WARN` and `OFF` now mean Information, Warning and None, so `level=WARN` logs at Warning and `level=OFF` logs nothing (both logged at Information before); the .NET names work as before, in any case. An unknown name used to log at Information without a word; now it stops the route at start with a message listing the accepted names. Packages: `redb.Route`. Upgrade: [UPGRADING.md](UPGRADING.md#log-level-takes-the-camel-names-and-refuses-any-other). - **An AS2 endpoint refuses to start with an `As2From` or `As2To` that is not an AS2 identifier.** Each must be 1 to 128 printable ASCII characters (RFC 4130 §6.2); a non-ASCII or longer identifier is now a configuration error naming the setting, instead of reaching the partner as a header it cannot accept. Packages: `redb.Route.As2`. - **An AS2 receiver answers a `required` receipt option it cannot honour with a failed MDN and does not process the message.** A `signed-receipt-protocol` other than `pkcs7-signature`, or `signed-receipt-micalg` with no algorithm usable here, marked `required`, now gets `failed/Failure: unsupported format` or `unsupported MIC-algorithms` (RFC 4130 §7.5.3). It used to be processed with the agreement's algorithm; `optional` still is. Packages: `redb.Route.As2`. - **An AS2 receiver without a certificate of its own answers a `required` signed receipt with a failed MDN.** It used to process the message and send an unsigned receipt; it now answers `failed/Failure: unsupported format` and does not process it (RFC 4130 §7.5.3). An `optional` signed receipt is still processed with an unsigned MDN. Packages: `redb.Route.As2`. - **The AS4 receiver refuses a security value in non-canonical base64 on every runtime.** A DigestValue, SignatureValue, CipherValue, BinarySecurityToken or KeyIdentifier whose last character has non-zero unused bits (`YR==` instead of `YQ==`) was accepted on .NET 10 and is refused on .NET 11; it is now refused on both, as XML Schema `base64Binary` requires, with the error code of any other malformed value there. Senders such as Domibus never write that form. Packages: `redb.Route.As4`. - **An AS4 resend that arrives while the first copy is still in the route is answered 503, not with a receipt.** A receipt then would tell the sender the message arrived although the first copy could still fail. The sender gets the `rejectStatusCode` with `Retry-After` and no ebMS signal and resends on its retry schedule (Domibus does); a resend after the first copy succeeded still gets its very receipt. A claim never confirmed is taken over after the new `inFlightClaimTimeout` (10 minutes). Packages: `redb.Route.As4`. - **Base64 credentials and WS-Security values must be canonical on every runtime.** A value whose last character has non-zero unused bits now gets 401 as an inbound HTTP Basic credential. In a SOAP signature it sets `redbSoap.signatureValid` to false. In an encrypted SOAP request it gets the `Security check failed` fault. .NET 10 used to accept such a value; .NET 11 refuses it. Packages: `redb.Route.Http`, `redb.Route.Soap`. - **IBM MQ consumer pauses after a backout**: in poll and batch modes the consumer waits `backoutDelay` milliseconds (default 1000) before it reads again, so a failed message no longer comes straight back; `backoutDelay=0` keeps the old behaviour. This option is redb's addition, not part of Apache Camel; listener mode is not affected. Packages: `redb.Route.IbmMq`. - **`AddRedbRouteLlm()` registers an in-memory tool idempotency store.** Without `AddRedbLlmStorage()` a repeated tool call with the same key (conversation and tool-use id) now returns the stored output instead of running the tool again, within the process and for 24 hours after the first call completed; `AddRedbLlmStorage()` or a store of your own (`InMemoryToolIdempotencyStore` takes a ttl) still replaces it, in either call order. Packages: `redb.Route.Llm`. Upgrade: [UPGRADING.md](UPGRADING.md#an-agent-without-addredbllmstorage-deduplicates-tool-calls-in-the-process). - **Telegram spans no longer carry the chat id.** The consumer span dropped `messaging.telegram.chat.id`; the send span dropped it and `messaging.destination.name`, which held the same value. A route that needs the chat id in its traces adds it with `.SpanTag("messaging.telegram.chat.id", Header(TelegramHeaders.ChatId), SpanTarget.Inbound)`. Packages: `redb.Route.Telegram`. - **The `redb-route*` templates create a net10.0 project and no longer take `--framework`.** A module runs in the Tsak worker, which targets .NET 10, and a module built for a newer framework does not load there. Drop `--framework` from scripts that create these templates. Packages: `redb.Templates`. Upgrade: [UPGRADING.md](UPGRADING.md#net-10-and-net-11-only). - **Microsoft dependencies move to the 10.0.15 servicing line.** Microsoft.Extensions.*, Microsoft.Data.Sqlite, System.Security.Cryptography.Xml / Pkcs and the ASP.NET Core packages are referenced at 10.0.15 (was 10.0.13). On .NET 11 System.Security.Cryptography.Xml / Pkcs are taken from the 11.0 line. An application that pins one of them lower raises its pin. - **VS Code extension 0.2.31: completion and validation follow the 4.8.0 endpoint options.** The editor offers the new options (batch mode, reply-to, mail `searchTerm`, the AS2, AS4, RabbitMQ and MQTT additions) and marks the removed ones (`enableBatch`, `maxPollRecords`, `searchQuery` and the others in UPGRADING.md) as errors. - **Route 4.8.0 is built on redb 4.8.0.** A route context that keeps state in redb (idempotent repository, aggregation, LLM storage) takes the redb 4.8.0 database upgrade at its first start; every node of one database moves to 4.8.0 together, as the redb 4.8.0 upgrade notes describe. ### Fixed - **A list body no longer goes out as its type name.** Kafka, RabbitMQ and IBM MQ producers send a list of `IMessage` element by element, each with its own body and headers (IBM MQ in one unit of work); Kafka also a plain list, as camel-kafka. RabbitMQ, IBM MQ and AMQP refuse a plain list, a request-reply producer refuses a list, and AMQP asks to `Split`. Packages: `redb.Route`, `redb.Route.Kafka`, `redb.Route.RabbitMQ`, `redb.Route.IbmMq`, `redb.Route.Amqp`. - **An AS2 resend that arrives while the first copy is still in the route is no longer answered as a duplicate.** With an `idempotentRepository`, the partner now receives `503` with `Retry-After` and no MDN for such a copy, and resends it; the `processed/warning: duplicate-document` MDN goes only to a copy of a message whose processing was confirmed. Before, the copy got that MDN, and when the first copy then failed the document was lost. A claim left unconfirmed by a stopped node for longer than the new `inFlightClaimTimeout` (10 minutes) is taken over, so the resend is processed. Packages: `redb.Route.As2`. - **Every redb store of `AddRedbLlmStorage()` called without an exchange opens a redb scope of its own per call**: the tool idempotency, eval run, approval, batch, conversation, knowledge, prompt template and tool result cache stores, as the cost budget store and the audit observer already did. They used the context's single `IRedbService`, so concurrent calls without an exchange (the eval runner saves without one; a host calling a store directly) shared one connection and the second was refused as concurrent use. Packages: `redb.Route.Llm`. ## Earlier versions Earlier releases are archived by line in [changelog/](changelog/): [4.7.x](changelog/CHANGELOG-4.7.x.md), [4.6.x](changelog/CHANGELOG-4.6.x.md), [4.5.x](changelog/CHANGELOG-4.5.x.md), [4.4.x](changelog/CHANGELOG-4.4.x.md), [4.3.x](changelog/CHANGELOG-4.3.x.md), [4.2.x](changelog/CHANGELOG-4.2.x.md), [4.1.x](changelog/CHANGELOG-4.1.x.md), [4.0.x](changelog/CHANGELOG-4.0.x.md), [3.x](changelog/CHANGELOG-3.x.md), [2.x](changelog/CHANGELOG-2.x.md), [1.x](changelog/CHANGELOG-1.x.md). Path: redb-route/CONCURRENCY.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/CONCURRENCY.md ---- # Concurrency & Parallelism in redb.Route How to process more than one message at a time — safely. Like [Apache Camel](https://camel.apache.org/manual/threading-model.html), redb.Route separates concurrency into **two independent axes**, and you pick the one that fits: | Axis | Question it answers | Primitive | |------|---------------------|-----------| | **Consumer-level** | How many messages does the *source* pull/receive at once? | Transport option (`ConcurrentConsumers`, `MaxConcurrentCalls`, partitions, …) | | **Processing-level** | How many messages does the *pipeline* process at once, regardless of source? | The **`.Threads(N)`** EIP | The rule of thumb: - **Broker/queue source** (RabbitMQ, AMQP, IBM MQ, Azure Service Bus, SEDA, Kafka, MQTT) → use its **consumer-level** knob. The transport competes for messages natively and preserves its own delivery/ack semantics. - **Polling source** (File, FTP/SFTP, SQL, S3, Elasticsearch, IMAP/POP3, LDAP, Timer, …) → these poll **serially by design** (one scan at a time is correct for a resource poll). To fan the *processing* out, add **`.Threads(N)`**. - **Any route, any source** → `.Threads(N)` always works as a general processing-concurrency stage. --- ## Processing concurrency — the `.Threads(N)` EIP `.Threads(N)` caps a route section's processing concurrency at **N**, so a strictly serial source keeps dispatching while up to N exchanges are processed in parallel. It is the general-purpose alternative to the `.To("seda://x?concurrentConsumers=N")` workaround — no named endpoint required. **Adaptive by exchange pattern** — one API, transparent the way Camel's `threads()` is: - **InOnly** — fire-and-forget hand-off: the exchange is *cloned* (own DI scope) and handed to the worker pool; the caller returns as soon as it's accepted, so a serial poll loop keeps pumping. - **InOut** — request/reply: the body runs **inline on the same exchange** under a `SemaphoreSlim` gate (≤ N concurrent). Nothing is cloned or copied, so the reply is preserved **exactly** — whether the route writes it to `Out` **or to `In`** (redb.Route's HTTP consumer reads `In` when `Out` is unset). Concurrency across concurrent requests stays capped at N. **RPC works, losslessly.** ```csharp From("file://in?moveTo=.done") .Threads(10) // up to 10 files processed in parallel .Process(HeavyTransform) .To("http://scoring-api/score") .End(); ``` Options: ```csharp .Threads(10) // minimum: pool of 10, bounded hand-off queue == pool size .Threads(10).MaxQueueSize(1000) // larger buffer: let the source run further ahead before backpressure .Threads(10).EnqueueTimeout(TimeSpan.FromSeconds(5)) // cap the wait for a free slot (default: wait forever) ``` ### Semantics — what to know | Property | Behaviour | |----------|-----------| | **Request/reply** | Adaptive by pattern: **InOnly** hands a clone to the pool (fire-and-forget); **InOut** runs the body **inline on the same exchange** under a gate, so the reply — on `Out` *or* `In` — is preserved losslessly. | | **Backpressure** | Bounded. InOnly waits on the hand-off queue; InOut waits on the gate. When saturated the caller waits for a free slot — it never buffers unboundedly. Bound that wait with `.EnqueueTimeout(...)`, which fails fast with a `TimeoutException` (for InOut, surfaced to the awaiting caller) instead of waiting indefinitely. | | **Per-exchange isolation** | **InOnly** clones the exchange and gives the worker its **own DI scope** (own scoped services / DB connection) — the worker never shares the caller's mutable exchange. **InOut** runs on the caller's own exchange/scope (inline). | | **Transaction boundary** | **InOnly is a transaction boundary** — the worker runs detached (`ExecutionContext.SuppressFlow`), like `.To("seda://")`, so it does **not** extend the caller's transaction; open the tx **inside** the pooled body. **InOut is NOT a boundary** — the body runs inline, so the ambient `TransactionScope` flows into it (correct for request/reply — the caller awaits the result). | | **Ordering** | **Not preserved** when `N > 1` (same as any competing-consumer model). Use `N = 1` — or don't use `.Threads()` — when strict ordering matters. | | **Errors** | **InOnly** routes the fault to the route's error handling (`OnException` / dead-letter) on the pool thread — not swallowed. **InOut** lets the fault propagate up the pipeline to the same outer `OnException` wrapper as an un-threaded route; if unhandled it surfaces to the awaiting caller. | | **Graceful drain** | On route/context stop the pool stops accepting, finishes every in-flight and queued exchange, and only force-cancels if a drain timeout is exceeded. In-flight work is not dropped. | ### An asynchronous step settles the message before the work is done A broker consumer with `ackMode=manual` (the default on RabbitMQ, AMQP, Kafka, SQS, Service Bus and Redis Streams) settles the message when the route **returns**: acknowledges it, commits the offset, deletes it. An asynchronous step — an InOnly `.Threads(N)`, a `.To("seda://...")` — returns the route as soon as the exchange is handed off, so the message is settled **before** the work behind the step has run. A crash or a failure there loses the message: the broker will not deliver it again (at-most-once, whatever `ackMode` says). The same goes for a Kafka transaction: the consumed offset no longer rides in it, because the route returned before the transaction committed (the producer logs a warning). - Keep the part of the route that must be settled with the message **synchronous**: no InOnly `.Threads()` or `seda:` hand-off between the consumer and the last step that has to succeed. - For processing concurrency on a broker, use the transport's own knob (next section): it keeps acknowledging after each message is processed. - An asynchronous step is right for work whose loss the route accepts — notifications, copies, metrics — or which is made durable on its own (the step writes to a queue that settles separately). InOut `.Threads(N)` runs inline and is not affected: the route returns after the body. ### When to reach for it - A **polling** consumer is your bottleneck (File/SQL/S3/IMAP poll one batch at a time, then process serially). - The per-message work is **I/O- or CPU-heavy** and independent, and **ordering doesn't matter**. - You want processing concurrency **without** standing up a separate `seda://` route. --- ## Consumer concurrency — per transport When the **source** is a broker or queue, prefer its native knob: it competes for messages at the protocol level and keeps the transport's own delivery/ack guarantees. | Transport | Option | What it does | |-----------|--------|--------------| | **RabbitMQ** | `.ConcurrentConsumers(N)` | One channel, one consumer, native `consumerDispatchConcurrency: N` — the RabbitMQ.Client dispatcher invokes the handler for up to N deliveries concurrently. | | **AMQP / IBM MQ** | `.ConcurrentConsumers(N)` | N real competing consumers, each on its own session/QM — up to N messages processed concurrently. | | **SEDA / VM** | `?concurrentConsumers=N` | N workers draining one in-memory queue. | | **Azure Service Bus** | `.MaxConcurrentCalls(N)` | Passed through to `ServiceBusProcessor`. | | **Kafka** | *partitions* | Scale by partition count + consumer-group members; a single consumer polls one partition serially by design. | | **MQTT** | `.ConcurrentConsumers(N)` | N workers with **manual ack after processing** — see below. | | **Quartz (Cron/Timer)** | `.Threads(N)` (on the endpoint) | Allows up to N overlapping job fires. | | **Polling** (File, FTP/SFTP, SQL, S3, Elasticsearch, IMAP/POP3, LDAP, Timer, Exec, LLM) | — | Serial poll **by design**; add the `.Threads(N)` EIP for processing concurrency. | | **Event-driven** (HTTP, gRPC, SignalR, TCP, WebSocket, Firestore) | host-managed | The host dispatches requests/connections concurrently already. | ### MQTT `ConcurrentConsumers` — why it's native ```csharp From(Mqtt.Subscribe("telemetry/#").Broker("main").Qos(1).ConcurrentConsumers(5)) .Process(IngestReading) .End(); ``` A generic `.Threads(N)` on an MQTT route would acknowledge each message on **hand-off** — i.e. *before* it is processed — because the receive handler returns as soon as the exchange is queued. That weakens QoS 1/2 to at-most-once (a crash mid-processing loses the message). The native `.ConcurrentConsumers(N)` dispatches to N workers but sets `AutoAcknowledge = false` and **acknowledges only after** the worker finishes processing. Concurrency **and** at-least-once are preserved. A failed message follows the same rule as in serial mode: acknowledged when the broker would never send it again, else left unacknowledged while the consumer reconnects (the MQTT package README, "Acknowledgement and failed messages"). Ordering is not preserved when `N > 1`. > **Quartz note.** A stateful Quartz job (`[DisallowConcurrentExecution]`) will not overlap regardless of > `Threads(N > 1)` — that's correct by design (stateful means "never run me concurrently"). The `Threads` > setting is simply ignored in that case. --- ## Choosing between the two ``` Is the source a broker / queue (Rabbit, AMQP, IBM MQ, ASB, SEDA, Kafka, MQTT)? └─ yes → use the transport's consumer knob (ConcurrentConsumers / MaxConcurrentCalls / partitions). It keeps native delivery + ack semantics. └─ no → the source polls serially (File, SQL, S3, IMAP, LDAP, Timer, …) └─ need parallel processing? → add .Threads(N) to the route. Does strict ordering matter? → keep N = 1 (or avoid concurrency on that route). Does the work share a transaction with the source? → don't split it across .Threads(); open the tx inside the body. ``` Both axes compose: a broker consumer with `ConcurrentConsumers(4)` whose pipeline also contains a `.Threads(8)` stage will have up to 4 concurrent receives, each of which can fan its own processing out to 8 — though in practice you rarely need both on the same route. --- ## Mapping to Apache Camel | Camel | redb.Route | |-------|-----------| | `threads(poolSize)` EIP (InOut-aware) | `.Threads(N)` / `.MaxQueueSize(q)` / `.EnqueueTimeout(t)` — adaptive: InOnly hands off, InOut preserves the reply | | `seda?concurrentConsumers=N` | `.To("seda://x?concurrentConsumers=N")` | | broker `concurrentConsumers` | `.ConcurrentConsumers(N)` (RabbitMQ / AMQP / IBM MQ / MQTT), `.MaxConcurrentCalls(N)` (ASB) | | `split/multicast/recipientList().parallelProcessing()` | `.Split(...).Parallel()` / `.Multicast().Parallel()` with `.MaxParallelism(N)` | | polling consumer (single-threaded scan) | polling connectors — serial by design; add `.Threads(N)` | For fan-out **within** a single exchange (split a body into parts and process the parts in parallel), see the `Split` / `Multicast` / `RecipientList` EIPs with `.Parallel().MaxParallelism(N)` — that is a *synchronous* fan-out (the caller awaits all branches and can aggregate), distinct from `.Threads()`, which caps the concurrency of *separate* exchanges (InOnly hands each clone to a worker pool; InOut runs inline under a gate). Path: redb-route/CONNECTORS_ROADMAP.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/CONNECTORS_ROADMAP.md ---- # redb.Route — Connectors Roadmap `redb.Route` is a .NET integration framework inspired by Apache Camel: a lightweight DSL for building message-routing pipelines (`.From(...)...Process(...)...To(...)`) on top of a pluggable component model. Each **connector** is a NuGet package that registers one or more URI schemes (`kafka:`, `http:`, `sftp:`, …) and exposes a typed options model, a Producer, a Consumer, and integration tests across `net10.0` / `net11.0`. This document is the single source of truth for **which connectors exist, what they do, and what is on the wishlist.** Updated whenever a connector ships or a new one is planned. --- ## Current Status 31 connector packages ship today, beside the core package and the `redb.Route.Core` bridge to redb. | Package | Scheme(s) | Status | |---|---|---| | `redb.Route` (core) | `direct:`, `direct-vm:`, `vm:`, `seda:`, `timer:`, `log:`, `mock:`, `bean:`, `controlbus:`, `validator:`, `xslt:` | ✅ Done | | `redb.Route.Kafka` | `kafka:` | ✅ Done | | `redb.Route.RabbitMQ` | `rabbitmq:` | ✅ Done | | `redb.Route.Redis` | `redis:` | ✅ Done | | `redb.Route.Amqp` | `amqp:` | ✅ Done | | `redb.Route.IbmMq` | `wmq:` | ✅ Done | | `redb.Route.MqttNet` | `mqtt:` (TLS with `useTls`) | ✅ Done | | `redb.Route.AzureServiceBus` | `asb:` | ✅ Done | | `redb.Route.Sqs` | `sqs:`, `sns:` | ✅ Done | | `redb.Route.Http` | `http:`, `https:` | ✅ Done | | `redb.Route.Tcp` | `tcp:` | ✅ Done | | `redb.Route.WebSocket` | `ws:`, `wss:` | ✅ Done | | `redb.Route.Grpc` | `grpc:` | ✅ Done | | `redb.Route.SignalR` | `signalr:` | ✅ Done | | `redb.Route.Soap` | `soap:`, `soaps:` | ✅ Done | | `redb.Route.As2` | `as2:`, `as2s:` | ✅ Done | | `redb.Route.As4` | `as4:`, `as4s:` | ✅ Done | | `redb.Route.File` | `file:` | ✅ Done | | `redb.Route.Ftp` | `ftp:` (FTPS with `useFtps`) | ✅ Done | | `redb.Route.Sftp` | `sftp:` | ✅ Done | | `redb.Route.S3` | `s3:` | ✅ Done | | `redb.Route.Mail` | `smtp:`, `pop3:`, `imap:` | ✅ Done | | `redb.Route.Ldap` | `ldap:` | ✅ Done | | `redb.Route.Firebase` | `fcm:`, `fstore:`, `fbstorage:` | ✅ Done | | `redb.Route.Telegram` | `telegram:` | ✅ Done | | `redb.Route.Sql` | `sql:` | ✅ Done | | `redb.Route.Elasticsearch` | `elasticsearch:`, `es:` | ✅ Done | | `redb.Route.Cache` | `cache:` | ✅ Done | | `redb.Route.Quartz` | `cron:`, `qtimer:` | ✅ Done | | `redb.Route.Exec` | `exec:` | ✅ Done | | `redb.Route.Llm` | `llm:`, `embed:`, `knowledge:`, `stt:` | ✅ Done | | `redb.Route.Llm.Mcp` | `mcp:` | ✅ Done | --- ## Connector Specifications ### Messaging & Streaming #### `redb.Route.Kafka` — Apache Kafka ✅ - **Scheme:** `kafka:` - **Dependencies:** `Confluent.Kafka` - **Producer/Consumer:** publish to topic / subscribe with consumer groups - **Key features:** partitioning, key/value serializers (JSON / Avro via Schema Registry), at-least-once / exactly-once (transactions), manual & auto offset commits, headers ↔ exchange headers - **DSL example:** ```csharp .From("kafka:orders?brokers=kafka:9092&groupId=order-processor&autoOffsetReset=earliest") .To("kafka:enriched?brokers=kafka:9092") ``` #### `redb.Route.RabbitMQ` — RabbitMQ ✅ - **Scheme:** `rabbitmq:` - **Dependencies:** `RabbitMQ.Client` - **Producer/Consumer:** exchange/queue/binding declaration, publisher confirms, manual ack/nack - **Key features:** routing keys via Simple expressions, dead-letter exchange, QoS prefetch, mandatory/immediate, RPC (Direct Reply-To), connection recovery - **DSL example:** ```csharp .From("rabbitmq:orders?exchange=orders.ex&queue=orders.q&ackMode=Manual&prefetchCount=10") .To("rabbitmq:notifications?exchange=notifications.ex&routingKey=${header.customerType}") ``` #### `redb.Route.Redis` — Redis ✅ - **Scheme:** `redis:` - **Dependencies:** `StackExchange.Redis` - **Producer:** SET/GET/HSET, list/stream push, pub/sub publish - **Consumer:** pub/sub subscribe, Streams (XREAD/XREADGROUP with consumer groups + acks), key-space notifications, BLPOP/BRPOP queue - **Key features:** TLS, sentinel, cluster, dynamic key naming, idempotency via SETNX #### `redb.Route.Amqp` — AMQP 1.0 ✅ - **Scheme:** `amqp:` - **Dependencies:** `AMQPNetLite.Core` - Generic AMQP 1.0 (works against Azure Service Bus, ActiveMQ Artemis, Solace, etc.). Use `redb.Route.AzureServiceBus` for Azure-native features (sessions, dead-letter mgmt). #### `redb.Route.Sqs` — Amazon SQS and SNS ✅ - **Scheme:** `sqs:`, `sns:` - **Dependencies:** `AWSSDK.SQS`, `AWSSDK.SimpleNotificationService` - **Producer/Consumer:** SQS send (single and list bodies) and receive; SNS publish - **Key features:** FIFO queues and topics, message attributes ↔ headers, redelivery after the visibility timeout and its extension for long handlers, batch mode, SNS-to-SQS subscription, LocalStack endpoints --- ### HTTP, RPC & Realtime #### `redb.Route.Http` — HTTP ✅ - **Scheme:** `http:`, `https:` - **Dependencies:** 0 (BCL `HttpClient`; ASP.NET optional for consumer) - **Producer:** HTTP client (GET/POST/PUT/DELETE) - **Consumer:** built-in HTTP server (webhook receiver) - **Key features:** method/timeout, `throwOnError`, headers ↔ exchange headers, Basic / Bearer auth, CORS, multipart, streaming - **DSL example:** ```csharp .To("https:api.example.com/orders?method=POST&timeout=30000") .From("http:0.0.0.0:8080/webhook?methods=POST") ``` #### `redb.Route.Grpc` — gRPC ✅ - **Scheme:** `grpc:` - **Dependencies:** `Grpc.Net.Client` - **Producer:** unary + server-streaming + client-streaming + bi-directional calls - **Consumer:** host a gRPC service backed by a route pipeline - **Key features:** TLS, deadlines, metadata ↔ headers, dynamic proto via reflection (optional) #### `redb.Route.WebSocket` — WebSocket ✅ - **Scheme:** `ws:`, `wss:` - **Dependencies:** 0 (BCL `System.Net.WebSockets`) - **Producer:** WebSocket client (send frames) - **Consumer:** built-in WebSocket server (accept connections, broadcast) - **Key features:** text & binary frames, sub-protocols, keep-alive ping/pong, multi-client broadcast #### `redb.Route.SignalR` — ASP.NET SignalR ✅ - **Scheme:** `signalr:` - **Dependencies:** `Microsoft.AspNetCore.SignalR.Client` - **Producer:** invoke hub methods from a route - **Consumer:** subscribe to hub events into a route - **Key features:** groups, users, connection-level auth, automatic reconnect #### `redb.Route.Tcp` — Raw TCP ✅ - **Scheme:** `tcp:` - **Dependencies:** 0 (BCL `System.Net.Sockets`) - **Producer:** TCP client. **Consumer:** TCP server. - **Key features:** framing (`Raw`, text lines, length-prefixed), `maxConnections`, `keepAlive`, `idleTimeout` - **DSL example:** ```csharp .From("tcp:0.0.0.0:9000?lengthPrefixed=true&maxConnections=100") .To("tcp:192.0.2.10:9000?textLine=true") ``` --- ### Web Services & B2B #### `redb.Route.Soap` — SOAP / WSDL ✅ - **Scheme:** `soap:`, `soaps:` - **Producer:** call SOAP services. **Consumer:** host SOAP endpoints. - **Key features:** SOAP 1.1 / 1.2, faults, header planes, WS-Security (UsernameToken, XML Signature, XML Encryption), MTOM #### `redb.Route.As2` — AS2 (RFC 4130) ✅ - **Scheme:** `as2:`, `as2s:` - **Dependencies:** `MimeKit` - **Producer/Consumer:** send and receive signed and encrypted S/MIME business documents with MDN receipts #### `redb.Route.As4` — AS4 (OASIS ebMS 3.0) ✅ - **Scheme:** `as4:`, `as4s:` - **Dependencies:** `MimeKit`, `BouncyCastle.Cryptography` - **Producer/Consumer:** the eDelivery AS4 common profile, one-way and two-way push: signed and encrypted user messages answered with signed receipts --- ### Files & Object Storage #### `redb.Route.File` — Local filesystem ✅ - **Scheme:** `file:` - **Dependencies:** 0 (BCL `System.IO`) - **Producer:** write files (Append / Overwrite / TempRename for atomicity) - **Consumer:** directory polling with filters - **Key features:** dynamic `fileName` via Simple expressions (`${header.orderId}.json`), `fileExist` strategy, `noop` / `moveTo` / `delete`, `idempotent` (skip already processed), glob `include` / `exclude`, `recursive`, `sortBy`, `charset`, `tempPrefix` - **DSL example:** ```csharp .From("file:C:/input?include=*.csv&noop=true&idempotent=true&delay=5000") .To("file:C:/output?fileName=${header.orderId}.json&fileExist=Append") ``` #### `redb.Route.Ftp` — FTP / FTPS ✅ - **Scheme:** `ftp:` (FTPS with `useFtps=true`) - **Dependencies:** `FluentFTP` - Same option surface as File (`include`, `exclude`, `moveTo`, `delete`, `noop`, `idempotent`, `tempPrefix`). - **Key features:** active/passive mode, binary/ascii, explicit/implicit TLS (FTPS), client certificates, recursive listing #### `redb.Route.Sftp` — SFTP (SSH) ✅ - **Scheme:** `sftp:` - **Dependencies:** `SSH.NET` - **Producer:** upload to remote server. **Consumer:** poll remote directory. - **Key features:** auth via `username/password` or `privateKey`, `knownHosts` host-key verification, atomic upload via `tempPrefix`, `stepwise` cd compatibility mode - **DSL example:** ```csharp .From("sftp:sftp.example.com/incoming?username=user&privateKeyPath=~/.ssh/id_rsa&delay=30000") .To("sftp:sftp.example.com/outgoing?username=user&password=xxx&tempPrefix=.tmp") ``` #### `redb.Route.S3` — Amazon S3 ✅ - **Scheme:** `s3:` - **Dependencies:** `AWSSDK.S3` - **Producer:** put objects, multi-part upload, presigned URLs - **Consumer:** list/poll bucket prefix (event-driven via SQS notifications planned in Phase 4) - **Key features:** dynamic `key` via Simple expressions, server-side encryption (SSE-S3 / SSE-KMS), storage class, `moveTo` / `delete` post-processing, idempotency, S3-compatible endpoints (MinIO, Ceph, Wasabi) --- ### Email, Directory & Mobile #### `redb.Route.Mail` — SMTP + POP3 + IMAP ✅ - **Scheme:** `smtp:`, `pop3:`, `imap:` - **Dependencies:** `MailKit` - **Components:** `SmtpComponent`, `Pop3Component`, `ImapComponent` - **Key features:** SMTP send (To/CC/BCC from headers, body → email body, attachments via `MimePart[]`), POP3 polling with `delete=true`, IMAP polling + **IDLE push**, folder select, unseen filter, full TLS/STARTTLS - **DSL example:** ```csharp .To("smtp:mail.example.com:587?username=bot@ex.com&password=xxx&security=StartTls") .From("imap:mail.example.com:993?username=inbox@ex.com&password=xxx&folder=INBOX&fetchFilter=Unseen&security=Ssl") ``` #### `redb.Route.Ldap` — LDAP / Active Directory ✅ - **Scheme:** `ldap:` - **Dependencies:** `Novell.Directory.Ldap.NETStandard` - **Producer:** search / add / modify / delete entries, bind for authentication - **Consumer:** poll for changes (changelog or full-diff) - **Key features:** simple bind + SASL (GSSAPI / DIGEST-MD5), StartTLS, paged search, referrals, attribute mapping ↔ exchange headers #### `redb.Route.Firebase` — Firebase: Cloud Messaging, Firestore, Cloud Storage ✅ - **Scheme:** `fcm:` (Cloud Messaging), `fstore:` (Firestore), `fbstorage:` (Cloud Storage) - **Dependencies:** `FirebaseAdmin`, `Google.Cloud.Firestore`, `Google.Cloud.Storage.V1` - **Cloud Messaging producer:** push notifications to devices / topics / condition expressions; Android / iOS / Web payloads, topic management, multicast, dry-run - **Firestore:** CRUD, queries and batch writes (producer); realtime snapshot listener (consumer) - **Cloud Storage:** upload, download, delete, copy, list, metadata #### `redb.Route.Telegram` — Telegram Bot API ✅ - **Scheme:** `telegram:` - **Dependencies:** `Telegram.Bot` - **Producer:** send, reply to, edit and delete messages, documents and photos; answer callback queries - **Consumer:** long polling or webhook - **Key features:** inline and reply keyboards, Mini App data, attachment download, rate-limit (HTTP 429) handling --- ### IoT & Enterprise Messaging #### `redb.Route.MqttNet` — MQTT 3.1 / 3.1.1 / 5.0 ✅ - **Scheme:** `mqtt:` (TLS with `useTls=true`) - **Dependencies:** `MQTTnet` - **Producer:** publish to topic. **Consumer:** subscribe with QoS 0/1/2. - **Key features:** TLS + client certs, last-will-and-testament, retained messages, MQTT 5 user properties ↔ exchange headers, shared subscriptions, session persistence #### `redb.Route.IbmMq` — IBM MQ ✅ - **Scheme:** `wmq:` - **Dependencies:** `IBMMQDotnetClient` (managed .NET client) - **Producer:** send to queues / topics (immediate / transacted / RPC) - **Consumer:** MQGET polling with backout support - **Key features:** transactions (MQCMIT / MQBACK), `backoutThreshold` + DLQ, RPC with dynamic reply queue, persistence levels, TLS via `sslCipherSpec` / `sslPeerName`, W3C distributed tracing in message properties, full MQMD headers ↔ exchange headers - **DSL example:** ```csharp .From(Wmq.Queue("ORDERS.IN") .Host("mq.example.com").Port(1414) .Channel("DEV.APP.SVRCONN").QueueManager("QM1") .Transacted(true) .BackoutThreshold(3).BackoutQueue("ORDERS.DLQ")) ``` #### `redb.Route.AzureServiceBus` — Azure Service Bus ✅ - **Scheme:** `asb:` - **Dependencies:** `Azure.Messaging.ServiceBus` - **Producer:** send to queue / topic, scheduled messages, batches - **Consumer:** queue / subscription receivers, **sessions**, dead-letter management - **Key features:** auto-renew lock, peek-lock vs receive-and-delete, dead-letter queue routing, MSI / connection-string auth, distributed tracing --- ### Data Stores #### `redb.Route.Sql` — SQL via pure ADO.NET ✅ - **Scheme:** `sql:` - **Dependencies:** `System.Data.Common` (BCL — 0 external; driver is your choice: `Npgsql`, `Microsoft.Data.SqlClient`, `MySqlConnector`, …) - **Components:** `SqlComponent` (parameterised SQL), `SqlStoredComponent` (stored procedures) - **Key features:** - Producer: execute SELECT / INSERT / UPDATE / DELETE with parameter binding from exchange headers / body - Consumer: poll a query, optionally update a `processed_at` column for at-least-once semantics - `SqlIdempotentRepository` — standalone `IIdempotentRepository` backed by a raw ADO.NET table (no `redb.Core` required) - **DSL example:** ```csharp .From("sql:select id, payload from inbox where processed_at is null?onConsumeBatchComplete=update inbox set processed_at = now() where id = :id&delay=5000") .To("sql:insert into orders(id, total) values(:id, :total)") ``` #### `redb.Route.Elasticsearch` — Elasticsearch / OpenSearch ✅ - **Scheme:** `elasticsearch:`, `es:` - **Dependencies:** `Elastic.Clients.Elasticsearch` - **Producer:** index / update / delete documents, bulk operations - **Consumer:** scroll / search-after polling - **Key features:** dynamic index names via Simple expressions, pipeline ingestion, refresh policies, version & sequence-number for optimistic concurrency, OpenSearch wire-compatible --- ### Scheduling & Bridges #### `redb.Route.Quartz` — Quartz.NET scheduler ✅ - **Scheme:** `cron:` (cron expressions), `qtimer:` (interval timers) - **Dependencies:** `Quartz` - **Consumer only:** trigger a route on a cron schedule / interval - **Key features:** cron expressions, misfire instructions, named scheduler reuse, clustered scheduler (via Quartz JobStore) #### `redb.Route.Core` — bridge to `redb.Core` ✅ - **Dependencies:** `redb.Route` + `redb.Core` - **Extension methods** to access `IRedbService` from a route pipeline - **RedbIdempotentRepository** — `IIdempotentRepository` backed by `redb.Core` (typed `IdempotentEntryProps` object, no raw SQL) #### `redb.Route.Cache` — cache as a route step ✅ - **Scheme:** `cache:` - **Dependencies:** `Microsoft.Extensions.Caching.Memory` - Get, put, remove and clear over `IMemoryCache` (in process) or any `IDistributedCache` registered in DI (Redis, SQL Server, …) #### `redb.Route.Exec` — run processes ✅ - **Scheme:** `exec:` - Run a command as a route step or on a fixed schedule, with an allowlist, working directory and environment overrides, and timeouts --- ### AI #### `redb.Route.Llm` — language models as endpoints ✅ - **Scheme:** `llm:`, `embed:` (embeddings), `knowledge:` (retrieval), `stt:` (speech to text) - A model is an addressable endpoint like any broker: prompts in, completions out; routes marked with `.AsLlmTool("name")` become tools the model can call #### `redb.Route.Llm.Mcp` — Model Context Protocol client ✅ - **Scheme:** `mcp:` (`mcp://server/tool` calls a tool) - Starts or connects to MCP servers (stdio, HTTP + SSE), discovers their tools and offers them to `redb.Route.Llm` --- ## Implementation Roadmap ### Phase 1 — Transport (✅ Complete) | # | Package | Dependencies | Status | |---|---|---|---| | 1 | `redb.Route.Kafka` | Confluent.Kafka | ✅ Done | | 2 | `redb.Route.RabbitMQ` | RabbitMQ.Client | ✅ Done | | 3 | `redb.Route.Redis` | StackExchange.Redis | ✅ Done | | 4 | `redb.Route.Amqp` | AMQPNetLite.Core | ✅ Done | | 5 | `redb.Route.Http` | 0 (BCL + ASP.NET) | ✅ Done | | 6 | `redb.Route.Tcp` | 0 (BCL) | ✅ Done | | 7 | `redb.Route.WebSocket` | 0 (BCL) | ✅ Done | | 8 | `redb.Route.Grpc` | Grpc.Net.Client | ✅ Done | | 9 | `redb.Route.File` | 0 (BCL) | ✅ Done | | 10 | `redb.Route.Ftp` | FluentFTP | ✅ Done | ### Phase 2 — Integrations (✅ Complete) | # | Package | Dependencies | Status | |---|---|---|---| | 1 | `redb.Route.Mail` | MailKit | ✅ Done | | 2 | `redb.Route.Quartz` | Quartz | ✅ Done | | 3 | `redb.Route.Sftp` | SSH.NET | ✅ Done | | 4 | `redb.Route.IbmMq` | IBMMQDotnetClient | ✅ Done | | 5 | `redb.Route.Sql` | System.Data.Common (ADO.NET) | ✅ Done | | 6 | `redb.Route.Ldap` | Novell.Directory.Ldap.NETStandard | ✅ Done | | 7 | `redb.Route.MqttNet` | MQTTnet | ✅ Done | | 8 | `redb.Route.SignalR` | Microsoft.AspNetCore.SignalR.Client | ✅ Done | ### Phase 3 — Cloud & Enterprise (✅ Complete) | # | Package | Dependencies | Status | |---|---|---|---| | 1 | `redb.Route.AzureServiceBus` | Azure.Messaging.ServiceBus | ✅ Done | | 2 | `redb.Route.S3` | AWSSDK.S3 | ✅ Done | | 3 | `redb.Route.Elasticsearch` | Elastic.Clients.Elasticsearch | ✅ Done | | 4 | `redb.Route.Firebase` | FirebaseAdmin | ✅ Done | ### Phase 4 — Protocols, B2B and AI (✅ Complete) | # | Package | Dependencies | Status | |---|---|---|---| | 1 | `redb.Route.Sqs` (`sqs:`, `sns:`) | AWSSDK.SQS, AWSSDK.SimpleNotificationService | ✅ Done | | 2 | `redb.Route.Telegram` | Telegram.Bot | ✅ Done | | 3 | `redb.Route.Soap` | 0 (BCL) | ✅ Done | | 4 | `redb.Route.As2` | MimeKit | ✅ Done | | 5 | `redb.Route.As4` | MimeKit, BouncyCastle.Cryptography | ✅ Done | | 6 | `redb.Route.Cache` | Microsoft.Extensions.Caching.Memory | ✅ Done | | 7 | `redb.Route.Exec` | 0 (BCL) | ✅ Done | | 8 | `redb.Route.Llm` | redb.Route.Llm.Abstractions, redb.Route.Core | ✅ Done | | 9 | `redb.Route.Llm.Mcp` | redb.Route.Llm.Abstractions | ✅ Done | ### Phase 5 — Planned No dates or versions are promised; order within a group reflects current priority. #### AWS | Package | Dependencies | Notes | |---|---|---| | `redb.Route.Dynamodb` | AWSSDK.DynamoDBv2 | Key-value / document store + DynamoDB Streams consumer | #### Azure | Package | Dependencies | Notes | |---|---|---| | `redb.Route.AzureEventHub` | Azure.Messaging.EventHubs | High-throughput event streaming (Kafka-compatible) | | `redb.Route.AzureBlob` | Azure.Storage.Blobs | Blob storage — Producer + Consumer (poll prefix / Event Grid) | | `redb.Route.CosmosDb` | Microsoft.Azure.Cosmos | Cosmos DB document store + Change Feed consumer | #### Google Cloud | Package | Dependencies | Notes | |---|---|---| | `redb.Route.GooglePubSub` | Google.Cloud.PubSub.V1 | Pub/Sub messaging | | `redb.Route.GoogleStorage` | Google.Cloud.Storage.V1 | GCS object storage | #### Cloud-native / Cross-cloud | Package | Dependencies | Notes | |---|---|---| | `redb.Route.Nats` | NATS.Net | NATS Core + JetStream (durable consumers, KV, object store) | | `redb.Route.Pulsar` | DotPulsar | Apache Pulsar — multi-tenant streaming with tiered storage | | `redb.Route.MongoDB` | MongoDB.Driver | Document store + Change Streams consumer | | `redb.Route.Clickhouse` | ClickHouse.Client | Analytics / OLAP — bulk insert producer, streaming consumer | | `redb.Route.Neo4j` | Neo4j.Driver | Graph database (Cypher producer) | #### Specialised | Package | Dependencies | Notes | |---|---|---| | `redb.Route.Saga` | (in-house) | Saga / Compensation orchestration on top of routes | | `redb.Route.Slack` | Slack.NetStandard | Slack incoming / outgoing webhooks + Events API consumer | | `redb.Route.Twilio` | Twilio | SMS / WhatsApp / Voice | | `redb.Route.S7` | S7NetPlus | Siemens S7 PLC — industrial automation read / write | > Have a connector you need that is not on this list? Open an issue at > [github.com/redbase-app/redb-route/issues](https://github.com/redbase-app/redb-route/issues). --- ## Common Patterns All connectors follow the same architectural conventions, which makes writing a new one mostly mechanical: - **Class hierarchy:** `ComponentBase` → `EndpointBase` → `IProducer` / `IConsumer` - **Options binding:** URI parameters parsed via `EndpointOptions.BindFromUri()` into a strongly-typed options class - **Connection management:** factories registered in the route registry, retrieved with `context.GetFromRegistry()` - **Transactions:** components opt in via `ITransactedAction` (Kafka, RabbitMQ, IbmMq, Sql, …) - **Error handling:** `DefaultErrorHandler` / `DeadLetterChannel` / per-route `OnException()` clauses - **Idempotency:** any consumer can plug in an `IIdempotentRepository` (in-memory, SQL, redb) - **Headers ↔ protocol metadata:** consistent two-way mapping in every connector - **Testing:** unit tests + Testcontainers-based integration tests per TFM (`net10.0` / `net11.0`) - **NuGet:** every connector ships as an independent package; you pull only what you need Path: redb-route/CONTRIBUTING.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/CONTRIBUTING.md ---- # Contributing to redb.Route Thank you for your interest in redb.Route! ## How to Contribute ### Reporting Issues - Use [GitHub Issues](https://github.com/redbase-app/redb-route/issues) for bug reports - Use [GitHub Discussions](https://github.com/redbase-app/redb-route/discussions) for questions and feature requests ### Bug Reports Please include: - Package name and version (e.g. `redb.Route.Kafka 1.0.0-preview.1`) - .NET version - Transport / broker version where applicable (e.g. Kafka 3.6, RabbitMQ 3.13) - Minimal route definition to reproduce the issue - Expected vs actual behavior (including exception message and stack trace if any) ### Feature Requests Open a [Discussion](https://github.com/redbase-app/redb-route/discussions/categories/ideas) with: - Description of the feature - Use case / motivation - Example code showing the desired DSL or API (if applicable) ## Code Contributions ### Scope This repository contains the full source of redb.Route — the core engine, all transports, and adapter packages. Pull requests for bug fixes, documentation improvements, and new transport connectors are welcome. ### Getting Started 1. Fork the repository 2. Create a branch: `git checkout -b fix/kafka-ack-handling` 3. Make your changes (see guidelines below) 4. Run existing tests if you have access to the required brokers 5. Submit a Pull Request with a clear description ### Code Guidelines - Follow the existing code style — C# 12, `nullable enable`, `implicit usings` - Use English for all code identifiers, XML doc summaries, and error messages - Add `/// ` for all new public classes and methods - Do not use `dynamic` — prefer concrete types and strong typing - Use LINQ where appropriate; avoid unnecessary nested loops - Every new transport must implement `IComponent` and register a URI scheme - Every new transport must have a fluent builder with `implicit operator string` - New processors must implement `IProcessor` or `IAsyncProcessor` - Do not suppress `CS1591` — every public member must have XML documentation ### New Transport Checklist Registration and API: - [ ] Implements `IComponent` and registers URI scheme - [ ] Has a fluent builder class (e.g. `MyTransportBuilder`) with `implicit operator string` - [ ] Registered via `AddRedbRouteXxx()` extension on `IServiceCollection` Options and connections: - [ ] Options class inherits from `EndpointOptions` (or is standalone with XML docs), binds strictly, and `Validate()` fails with errors that name the option - [ ] Every secret is marked `[Sensitive]`; connection options carry `[ConnectionParameter]` / `[ConnectionFactoryReference]`; options that apply to one side only carry `[EndpointRole]` - [ ] A connection factory can be registered by name and referenced from the endpoint URI Lifecycle: - [ ] A polling or pull consumer derives from `DrainableConsumer`; a callback consumer uses `InflightDrainGuard` and says why - [ ] `Start` throws when the broker cannot be reached, so the route's start retry takes over - [ ] A connection lost while the route runs is re-established with back-off; the endpoint reports the outage through its health (`TransportCondition`), with one log line on loss and one on recovery - [ ] Stop drains in-flight messages within the shutdown timeout; what is still unsettled goes back to the broker, never acknowledged - [ ] The producer derives from `ConnectableProducer` and reconnects on the next send after a loss - [ ] Connections are released in `DisposeAsync` Delivery: - [ ] `ackMode` (`manual` by default, `auto`) where the protocol settles per message, or the README says why not - [ ] A failed message is redelivered in a way the broker counts; poison messages are bounded (broker counter and dead letter, or a connector option) and the default is documented - [ ] Sends inside a transacted route are deferred through `TransactedActions.Defers` with a `transacted` option; no exactly-once claim unless the broker commits output and input together - [ ] Concurrency through `ConcurrencyOption` (accepts `auto`); in-flight bounded by the protocol's credit; batch mode through `BatchDispatcher` where the protocol receives in batches; the ordering guarantee is written down per mode Headers and telemetry: - [ ] Headers use a consistent `redbXxx.` prefix, declared in one class, and pass through an `IHeaderFilterStrategy` - [ ] Trace context is injected on send and extracted on receive - [ ] Transport spans through `RouteTelemetryExtensions`; failures through `RecordFailure`; the endpoint's BytesOut is recorded; `RecordError` is given the exception Tests and docs: - [ ] Unit tests run without a broker; integration tests run against the broker in a container on `net10.0` and `net11.0` - [ ] Tests cover broker down at start, broker restarted while running, stop with messages in flight, failure then redelivery, poison to dead letter, `ackMode=auto`, transacted commit and rollback, header round trip and the concurrency bound, or say why an item does not apply - [ ] Has a `README.md` with NuGet badge, Installation, Usage, options, the delivery guarantee, Fluent Builder API table, and "Part of" footer - [ ] The scheme is listed in [CONNECTORS_ROADMAP.md](CONNECTORS_ROADMAP.md) - [ ] A changelog entry describes the change for users ### Commit Messages Use the format: `type(scope): description` Examples: - `fix(kafka): handle null message key in consumer` - `feat(s3): add server-side encryption options` - `docs(http): document named URL parameter binding` ## License By contributing, you agree that your contributions will be licensed under the [Apache License 2.0](LICENSE). Path: redb-route/Directory.Build.props 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/Directory.Build.props ---- net10.0;net11.0 enable enable latest true false redbase redbase REDB Route Copyright В© redbase 2026 Apache-2.0 https://redbase.app https://github.com/redbase-app/redb-route git 4.8.0 4.8.0 Path: redb-route/Directory.Build.targets 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/Directory.Build.targets ---- true <_RedbCentral>true <_RedbNetMajor>$([System.Version]::Parse('$(TargetFrameworkVersion.TrimStart(`v`))').Major) 3.1.12 4.18.1 10.0.15 11.0.0 $(RedbSecAspNetCoreVersion) 10.0.15 11.0.0 10.0.15 true $(WarningsAsErrors);NU1506 true all moderate $(WarningsAsErrors);NU1902;NU1903;NU1904 Path: redb-route/Directory.Packages.props 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/Directory.Packages.props ---- true $(Version) Path: redb-route/EXPRESSIONS.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/EXPRESSIONS.md ---- # The redb.Route expression language What you can write in a condition, a value or a `${...}` template, and what you get. Every table marked for running is evaluated by `ExpressionsGuideExamplesTests` on the exchange of section 0: the results below are what the engine gives, not what it is meant to give. --- ## 0. The exchange behind the examples ``` header.a = 42 header.b = 3 header.neg = -7 header.zero = 0 header.price = 2.5 header.s = "Hello World" header.flag = true header.off = false header.Content-Type = "text/xml" header.empty = "" header.O'Brien = "obrien" header.user = { Name = "Ann", Age = 30, Active = true, Manager = { Name = "Bob", Age = 51 } } header.list = [5, 1, 9] header.when = 2026-08-28 10:30 UTC header.redbFile.Name = "orders/a.xml" header.redbFile.NameOnly = "a" (as a file consumer sets them) property.count = 7 property.items = ["p", "q", "r"] property.nums = [1, 2, 3, 4] property.cfg = { enabled = true, limit = 5 } property.counter = 10 body = "payload" exception.Message = "boom" registry: "pricing" and "pricing-rules", both a bean with Gross(int qty, double price), IsGold(string name), Badge(string name, int points), Touch(string), a Rate property, and CheckAsync-style methods where noted; "limits.max", the number 100 ``` --- ## 1. Three positions The same text means different things depending on where it is written. This is the language's main rule. | Position | In the DSL | What happens to the text | |---|---|---| | **String** | `.SetHeader("k", "a>b")`, `Rabbit.Queue("q").Password("p@ss(1)")` | nothing: a literal, whatever it contains | | **Template** | `.SetHeader("k", Expr("Hi, ${header.s}!"))`, `.ToD("kafka://${header.region}")`, `.Log("id=${header.a}")` | text as written; each `${...}` is evaluated | | **Expression** | `.SetBody(Expr("header.a + 1"))`, `.Transform(Expr("upper(body)"))` | the whole text is an expression | | **Condition** | `.Filter("header.a > 10")`, `.When("header.flag")`, `.LoopWhile("property.i < 3")`, `.Validate("header.a > 0")` | an expression whose result is read as yes or no | Inside `${...}` and in an expression the language is the same: `${...}` only marks an expression inside text. Whitespace around operators carries no meaning: `header.a>10` and `header.a > 10` are the same. In route markup an attribute typed as an expression (`expr=`, `correlation=`, `while=`, ...) is an expression, and a `${...}` in it makes it a template; `value=` is a literal. **Bare text in an expression.** A text without an arithmetic operator (`+ - * /`) outside quotes is a lookup when it names one (`header.a`, `body`) and otherwise the text itself, as in Apache Camel: `hello`, `plain text`, `key=value`. A text with one is arithmetic and must be whole: it parses to its end, and each bare word in it is a value (a root such as `header.a`, `property.x`, `body`, a number, or quoted text). Otherwise it is an error naming the place: `1 +` ends where a value is expected, `header.a+b` has `'b' at position 10 is not a value`, and `application/json` has `'application' at position 1 is not a value`. Write text in quotes: `'application/json'`. --- ## 2. Reading the exchange | Expression | Result | |---|---| | `header.a` | `42` | | `header.s` | `Hello World` | | `header.missing` | `null` | | `property.count` | `7` | | `body` | `payload` | | `header.user.Name` | `Ann` | | `header.user.Manager.Name` | `Bob` | | `header.user.Age` | `30` | | `header.list.Count` | `3` | | `header.s.Length` | `11` | | `property.cfg.enabled` | `True` | | `property.cfg.limit` | `5` | | `property.items.Count` | `3` | | `header.list[1]` | `1` | | `property.items[0]` | `p` | `attachments.size` is the number of attachments of the In message and `attachments[0].fileName` the file name of the first (`name`, `contentType`, `contentId`, `length` likewise). An object reads the same wherever it lies: in a header, in a property or as the body. Members are found by name, case-insensitive, public fields included; a dictionary answers `.key` and `['key']`. Member access is null-safe by default: a member of a missing value is `null` (there is no separate `?.` operator to write). **Names with a dot or a dash.** The literal name comes first: `header.dotted.key` is the header named `dotted.key` if there is one, else the member `key` of the header `dotted`. In a template the same rule keeps a dashed name readable: `${header.Content-Type}` gives `text/xml`. In a bare expression `header.Content-Type` would be a subtraction, so it is an error that says so: `'header.Content-Type' at position 1 reads as a subtraction: a name with a dash is written ${header.Content-Type}`. --- ## 3. Arithmetic | Expression | Result | |---|---| | `header.a + header.b` | `45` | | `header.a - header.b` | `39` | | `header.a * 2` | `84` | | `header.a / 4` | `10.5` | | `(header.a + header.b) * 2` | `90` | | `header.a + 1.5` | `43.5` | | `-header.a` | `-42` | | `header.price * 2` | `5` | | `header.a % 5` | `2` | | `header.a % header.zero` | `null` | Precedence is the usual one and parentheses work. Increments **change the exchange**, for headers and properties, prefix and postfix, in an expression and inside `${...}`. A missing value starts at 0; a value that is there but not a number is an error naming it (`header.x++: the value 'abc' (String) is not a number.`): | Expression | Returns | Afterwards | |---|---|---| | `header.a++` | `42` | `header.a = 43` | | `++header.a` | `43` | `header.a = 43` | | `header.a--` | `42` | `header.a = 41` | | `--header.a` | `41` | `header.a = 41` | | `property.counter++` | `10` | `property.counter = 11` | | `++property.counter` | `11` | `property.counter = 11` | --- ## 4. Comparison and logic | Condition | Result | |---|---| | `header.a > 10` | `True` | | `header.a>10` | `True` | | `header.a == 42` | `True` | | `header.s == 'Hello World'` | `True` | | `header.s != 'x'` | `True` | | `header.missing == null` | `True` | | `header.a >= 42 AND header.b < 5` | `True` | | `header.a > 100 OR header.b < 5` | `True` | | `header.a > 10 XOR header.b > 10` | `True` | | `NOT header.flag` | `False` | | `!header.off` | `True` | | `header.a > 10 && header.b < 5` | `True` | | `header.s == 'a > b'` | `False` | | `header.flag OR bean:nobody.Check()` | `True` | | `header.off AND bean:nobody.Check()` | `False` | | `header.s =~ 'hello world'` | `True` | | `header.s == 'hello world'` | `False` | | `header.a =~ '42'` | `True` | | `header.a range '1..42'` | `True` | | `header.price range '2.5..3'` | `True` | | `header.a not range '1..10'` | `True` | | `header.missing range '1..10'` | `False` | Operators: `== != =~ > < >= <=`, `range` and `not range`, `in` and `not in` (section 7), `AND OR XOR NOT` (any case), `&& || !`. String literals take single or double quotes; an operator inside quotes is text. Equality is not truthiness: `42 == 'x'` is false. - **`==` on two strings is exact**, case included. **`=~`** is Apache Camel's equals-ignoring-case: two strings compare ignoring case (ordinal, no culture); any other pair compares as `==`. There is no negated form: write `!(header.s =~ 'x')`. - **Numbers of different types** are equal when their values are: `3 == 3.0` and `3 == '3'` are true, `3 == 5.0` is false. - **`range 'from..to'`** is true for a number within both ends, inclusive, as in Apache Camel; `not range` is its opposite. The right side is a quoted literal of two numbers, decimals allowed, read when the expression is compiled: a malformed one (`'1-10'`) or one whose start is above its end (`'10..1'`) is an error at load and in `check` / `pack`. A missing value is in no range. A text that is not a number is an error naming it: `header.s range '1..10': the value 'Hello World' (String) is not a number.` A numeric text (`'12'`) counts. - **`range` is an operator only after an operand.** Elsewhere it is a name: `header.range` reads the header called `range`. `AND` and `OR` short-circuit: the right side runs only when the left one does not decide, so in the last two rows the call to a bean that does not exist never happens. `XOR` needs both sides and evaluates both. --- ## 5. Ternary and `??` | Expression | Result | |---|---| | `header.a > 10 ? 'big' : 'small'` | `big` | | `header.flag ? header.a : header.b` | `42` | | `header.missing ?? 'default'` | `default` | | `header.a ?? 0` | `42` | | `header.a ?? bean:nobody.Check()` | `42` | `??` evaluates its right side only when the left one is `null`: the last row never calls the bean that does not exist. --- ## 6. Strings A function `f(x, ...)` and a method `x.f(...)` both work. | Expression | Result | |---|---| | `upper(header.s)` | `HELLO WORLD` | | `lower(header.s)` | `hello world` | | `trim(' x ')` | `x` | | `length(header.s)` | `11` | | `concat(header.s, '!')` | `Hello World!` | | `substring(header.s, 0, 5)` | `Hello` | | `substring(header.s, 6)` | `World` | | `replace(header.s, 'World', 'Route')` | `Hello Route` | | `contains(header.s, 'World')` | `True` | | `startswith(header.s, 'Hello')` | `True` | | `endswith(header.s, 'World')` | `True` | | `header.s.toUpper()` | `HELLO WORLD` | | `header.s.substring(0, 5)` | `Hello` | | `header.s.replace('o', '0')` | `Hell0 W0rld` | | `header.s.indexOf('W')` | `6` | A method not in the language's own list is looked up on the CLR object, so `header.list.Count` and `header.user.Manager.Name` need no special support. --- ## 7. Numbers, collections, dates | Expression | Result | |---|---| | `count(property.items)` | `3` | | `sum(property.nums)` | `10` | | `avg(property.nums)` | `2.5` | | `abs(header.neg)` | `7` | | `round(header.price)` | `2` | | `round(2.567, 2)` | `2.57` | | `min(header.a, header.b)` | `3` | | `min(property.nums)` | `1` | | `max(header.list)` | `9` | | `dateformat(header.when, 'yyyy-MM-dd')` | `2026-08-28` | | `dateformat(header.when, 'HH:mm')` | `10:30` | | `dateformat(dateadd(header.when, 1, 'day'), 'yyyy-MM-dd')` | `2026-08-29` | | `datediff('2026-01-03', '2026-01-01', 'days')` | `2` | A date written bare is arithmetic (`2026-08-28` is `1990`); quote it (`'2026-08-28'`) or read it from a header. `round` rounds half to even, as .NET does (`2.5` gives `2`). `now()` is the current time and `uuid()` a new GUID (`uuid('N')` compact); both change on every evaluation. `stats(target, metric)` reads an endpoint's measurements (see [METRICS.md](METRICS.md)) and `messageHistory('compact')` the exchange's trail. `attachmentContent('name')`, `attachmentContentAsText`, `attachmentContentType` and `attachmentHeader` read an attachment of the In message. Expressions are synchronous, so these functions read a whole attachment; they are meant for small parts. --- ## 8. JSON and XML in the body | Template | Result | |---|---| | `${jpath($.order.id)}` | `7` | | `id=${jpath($.order.id)} total=${jpath($.order.total)}` | `id=7 total=150.5` | | `${jsonpath:$.order.id}` | `7` | | Template | Result | |---|---| | `${xpath(/order/id)}` | `7` | | `${xpath:/order/id}` | `7` | Apache Camel's spellings `${jsonpath:path}` and `${xpath:path}` mean `jpath('path')` and `xpath('path')`. The spelling takes the whole inside of its `${...}`: the path runs to the closing brace, and text may stand around the placeholder (`id=${jsonpath:$.order.id}`). Inside `${...}` a path may be written bare: `${jpath($.order.id)}`. In a bare expression and in a condition the path is **quoted**: `jpath('$.order.id')`, `xpath('/order/id')`; unquoted, `$` and `/` read as operators and the expression does not compile (it fails when the route is built, never silently). `jpath` follows RFC 9535 (JsonPath.Net): `.name`, `['name']`, `[0]`, slices, `[*]`, `..`, filters such as `[?(@.price < 10)]` and the standard functions. --- ## 9. Templates `${...}` | Template | Result | |---|---| | `Hello, ${header.s}!` | `Hello, Hello World!` | | `${header.user.Name} is ${header.user.Age}` | `Ann is 30` | | `a=${header.a}, b=${header.b}, sum=${header.a + header.b}` | `a=42, b=3, sum=45` | | `${header.a + 1}` | `43` | | `${header.a > 10}` | `True` | | `${property.cfg.limit > 3 ? 'over' : 'under'}` | `over` | | `${count(property.items)} items` | `3 items` | | `${header.Content-Type}` | `text/xml` | | `${header.price}` | `2.5` | | `${exception.Message}` | `boom` | | `[${header.missing}]` | `[]` | **A whole placeholder keeps its type.** `SetHeader("n", Expr("${header.a}"))` stores the `int` 42, not the text "42"; `${header.a > 10}` stores a `bool`. A template with text around its placeholders is always a string. Numbers and dates render the same on every machine: `2.5`, and dates in ISO 8601. A placeholder that does not parse (`${}`) fails when the route is built, not on every message. ### Braces and quoting A placeholder starts at `${` and ends at the `}` that balances it. Everything else in a template is text. | Template | Result | |---|---| | `${concat('a', '}', 'b')}` | `a}b` | | `{${header.a}}` | `{42}` | | `${}` | `${}` | | `${header.O'Brien}` | `obrien` | | `echo \${HOME} for ${header.s}` | `echo ${HOME} for Hello World` | | `text ${body` | `error: unclosed '${' at position 6 of "text ${body": the placeholder has no closing '}'.` | - A `}` inside a quoted literal belongs to the literal. - A plain `{` does not open anything; the outer braces of `{${header.a}}` stay text. - `${}` is not a placeholder; it stays as written. - A placeholder may hold another one only as an argument of a `bean:` call (section 11); elsewhere a `${` inside an expression is an error naming its position. The general form `${header.a + ${header.b}}` is not supported. - A quote that never ends is an ordinary character: `${header.O'Brien}` reads the header `O'Brien`. - A `${` that nothing closes is an error where the template is compiled, at load for a route file, and `check` / `pack` report it at the attribute. - A literal `${` is written `\${`: it opens nothing and renders as `${`. A backslash meant as text right before a placeholder (`\\${header.x}`) has no spelling. ### A format suffix `${value:F2}` | Template | Result | |---|---| | `${header.price:F2}` | `2.50` | | `${header.a:D5}` | `00042` | | `${header.price * 4:F1}` | `10.0` | A placeholder that ends in a colon and a standard .NET format (one letter and up to two digits: `F2`, `N0`, `D8`) is `format(value, 'F2')` with the invariant culture. The value before the colon is a path or a call (`header.price`, `round(x)`), so a namespace written against its name (`env:X`) is never a format, and a ternary's colon is never one. A custom format (`yyyy-MM-dd`) is written with `format(...)` or `dateformat(...)`. ### File names `${file:name}` | Template | Result | |---|---| | `${file:name}` | `orders/a.xml` | | `archive/${file:name.noext}.done` | `archive/a.done` | Apache Camel's file language reads the headers a file consumer sets on the message. A `${file:key}` takes the whole inside of its `${...}`, the key running to the closing brace, and text may stand around it, as in `archive/${file:name.noext}.done`: | Key | Header | |---|---| | `name`, `onlyname` | `redbFile.Name` | | `name.noext`, `onlyname.noext` | `redbFile.NameOnly` | | `ext`, `name.ext` | `redbFile.Extension`, without the dot (`xml`) | | `parent` | `redbFile.Parent` | | `path`, `absolute.path` | `redbFile.AbsolutePath` | | `relative.path` | `redbFile.RelativePath` | | `length`, `size` | `redbFile.Length` | | `modified` | `redbFile.LastModified` | A message that did not come from a file has no such headers, and the key is empty. A key not in the table is an error when the route is built, listing the keys. The file consumers' own options (`moveTo`, `preMove`, `moveFailed`, `doneFileName`, `idempotentKey`, and S3's `doneFileName`) take the same keys and give the same values, read from the file being handled; the file producers' `tempFileName` reads the file being written (`${file:name}.part`). There a key matches ignoring case (`${FILE:NAME}`), as these options always did; in a template it matches exactly, as in Camel. An unknown key in an option fails when the endpoint is created. ### Configuration values `{{key}}` `{{key}}` and `{{key:default}}` are not part of the expression language: they are configuration placeholders, resolved before the route runs in endpoint URIs, in `enabled=` of a route, in bean values and in `value=` of ``, `` and ``. A key is looked up in this order: 1. `IConfiguration` of the host, with its own sources in the host's order (environment, `appsettings.json`, secrets); 2. the context properties (in Tsak, filled from the context's configuration section); 3. the OS environment, only when the context has no `IConfiguration`. With an `IConfiguration` the host decides whether the environment takes part. A key with no value and no default is an error naming the key. Inside an expression, read a configured value through a header set from `{{key}}`. --- ## 10. Conditions and truthiness A condition is any expression; its result is read by **one rule**: | Value | Reads as | |---|---| | `bool` | itself | | number | not zero | | string | the words `true/false`, `1/0`, `yes/no`, `y/n`, `on/off`; any other text: true when not empty | | `null` | false | | any other object | true | | Condition | Result | |---|---| | `header.flag` | `True` | | `header.off` | `False` | | `header.missing` | `False` | | `header.empty` | `False` | | `property.count` | `True` | | `'no'` | `False` | | `'anything'` | `True` | | `header.user.Age > 18 AND header.user.Active` | `True` | | `count(property.items) >= 3` | `True` | | `${header.flag}` | `True` | | `logical(header.a)` | `True` | The boolean words are English only, so the author's locale never changes what a route means. A condition that does not compile is a build error: `.Filter("header.a >")` throws `ExpressionCompilationException` at `Start()`. **Write a comparison bare.** `${header.kind} == 'order'` renders to text such as `refund == 'order'`, which is non-empty and therefore true. Write `header.kind == 'order'`, or the whole comparison inside the braces. The package gate warns about a condition that compares outside its placeholders. --- ## 11. Registry objects: `bean:` and `ref:` `bean:name.Method(args)` calls a public method of an object in the route context's registry (`AddToRegistry`, or a `` declaration), in any position of the language: a condition, a value, a template. | Expression | Result | |---|---| | `bean:pricing.Gross(header.b, header.price)` | `7.5` | | `${bean:pricing.Gross(${header.b}, ${header.price})}` | `7.5` | | `bean:pricing-rules.Badge(header.user.Name, 7)` | `Ann:7` | | `bean:pricing.Gross(header.b, 2) - 1` | `5` | | `bean:pricing.Touch('x')` | `null` | | Condition | Result | |---|---| | `bean:pricing.IsGold(header.user.Name)` | `True` | | `header.flag && bean:pricing.IsGold('Bob')` | `False` | | Template | Result | |---|---| | `total ${bean:pricing.Gross(header.b, 2)} EUR` | `total 6 EUR` | - **The name** is the registry name without `#`. It may contain dashes (`pricing-rules`). - **The method** is required: `bean:pricing` alone is an error. `bean:pricing.Method` without parentheses calls it with no arguments. A dash after a method without parentheses is a minus: `bean:svc.Count-1` calls `Count`, then subtracts one. - **Arguments** are expressions of the language. Inside a `${bean:...}` placeholder, `${...}` may wrap an argument and means the same as writing it bare. In a bare expression write the arguments bare: a `${` there makes the whole text a template (section 1), so `bean:pricing.Gross(${header.b}, 2)` renders as text instead of calling. - **Binding** follows the `bean:` URI rules: the method by name (any case) and number of arguments; a parameter of type `IExchange`, `IMessage` or `CancellationToken` is filled in and does not count; each value converts to its parameter's type. - **The result** keeps its type; a `void` method gives `null`, which reads as false or empty, as in Apache Camel. - **Synchronous only**, as in Apache Camel's Simple language: a method returning `Task`, `Task`, `ValueTask` or `ValueTask` is refused, with the advice to call it as a step (``). - **When it is resolved.** The bean is looked up on the call's first evaluation in a route context, not when the route is loaded, and the bound method is kept for that context. A missing bean or method is an error naming the call. - **Templates are data.** A payload template (`SetBodyTemplate` and the like) renders under a sandbox in which an expression reads members but never runs code: a method call on an object is refused with `ExpressionSandboxViolationException`. A `bean:` call in a template argument (`args.Set("gold", "bean:...")`) or in the template's own `expr(...)` is refused the same way, so the bean never runs. A `ref:name` or `env:NAME` there is refused too, before the registry or the environment is read; its message names the spelling (`'ref:rules' cannot be read here`), and `Written` carries it. - **The colon touches both sides.** `bean:` and `ref:` are namespaces only when the colon touches the word and the name. In a ternary whose branch is a variable named `bean` or `ref`, keep the spaces: `flag ? bean : other`; `flag?bean:other` is a call and `flag?ref:other` a registry name. ### `env:NAME`, an environment variable `env:NAME` is the OS environment variable `NAME`, as Apache Camel's `${env:NAME}`: `${env:BILLING_TOKEN}` in a template, `env:REGION == 'eu'` in a condition. A variable that is not set is `null` and renders empty. It is read on every evaluation. A template's sandbox refuses it, so a payload template cannot read the process environment. For a value that may come from configuration or the environment, `{{BILLING_TOKEN}}` reads `IConfiguration` first (see Configuration values above). ### `ref:name`, the object itself `ref:name` is the object registered under `name`, as Apache Camel's `${ref:name}`. Nothing is called on it. | Expression | Result | |---|---| | `ref:limits.max` | `100` | | `ref:limits.max - header.b` | `97` | | `${ref:limits.max}` | `100` | | Condition | Result | |---|---| | `header.a < ref:limits.max` | `True` | | Template | Result | |---|---| | `max ${ref:limits.max}` | `max 100` | - **The name** is the whole run of letters, digits, `_`, `.` and `-` after the colon: `ref:chat.settings` is the object registered as `chat.settings`. Put a space before a minus: `ref:limit-1` is the name `limit-1`, `ref:limit - 1` subtracts. - **Nothing is read from it** by `ref:` itself. A whole placeholder `${ref:name}` keeps the object (a header set from it holds the instance); with text around it, the template writes its `ToString()`. To read a property, call a method with `bean:name.Method(...)`, or pass the object to one: `bean:fmt.Describe(ref:chat.settings)`. `ref:name(...)` is an error pointing to `bean:`. - **Missing, sandbox, context, colon:** as for `bean:`. A name not in the registry is an error naming it; the object is looked up once per route context; a template's sandbox refuses it; `flag ? ref : other` needs its spaces. ### `Method()` in C# `Method(reference, spec)` is the typed form of the same call, Apache Camel's `method()`: ```csharp From("direct://orders") .Filter(Method("#loyalty", "IsGold(${header.customer})")) // a condition .SetBody(Method("#pricing", "Gross(${header.qty}, 2.5)")) // a value, its type kept .EndFilter() .Validate(Method("#rules", "IsAllowed(${header.customer})"), "not allowed"); ``` The spec is written as in the `bean:` URI (`Name` or `Name(arg, ...)`, each argument a template or an expression). The bean is a registry name; a type goes through `` or `AddToRegistry` first. In a condition (`Filter`, `When`, `Validate`) a method returning `Task` is awaited; in a value position the call is synchronous, as the function is. `Validate(IExpression)` reads any expression as a condition, as `Filter` does: `Validate(Expr("header.a > 0"))`. ### What `check` and `pack` verify Every expression of a route file compiles as the engine compiles it, a bare one and each `${...}`: one the engine refuses is an error at its attribute, in the engine's words. Text after a complete expression is such an error, in a placeholder, a value and a condition alike: `${exception.type|message}` gives `unexpected '|' at position 15 within the expression: the expression ends before it.` A bare expression that starts with a root of the exchange and then becomes text by the rule for bare text (`header.b 3`) is a warning: its value is the text itself, and in a condition it is always true. In an endpoint's own options, `${file:...}` is the file component's and is checked when the endpoint is created. For every `bean:` call and `ref:` name in a route file: that it parses (an error at the attribute otherwise); that the name is declared by a `` of the package (a warning otherwise, since module code may register it); and, with `--bin`, that a declared bean's type has the called method with that many arguments and that it is synchronous. A bare `bean:` call or `ref:` name in a text that also holds a `${...}` is warned: the text renders as a template. --- ## 12. Compared with Apache Camel's Simple | Camel Simple | redb.Route | |---|---| | `${header.x}`, `${exchangeProperty.x}`, `${body}` | `${header.x}`, `${property.x}`, `${body}` | | `${header.x} == 'a'` as a predicate | `header.x == 'a'`; `${...}` around an operand renders text first | | `${bean:name.method(${body})}`, `${bean:name?method=m}` | `${bean:name.method(${body})}` or `bean:name.method(body)`; the `?method=` form belongs to the `bean:` URI | | `method(ref, "name")` | `Method("#ref", "name(args)")` | | `${ref:x}` | `${ref:x}` or `ref:x`, the whole run is the name | | `${header.x} =~ 'abc'` | `header.x =~ 'abc'`, the same rule: two strings ignore case, any other pair is `==` | | `${header.n} range '100..199'`, `not range` | `header.n range '100..199'`, `not range`; the literal is checked at load | | `${env:X}` | `${env:X}` or `env:X`; `{{X}}` reads configuration first | | `${jsonpath:$.x}`, `${xpath:/x}` | the same, or `jpath('$.x')` / `xpath('/x')` | | `${file:name}`, `${file:name.noext}`, `${file:size}` | the same, over the `redbFile.*` headers | | `${date:now:yyyyMMdd}` | `dateformat(now(), 'yyyyMMdd')` | | escaping `\${` and `$${` | `\${`; `$${` is a dollar sign followed by a placeholder here | --- ## 13. Known limits | What | Today | |---|---| | `jpath($.x)` / `xpath(/x)` bare and unquoted | does not compile; quote the path or write it inside `${...}` | | `header.Content-Type` bare | an error pointing to `${header.Content-Type}` (a subtraction otherwise) | | `round(2.5)` | `2`, banker's rounding | Path: redb-route/LICENSE 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/LICENSE ---- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may accept and charge a fee in exchange for, or offer support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2024-2026 RedBase Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Path: redb-route/METRICS.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/METRICS.md ---- # Metrics: measuring routes, and reading the measurements back redb.Route measures itself on two layers. This guide covers what each layer holds, how to read it — from your application, and from inside a route — and how to log the numbers for a whole route or for one section of it. ## The two layers **Layer 1 — OpenTelemetry export.** One ActivitySource and one Meter, both named `redb.Route`. Traces cover the routes and the processors, and the transports that open spans: a send span per producer call, and an inbound span per message or request — a child of the caller's `traceparent`, or a root when none came — with the sender's baggage back on it and `redb.route.endpoint` on every one. Connectors do this through `RouteTelemetryExtensions` (`StartConsumerSpan`, `InjectTraceContext`, `RecordFailure`); a connector's README says what it traces. `RouteEngineOptions.EnableTelemetry = false` opens none of these spans, the transport spans included, but a context that came in is still passed on to the next hop. Metrics cover the engine and the EIPs: | Instrument | Kind | What it counts | |---|---|---| | `redb.route.exchanges.processed` / `.failed` | counter | exchanges through all routes | | `redb.route.exchange.duration` | histogram | end-to-end processing, ms | | `redb.route.exchanges.inflight` | up-down counter | currently processing | | `redb.route.step.processed` / `.failed` / `.duration` | counter / histogram | `.Metered()` sections | | `redb.route.throttle.delayed` | counter | exchanges delayed by rate limiting | | `redb.route.circuitbreaker.tripped` / `.rejected` | counter | breaker opens; exchanges refused | | `redb.route.filter.dropped`, `.debounce.*`, `.splitter.parts`, `.timeout.expired`, `.wiretap.*`, `.multicast.*`, `.retry.*` | counters | per-EIP events | Measurements are tagged with `redb.route.id`, and step metrics also with `redb.route.step`. A .NET `Meter` is push-only: this layer goes to a subscriber or nowhere. The standard subscriber is an OpenTelemetry backend: ```csharp services.AddOpenTelemetry() .WithMetrics(m => m.AddMeter("redb.Route")) .WithTracing(t => t.AddSource("redb.Route")); ``` **Layer 2 — endpoint statistics.** Every endpoint tracks its own counters, readable in-process through `IEndpointStatistics`: `MessagesIn`, `MessagesOut`, `Errors`, `Warnings`, `Rejected` (shed by an admission limit before the pipeline ran), `Cancelled` (abandoned by a cooperative cancellation — not the route's fault, and not an error), `Refused` (requests the transport refused as the caller's fault with the protocol's own error, before any exchange; `LastRefusalMessage`/`Time` say why; not an error, and not in health), `BytesIn`/`BytesOut`, `ThroughputPerSecond`, `AverageProcessingTime` (last 100 messages), `LastErrorMessage`/`Time`, `HealthStatus`/`HealthReason`. A consumer endpoint's completed count is `MessagesIn − Errors − Cancelled`. ### A business key on a span, not in baggage Two different jobs travel with a trace, and they must not be mixed. **Correlation across the network** is the W3C context and the baggage: they go to every next service, so baggage carries only what those services may see. **Finding a trace locally** — by an order number, a batch id — is an attribute on one of this service's spans: `.SpanTag(key, value)` (`SpanTarget.Enclosing`, the nearest `Traced` scope or the route span; `SpanTarget.Inbound`, the server or consumer span of the request). Jaeger and Tempo search attributes on every span of a trace. A business key put in baggage instead leaks to systems that have no business with it. The attribute exists only in layer 1: nobody listening, an unsampled span or `.Tracing(false)` means nothing is set. The same key for the route itself to read stays where it always was — a header or a property. ## Reading measurements from inside a route ### `stats()` in the expression language Endpoint statistics are values in the expression language, so a route can **branch** on its own measurements: ```csharp // Turn traffic away from a degraded target. .Filter("stats('direct:orders', 'health') != 'Critical'") // Alarm on a cancellation storm. .When("stats('current', 'cancelled') > 100") // Log your own counters, no lambda captures. .SetHeader("err", Expr("${stats('current', 'errors')}")) .SetHeader("avg", Expr("${stats('current', 'averageProcessingTimeMs')}")) .To("log:orders?showHeaders=true&showBody=false") ``` `stats(target, metric)`: the target is an endpoint URI or `'current'` (the route processing the exchange). Metric names, case-insensitive: `messagesIn`, `messagesOut`, `errors`, `warnings`, `rejected`, `cancelled`, `refused`, `bytesIn`, `bytesOut`, `throughputPerSecond`, `averageProcessingTimeMs`, `health`, `healthReason`, `lastError`, `lastRefusal`. A typo in a literal metric name fails the route **build** with the list of known names, not the first message. The same function reads the **OpenTelemetry layer** when the target starts with `otel:` — the EIP counters and `.Metered()` durations live only there, and this is the only way a route (or markup, which has no lambdas) can see them: ```csharp // The slowest run of one metered step of this route. .SetHeader("worst", Expr("${stats('otel:redb.route.step.duration/enrich', 'max')}")) // How often the throttle delayed another route. .When("stats('otel:redb.route.throttle.delayed@orders', 'sum') > 100") ``` `otel:instrument[@route][/step]`: without `@route` the instrument is read for the route processing the exchange, `/step` matches the `redb.route.step` tag. The field is `count`, `sum`, `min`, `max` or `last`, and a literal unknown field fails the build like an unknown metric. This branch needs the in-process subscriber (`context.UseMetricsSnapshot()`); without it the call fails and says so. An instrument nobody has measured yet reads as zero. ### `IExchange.Context` Any processor can reach the route context directly — Apache Camel's `exchange.getContext()`: ```csharp .Process(e => { var s = (IEndpointStatistics)e.Context!.GetEndpoint("direct:orders"); log.LogInformation("in={In} err={Err} cancelled={C} avg={Avg:F1}ms", s.MessagesIn, s.Errors, s.Cancelled, s.AverageProcessingTime.TotalMilliseconds); }) ``` The context is stamped when the exchange enters a route and restored when it leaves, so inside a `direct:` sub-route it is the inner route's context, and `null` on an exchange you built by hand. ### The control bus `controlbus:route?action=stats` puts a `` XML into the exchange body — one route by `routeId` (or `current`), or the whole context without one. It carries the full counter surface, XML-escaped. A timer-driven monitoring route is the classic shape: ```csharp r.From("timer:stats?period=60000") .To("controlbus:route?action=stats") .To("log:route-stats?level=Information"); ``` Mind one trap: from inside a wire-tap branch, `routeId=current` names the *branch* route, not the one you tapped — name the route explicitly there. ## The trail of one exchange: `messageHistory()` Message History records every node an exchange passed, with the time it took, and the failure dump prints it. The same trail is a value in the expression language, so a route can log it or branch on its cost: ```csharp .Log("${messageHistory()}") // the table, as the failure dump prints it .SetHeader("trail", Expr("${messageHistory('compact')}")) // log > choice > to(http) .When("messageHistory('slowestMs') > 500") // only the exchanges that cost something ``` Kinds: `table` (the default), `compact`, `json`, `count`, `totalMs`, `slowestMs`, `slowest`, `lastNode`. The numbers make it a predicate, which is what markup needs: ``. Message history is opt-in (`RouteEngineOptions.EnableMessageHistory`, or `.MessageHistory()` on one route), so an exchange that recorded nothing reads as an empty string and zero. That is the one measurement in this language that answers instead of failing: a diagnostic log must not break a route where history is simply off. An unknown kind is still an authoring error and fails the build. ## Measuring a section of a route Two ways, different trade-offs: **`.Metered("name") … EndMetered()`** wraps a section in step metrics — precise duration histograms tagged `redb.route.id` + `redb.route.step`, at the cost of living in layer 1 (readable in-route only through the snapshot below): ```csharp .Metered("enrich") .Xslt("enrich.xsl") .To("sql:INSERT ...?dataSource=main") .EndMetered() ``` **Extract the section into a `direct:` sub-route.** The section becomes an endpoint with its own full `IEndpointStatistics` — readable via `stats('direct:enrich', ...)`, the control bus, and `e.Context`, with no extra setup: ```csharp r.From("direct:enrich").RouteId("enrich").Xslt("enrich.xsl").To("sql:..."); // main route: .To("direct:enrich") ``` ## Reading the OpenTelemetry layer in-process: the metrics snapshot The EIP counters and `.Metered()` step durations exist only in layer 1. To read them without an external backend, opt in to the in-process subscriber: ```csharp context.UseMetricsSnapshot(); // or services.AddMetricsSnapshot() with DI // later, from a processor or from application code: var snap = context.GetMetricsSnapshot()!; // or e.Context.GetMetricsSnapshot() double? delayed = snap.Value("redb.route.throttle.delayed", routeId: "orders"); var work = snap.Point("redb.route.step.duration", routeId: "orders", step: "enrich"); // work: Count, Sum, Min, Max, Last — current values, nothing more ``` Design limits, on purpose: **opt-in** (a `MeterListener` gets a callback for every measurement — nobody pays for that without asking), **current values only** (no windows, no percentiles, no history — that is an OpenTelemetry backend's job), **exact tag matching** (a point either was recorded under `(instrument, routeId, step)` or there is nothing to return). The listener is disposed when the context stops; collected points stay readable. ## Choosing, in one table | You want | Use | |---|---| | Dashboards, alerting, history, percentiles | OpenTelemetry backend: `AddMeter("redb.Route")` | | Find a trace by a business key | `.SpanTag("sap.order.id", ...)` — a span attribute, never baggage | | Branch a route on an endpoint's health or counters | `stats(...)` in a condition | | Branch a route, or markup, on EIP counters and step durations | `stats('otel:…', field)` + `UseMetricsSnapshot()` | | See which steps one exchange went through, and what each cost | `messageHistory()` in a log or a condition | | Log a route's own numbers periodically | timer route → `controlbus:...?action=stats` → `log:` | | Full counter surface from a processor | `e.Context.GetEndpoint(...)` as `IEndpointStatistics` | | Numbers for one section of a route | `direct:` sub-route (statistics) or `.Metered()` (histograms) | | EIP counters / step durations without a backend | `context.UseMetricsSnapshot()` | Path: redb-route/NOTICE 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/NOTICE ---- redb — Entity Database for .NET Copyright 2024-2026 RedBase This product includes software developed by RedBase (https://redbase.app). Licensed under the Apache License, Version 2.0 (the "License"); you may not use the open-source components of this product except in compliance with the License. You may obtain a copy of the License in the LICENSE file in the root of this distribution or at: http://www.apache.org/licenses/LICENSE-2.0 ------------------------------------------------------------------------ Components and licenses ------------------------------------------------------------------------ * Open-source projects (Apache License 2.0): redb.Core, redb.Postgres, redb.MSSql, redb.Tsak.Core, redb.Tsak.Web, redb.Tsak.CLI, redb.Tsak.Worker, redb.Tsak.Client, redb.Tsak.Contracts, redb.Identity, redb.Route, redb.CLI, redb.PropsEditor, redb.Templates, redb.Examples, and other non-".Pro" projects. * Commercial / Pro projects (REDBASE Commercial License — see LICENSE-PRO.txt): redb.Core.Pro, redb.Postgres.Pro, redb.MSSql.Pro, redb.Tsak.Core.Pro, redb.Tsak.Web.Pro, redb.Licensing (the licensing library is distributed alongside Pro components). * Third-party components: see project files (.csproj) for transitive package references and their respective licenses. Path: redb-route/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/README.md ---- # redb.Route **Enterprise integration framework for .NET. Wire any system to any system in a few lines of C#.** > **LLMs / coding agents:** canonical training contract for the whole redb ecosystem → redb.Route is the .NET equivalent of [Apache Camel](https://camel.apache.org/) — a fluent C# DSL that connects Kafka, RabbitMQ, Redis, SQL, HTTP, gRPC, SFTP, MQTT, S3, and more through `From → Process → To` pipelines. C# DSL or XML routes, no message-bus lock-in, no per-endpoint license fees. [![NuGet](https://img.shields.io/nuget/v/redb.Route?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route) [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE) [![.NET](https://img.shields.io/badge/.NET-10%20%7C%2011-purple)](https://dotnet.microsoft.com) [![Website](https://img.shields.io/badge/docs-redbase.app-orange)](https://redbase.app) Certificate of the eDelivery AS4 conformance tests passed by redb.Route.As4 4.6.1 **eDelivery AS4 conformance.** [redb.Route.As4](https://github.com/redbase-app/redb-route/tree/main/redb.Route.As4) 4.6.1 is listed by the European Commission among [eDelivery AS4 v1.x conformant products](https://ec.europa.eu/digital-building-blocks/sites/spaces/DIGITAL/pages/721846393/eDelivery+AS4+v1.x+conformant+products): it passed the eDelivery conformance tests of the eDelivery AS4 Profile 1.16, Common Profile, 76 of 76 required tests, on 2026-11-04 ([certificate, PDF](https://redbase.app/files/as4/redb-route-as4-4.6.1-ec-conformance-certificate.pdf)). The certificate is for version 4.6.1; later versions have not gone through the conformance service again. It attests the eDelivery Common Profile, not Peppol. > **Production runtime:** routes are packaged as `.tpkg` modules and deployed to **[redb.Tsak](https://github.com/redbase-app/redb-tsak)** — the runtime container with hot-reload, clustering, REST management API, CLI and Blazor dashboard. redb.Route handles the _what_ (pipeline logic); redb.Tsak handles the _where_, _when_ and _how many_ (deployment lifecycle). See [Running Routes in Production](#running-routes-in-production--redbtsak). ```csharp From("kafka://orders?groupId=svc&brokers=localhost:9092") .Filter(Header("type").isEqualTo("new")) .To("rabbitmq://events?host=localhost"); ``` --- ## Highlights - **30 external transports + 11 built-in components** (Direct, Direct-VM, VM, SEDA, Timer, Mock, Log, Bean, ControlBus, Validator, XSLT). With the further components the packages carry (HTTPS, WSS, IMAP / POP3 / SMTP, SNS, cron, LLM embeddings, knowledge and speech-to-text, Firebase messaging and storage, Cache) that is 53 components, 57 URI schemes with the TLS and alias names (`as2s`, `as4s`, `soaps`, `es`). One of the transports — `llm:` — is a first-class LLM connector with a universal OpenAI-compatible provider (14 APIs) and a native Anthropic Messages API provider, plus `.AsLlmTool()` to expose any of the other transports as an LLM-callable tool with zero connector changes. Token-by-token streaming runs end-to-end: `?stream=true` on an `llm://` step lands on the wire as Server-Sent Events through `redb.Route.Http` (with an `event: done` summary trailer) or as one `Text` frame per token through `redb.Route.WebSocket`. - **MCP client connector — `mcp:` URI.** `redb.Route.Llm.Mcp` spawns external **Model Context Protocol** servers (stdio or HTTP+SSE), runs `initialize` + `tools/list` on startup and registers every remote tool into `IToolDescriptorRegistry` as a first-class `ILlmToolDescriptor`. The agent picks them up like any native tool — full audit (`ToolSetHash`), governance (`Safety`), observability and approval flow inherited automatically. Cancellation is threaded all the way through: an aborted agent iteration emits a JSON-RPC `notifications/cancelled` and the in-flight `tools/call` unwinds. One package = the entire community MCP ecosystem (Serena, filesystem, git, fetch, github, sqlite, …) becomes callable from a redb agent. - **30+ EIP patterns** — Splitter, Aggregator, CBR, WireTap, Saga, Circuit Breaker, Idempotent Consumer, Claim Check, Throttle, Resequencer, Scatter-Gather, and more. - **Compiled expression engine** — `${header.x}`, `${header.x++}`, arithmetic, JSONPath, XPath compile to `Func` via `System.Linq.Expressions`. No interpreter overhead. - **Type-safe fluent builders** — `Kafka.Topic("orders").GroupId("svc").Acks("All")` instead of URI strings. - **OpenTelemetry built-in** — Activities and Meters per route and per step, no extra config. - **Transactional routes** — `.Transacted()` wraps pipeline steps in `TransactionScope`; SQL transport binds ADO.NET transactions per statement. - **Production runtime** — [redb.Tsak](#running-routes-in-production--redbtsak) hosts route assemblies with hot-reload, clustering, REST API and Web UI. - **Apache 2.0 licensed** — no commercial restrictions, no per-endpoint pricing. --- ## Table of Contents - [Quick Start](#quick-start) - [Why redb.Route](#why-redbroute) — [Differentiators](#what-sets-redbroute-apart) · [vs other .NET options](#vs-other-net-options-quick-guide) · [Manual code comparison](#manual-code-comparison) - [Use Cases](#use-cases) - [Configuration](#configuration) — appsettings, IOptions, DI parameterization, [credentials & secret redaction](#credentials--secret-redaction) - [How It Compares](#how-it-compares) — vs Apache Camel, MassTransit, NServiceBus, Wolverine; [Migrating from Camel](#migrating-from-apache-camel) - [Routing Patterns](#routing-patterns) — From, To, Filter, Choice, Split, Recipient List, Dynamic Router - [Error Handling](#error-handling) — [Retry](#retry-per-step) · [Dead Letter Channel](#dead-letter-channel) · [TryCatch](#trycatch-scoped) · [OnException scope](#onexception--scope-form-chain) · [Route configuration](#route-configuration--handlers-apart-from-the-routes) · [OnException configure](#onexception--configure-form-action) · [Redelivery options](#redelivery-configuration) · [Combined example](#combined-example) - [Message Transformation](#message-transformation) — SetBody, SetHeader, Marshal, Unmarshal, header filter strategy - [Expression Language](#expression-language) — helpers, predicates, a short reference; the full guide is [EXPRESSIONS.md](EXPRESSIONS.md) - [Other EIP Patterns](#other-eip-patterns) — WireTap, Multicast, Throttle, Circuit Breaker, Saga, Idempotent Consumer, Loop, Delay, Resequencer, Enrich - [Bean References](#bean-references) — `bean:` URI, `.Bean(ref, method)`, `` - [Request-Response (InOut)](#request-response-inout) - [Concurrency & Parallelism](#concurrency--parallelism) — `.Threads(N)` EIP, consumer-level knobs, [full guide](CONCURRENCY.md) - [Transactions](TRANSACTIONS.md) — `.Transacted()`, commit order (database, sends, acknowledgement), `Retry`, idempotent consumer - [Behaviour Guarantees](#behaviour-guarantees) — stop and `DoFinally`, a stop across `direct-vm:` and `Enrich`, Out→In merge, Split properties, `now()` and `delay` - [Reliability](#reliability) — RabbitMQ confirms, lost connections and the Control Bus, Kafka EOS, persistent IdempotentConsumer, Outbox via Sql polling - [Validation](#validation) - [Testing with Mock](#testing-with-mock) - [Telemetry](#telemetry) - [Logging](#logging) - [Fluent Transport Builders](#fluent-transport-builders) - [Architecture](#architecture) - [DSL Reference](#dsl-reference) - [XML Route Tools](#xml-route-tools) — `redb-route-xml` .NET tool, VS Code extension - [URI Scheme Reference](#uri-scheme-reference) - [Transport Capability Matrix](#transport-capability-matrix) - [Packages](#packages) - [Running Routes in Production — redb.Tsak](#running-routes-in-production--redbtsak) - [Upgrading](#upgrading) — [UPGRADING.md](UPGRADING.md), [CHANGELOG.md](CHANGELOG.md) - [Contributing](#contributing) - [License](#license) --- ## Quick Start Every redb.Route pipeline follows the same shape: a single source (`From`), zero or more processors in the middle, and one or more sinks (`To`). Messages flow as `IExchange` instances carrying `Body`, `Headers`, and `Properties`. ```mermaid flowchart LR From([From\nkafka://orders]) --> Filter[Filter] Filter --> Transform[SetBody / Transform] Transform --> Choice{Choice} Choice -- high --> ToA([To\ndirect://fast-lane]) Choice -- low --> ToB([To\nseda://batch]) Choice -- else --> ToC([To\ndirect://standard]) ``` Install the engine and the transports a route uses (one package per transport, listed in [Packages](#packages)): ```bash dotnet add package redb.Route dotnet add package redb.Route.Kafka dotnet add package redb.Route.RabbitMQ ``` ```csharp // Program.cs — minimal integration pipeline var builder = Host.CreateApplicationBuilder(args); builder.Services.AddRedbRoute(route => { route.AddRoutes(r => { // Kafka → filter → RabbitMQ in 3 lines r.From("kafka://orders?groupId=svc&brokers=localhost:9092") .Filter(e => e.In.GetHeader("type") == "new") .To("rabbitmq://events?host=localhost"); }); }); builder.Services.AddRedbRouteKafka(); builder.Services.AddRedbRouteRabbitMQ(); var app = builder.Build(); app.Run(); ``` For complex routing logic, group routes into a `RouteBuilder` class: ```csharp public class OrderRoutes : RouteBuilder { protected override void Configure() { From("kafka://orders?groupId=svc&brokers=localhost:9092") .RouteId("order-pipeline") .Choice() .When(Header("priority").isEqualTo("high")) .Log("High priority order") .To("direct://fast-lane") .When(Header("priority").isEqualTo("low")) .To("seda://batch-queue") .Otherwise() .To("direct://standard") .EndChoice(); From("direct://fast-lane") .SetHeader("processed-at", e => DateTimeOffset.UtcNow) .Process(async (exchange, ct) => { var body = (string)exchange.In.Body!; exchange.In.Body = $"PROCESSED: {body}"; }) .To("rabbitmq://processed?host=localhost"); } } builder.Services.AddRedbRoute(route => route.AddRouteBuilder()); ``` Or every route builder of an assembly — each public, non-abstract `RouteBuilder` (Apache Camel's routes discovery). A filter states conditions and leaves builders out; a builder that cannot be created, or one already registered, is an error naming the type, never skipped: ```csharp builder.Services.AddRedbRoute(route => route .AddRouteBuilders([typeof(OrderRoutes).Assembly], type => type.Namespace!.StartsWith("Orders.Routes"))); // Without a host: builders with a public parameterless constructor context.AddRoutes(typeof(OrderRoutes).Assembly); ``` --- ## Why redb.Route ### What sets redb.Route apart Four things you do not get together in any other .NET integration framework: - **30 transports out of the box, including a full LLM connector.** Kafka, RabbitMQ, Redis, SQL, HTTP, gRPC, SOAP, AS2, AS4, SFTP, MQTT, S3, Amazon SQS + SNS, IBM MQ, AMQP 1.0, Azure Service Bus, Elasticsearch, Firebase, LDAP, Mail, TCP, WebSocket, SignalR, Telegram, FTP, Quartz, File, **Exec** (local-process execution), **`llm:`** (OpenAI-compatible universal provider for 14 vendors + native Anthropic Messages API), and **`mcp:`** (Model Context Protocol client — the whole community MCP ecosystem as callable tools) — **plus `.AsLlmTool()` that turns any of the other 29 transports into an LLM tool with zero connector changes**. MassTransit ships 5, Wolverine 4, NServiceBus 7. The competitors expect you to use only message brokers; redb.Route treats files, mailboxes, FTP servers, SQL polling, local processes and LLM endpoints as first-class transports — and any of them can become an LLM-callable tool. - **Compiled expression engine.** `${header.x}`, `${header.x++}`, arithmetic, JSONPath, XPath are translated to `Func` via `System.Linq.Expressions` at route-build time. No interpreter, no per-message parsing, the compiled delegates are cached. Apache Camel's Simple language is parsed once into an expression tree and evaluated at run time; MassTransit / Wolverine / NServiceBus have no expression engine at all. - **30+ EIP patterns as first-class DSL.** Filter, Choice, Splitter, Aggregator, Multicast, WireTap, Recipient List, Dynamic Router, Resequencer, Scatter-Gather, Claim Check, Idempotent Consumer, Saga, Circuit Breaker, Throttle, Retry, Dead Letter, Loop, Delay, Debounce, Enrich, Timeout, TryCatch, Transacted, Control Bus, Process, Validate. The .NET competitors give you Saga + Request/Response + Outbox; everything else you write yourself. - **Apache 2.0 licensed, no per-endpoint pricing.** NServiceBus is commercial after 2 endpoints. redb.Route is unrestricted for any use, any scale. Plus: type-safe fluent builders (`Kafka.Topic(...).GroupId(...)` instead of URI strings), built-in OpenTelemetry per route and per step, transactional pipelines via `.Transacted()`, and a production runtime ([redb.Tsak](#running-routes-in-production--redbtsak)) with hot-reload and clustering. ### vs other .NET options — quick guide | If you need | Pick | |-------------|------| | Routing across many transports (Kafka + SQL + SFTP + HTTP in one pipeline) | **redb.Route** | | EIP patterns (Splitter, Aggregator, Content-Based Router, WireTap) | **redb.Route** | | Protocol bridging (Kafka ↔ RabbitMQ, MQTT ↔ HTTP, FTP ↔ SQL) | **redb.Route** | | Choreography saga with compensations (pipeline-level, no external state) | **redb.Route** (`.Saga(s => s.Step(...).Compensate(...))`) | | Outbox via SQL polling (`SELECT … WHERE processed=0` → process → `UPDATE`) | **redb.Route** (`Sql.Poll(...)` + `.Transacted()`) | | In-process dispatch to handler classes (`RedbController` behind `direct:`) | **redb.Route** + `redb.Route.Controllers` | | Async in-process pub/sub with `RouteBuilder` consumer classes | **redb.Route** (`seda:` + `RouteBuilder`) | | Durable orchestrated saga state machine persisted across process restarts | MassTransit / NServiceBus / Wolverine | | Transactional pipeline (database first, broker sends after the commit, ack last) | **redb.Route** (`.Transacted()`: RabbitMQ, AMQP 1.0, Kafka, IBM MQ, Azure Service Bus, SQS/SNS, Redis PUBLISH/XADD) | | Managed transactional outbox container (auto table + background retry daemon) | MassTransit / NServiceBus / Wolverine | > redb.Route and MassTransit/NServiceBus solve different problems. redb.Route is a **pipeline and transport integration engine** (Apache Camel for .NET). MassTransit/NServiceBus are **message-bus frameworks** centered on consumer registration and managed saga state. You can use both together — redb.Route for cross-protocol routing and transformation, MassTransit for durable long-running workflows. Full side-by-side tables: [How It Compares](#how-it-compares). ### Manual code comparison | Problem | Manual code | redb.Route | |---------|-------------|------------| | Connect Kafka → RabbitMQ | 80+ lines: consumer, producer, serialization, error handling | `From("kafka://orders").To("rabbitmq://events")` | | Content-based routing | Nested `if/switch`, custom dispatch tables | `.Choice().When(...).To(...).Otherwise().To(...)` | | Retry + Dead Letter | Hand-rolled retry loops, DLQ logic | `OnException().MaximumRedeliveries(3)` + `DeadLetterChannel("seda://failed")` | | File polling → DB | `FileSystemWatcher` + ADO.NET + threading | `From("file:///data?include=*.csv").To("sql://...")` | | Observability | Custom metrics, `Activity` spans, logging | Built-in OpenTelemetry — traces and metrics per route/step | | Protocol bridging | Custom adapter per protocol pair | Any-to-any via URI schemes: `kafka:`, `http:`, `grpc:`, `mqtt:` | --- ## Use Cases redb.Route fits any workload where messages move between systems and need transformation, routing, or buffering on the way: - **Message broker bridging.** Kafka topic → filter → enrich → RabbitMQ exchange. MQTT sensor stream → batch → SQL inserts. - **File ingestion pipelines.** SFTP folder polling → unmarshal CSV → validate → SQL upsert → archive to S3. - **API gateways and webhooks.** HTTP endpoint (`Http.Listen`) → validate → fan-out to internal queues → respond. Stripe/GitHub webhooks → SignalR broadcast. - **Scheduled jobs.** Quartz Cron → SQL extract → email report. Timer → poll external API → push to Kafka. - **Protocol translation.** SOAP → JSON, XML → CSV, gRPC → REST, MQTT → AMQP. Any-to-any via marshal/unmarshal + URI swap. - **Saga orchestration without a state-machine framework.** Reserve inventory → charge payment → ship — with compensating steps on failure. - **Event-driven microservices.** Per-service `RouteBuilder` classes register routes; `IHostedService` boots them; OpenTelemetry traces span the whole chain. - **Legacy integration.** IBM MQ, FTP, LDAP, POP3/IMAP, raw TCP — first-class support, not afterthoughts. - **Real-time dashboards.** Kafka stream → throttle → SignalR Hub → Blazor/JS clients. If the question is *"how do I move messages from A to B with rules in the middle?"*, redb.Route answers it in a few lines of C#. --- ## Configuration Endpoints, transports, and options work with the standard .NET configuration stack — `appsettings.json`, `IOptions`, environment variables, secrets — without a custom config layer. ### Endpoint URIs from configuration Resolve broker URLs, topic names, and credentials at startup, then build endpoint URIs in code: ```jsonc // appsettings.json { "Kafka": { "Brokers": "broker1:9092,broker2:9092", "GroupId": "order-svc", "Topic": "orders" }, "RabbitMQ": { "Host": "rabbit.local", "Exchange": "events" } } ``` ```csharp builder.Services.AddRedbRoute(route => { route.AddRoutes(r => { var cfg = builder.Configuration; var kafka = Kafka.Topic(cfg["Kafka:Topic"]!) .Brokers(cfg["Kafka:Brokers"]!) .GroupId(cfg["Kafka:GroupId"]!); var rabbit = Rabbit.Queue("events") .Host(cfg["RabbitMQ:Host"]!) .Exchange(cfg["RabbitMQ:Exchange"]!, "topic"); r.From(kafka).To(rabbit); }); }); ``` ### Bind options into a RouteBuilder Typed `IOptions` flows through DI like any service. Inject into `RouteBuilder` constructors and use the values inside `Configure()`: ```csharp public class KafkaOptions { public string Brokers { get; set; } = ""; public string GroupId { get; set; } = ""; public string Topic { get; set; } = ""; } public class OrderRoutes : RouteBuilder { private readonly KafkaOptions _kafka; public OrderRoutes(IOptions kafka) => _kafka = kafka.Value; protected override void Configure() { From(Kafka.Topic(_kafka.Topic).Brokers(_kafka.Brokers).GroupId(_kafka.GroupId)) .RouteId("order-pipeline") .To("seda://orders-internal"); } } // Program.cs builder.Services.Configure(builder.Configuration.GetSection("Kafka")); builder.Services.AddRedbRoute(route => route.AddRouteBuilder()); ``` ### Named SQL data sources The SQL transport uses **named** data sources registered in DI, so connection strings stay in configuration and out of route code: ```csharp builder.Services.AddRedbRouteSql(sql => { sql.AddDataSource("main", builder.Configuration.GetConnectionString("Main")!, "SqlServer"); sql.AddDataSource("audit", builder.Configuration.GetConnectionString("Audit")!, "PostgreSql"); }); // Routes reference the data source by name — credentials never appear in the URI From(Sql.Poll("SELECT * FROM Orders WHERE Status = 'New'") .DataSource("main") .Delay(5000)) .To(Sql.Execute("INSERT INTO AuditLog (Body) VALUES (@body)") .DataSource("audit") .Transacted()); ``` ### Credentials & secret redaction Two independent mechanisms keep passwords out of logs, OpenTelemetry tags, metric labels, health checks and the Tsak dashboard. **1. Keep the secret out of the URI — named `ConnectionFactory`.** Every connector that takes credentials accepts `connectionFactory=`, resolved from the route registry. The route then carries no secret at all, so there is nothing to mask on the happy path: ```csharp context.AddToRegistry("corp-ldap", new LdapConnectionFactory { Server = "ldap.corp.local", Port = 636, Ssl = true, BindDn = "cn=svc-reader,dc=corp,dc=local", BindPassword = Environment.GetEnvironmentVariable("LDAP_BIND_PASSWORD") }); From("ldap://SEARCH:dc=corp,dc=local?connectionFactory=corp-ldap&filter=(objectClass=user)") ``` A value written inline in the URI always wins over the factory, so existing routes keep working; a factory name that is not registered logs a warning and falls back to the URI parameters. For connectors whose address lives in the endpoint path (Http, Mail, SignalR, gRPC, Tcp, WebSocket) the factory deliberately carries no host/port — it can never silently redirect a route. **2. Redact whatever still ends up in a URI — `[Sensitive]`.** Guessing a secret from its parameter name fails open, so the option itself declares it: ```csharp public sealed class LdapEndpointOptions : EndpointOptions { public string Server { get; set; } = "localhost"; // printed in logs [Sensitive] public string? BindPassword { get; set; } // always rendered as **** } ``` `BindFromUri` harvests those declarations by reflection (once per options type), so the set of redacted parameter names is derived from the code and never hand-maintained — the same design as Apache Camel's `@UriParam(secret = true)`, which its build plugin turns into `SensitiveUtils.SENSITIVE_KEYS`. A name-keyword heuristic (`*password*`, `*token*`, `*secret*`, …) stays on as a backstop, `userinfo` passwords in `scheme://user:pass@host` are masked too, and secrets are replaced with a constant `****` — never a partial prefix. To register a credential parameter that is not an annotated option, call `EndpointUri.AddSensitiveKeys("myCustomToken")` at startup. A `[Sensitive]` member of an option group (`[OptionGroup]`, options written `group.member=value` as Camel's prefixed options, such as mail's `searchTerm.subject`) is masked as `group.member`. The same values are masked inside the error, warning and refusal texts an endpoint records: every `[Sensitive]` option and every secret URI parameter of the endpoint is replaced wherever it appears, plain or URL-escaped. This masking covers those endpoint texts only; the log step (see [Logging](#logging)) writes exactly what the route author asks for. **3. The id of an unnamed route carries neither.** A route that declares no `RouteId("...")` is named after its endpoint: the scheme, the path and a deterministic UUID of the whole URI (`kafka://orders?brokers=...` becomes `kafka-orders-1b4e28ba-2fa1-11d2-883f-0016d3cca427`). The query string stays out of the name and `user:pw@host` credentials are dropped from it, so the id is safe to print; the UUID is RFC 4122 version 5 in the URL namespace over the normalized endpoint URI, so it is the same on every start and every node — metric series, stored checkpoints and `controlbus:route` commands survive a restart — and any UUID library recomputes it from the URI. The name holds only `A-Z a-z 0-9 _ -`: a `/` or a `:` breaks dashboard labels and metric tags. ### XML from somebody else Every document that arrives from outside — a SOAP envelope, a message body an `xpath()` reads, the XML model of a template, a markup file inside a package — is read through `SafeXml`, which refuses a document type declaration. A DTD can nest internal entities so that a small message expands into a huge one in memory: on .NET 10, 452 bytes become 300 000 characters, and that is the polite version. The direct loaders all do it — `XmlDocument.Load`, `XDocument.Load`, `XDocument.Parse` — and `XmlResolver = null` changes nothing, because the expansion runs on *internal* entities. Only a reader from `XmlReader.Create` refuses a DTD, which it does by default. Reading somebody else's XML in your own processor deserves the same treatment: ```csharp var doc = SafeXml.Parse(text); // or Load(bytes) / LoadFile(path) var dom = SafeXml.LoadDocument(bytes); // XmlDocument, whitespace preserved for signatures var capped = SafeXml.Parse(text, maxCharacters: 1_000_000); ``` ### Engine options ```csharp builder.Services.Configure(o => { o.EnableTelemetry = true; // OpenTelemetry Activities o.EnableMetrics = true; // OpenTelemetry Meters o.ShutdownTimeout = TimeSpan.FromSeconds(30); // drain window on stop o.DefaultProcessingTimeout = TimeSpan.FromMinutes(5); o.ConsumerStartRetry.MaxAttempts = 0; // start retry of a failed consumer, see below }); ``` #### A consumer that fails to start A consumer whose `Start` throws while the context starts (a broker, database or server not up yet, a listener port still taken) does not stop the context: its route is marked `Errored` and the other routes start. The context then starts that consumer again in the background, first after `Delay`, the pause growing by `Multiplier` up to `MaxDelay`, until it starts or `MaxAttempts` runs out (`0` = until the context stops). While it waits the route stays `Errored`, so `RouteHealthCheck` reports it unhealthy; once the consumer starts the route is `Started` and the lifecycle listeners get `OnRouteStarted`. Each failed retry logs a Warning with the next pause, and the start-up log names the `Errored` routes instead of reporting every endpoint operational. | `ConsumerStartRetry` | Default | |---|---| | `Enabled` | `true` | | `Delay` | 2 s | | `Multiplier` | 2 | | `MaxDelay` | 1 min | | `MaxAttempts` | `0` (no limit) | | `UnhealthyOnRestarting` | `true`: an `Errored` route waiting for a retry is Unhealthy; `false` reports it Degraded | | `UnhealthyOnExhausted` | `true`: an `Errored` route no retry waits for (retries ran out, retry off, a policy refused) is Unhealthy; `false` reports it Degraded | Routes with `AutoStart(false)` and routes a route policy starts (a clustered route waits for its lock) are left to whoever starts them, and a route started, stopped or resumed by hand leaves the retry. Only the start is supervised: a consumer that loses its connection later reconnects through its transport. This is the back-off of Apache Camel's supervising route controller (`camel.routecontroller.*`), with two differences. It is on by default: without the supervisor Camel fails the whole context start, so a missing broker is loud, whereas redb.Route starts the other routes, and an `Errored` route nobody restarts would go unnoticed. And the pause grows (Camel's `backOffMultiplier` defaults to 1, with no maximum delay), so a long outage writes a Warning a minute rather than every two seconds. Camel's `initialDelay`, `backOffMaxElapsedTime` and include / exclude route patterns have no counterpart; `AutoStart(false)` keeps a route out. `UnhealthyOnRestarting` and `UnhealthyOnExhausted` are Camel's switches of the same names, with Camel's defaults since 4.7 (`true`, DOWN). A host where one broker that is down must not take the node out of its load balancer sets both to `false`: the route is then Degraded, which a readiness probe passes unless it fails on Degraded. #### What `RouteHealthCheck` reports `services.AddHealthChecks().AddRedbRouteCheck()` registers a check over the context's routes and the endpoints they send to: | Result | When | |---|---| | Unhealthy | a route is `Errored` (unless `UnhealthyOnRestarting` / `UnhealthyOnExhausted` is `false` for its phase), or a route's source endpoint is `Critical` or `Failed` | | Degraded | a route is stopped or suspended, an `Errored` route those switches set to Degraded, a source endpoint has a `Warning`, or an endpoint the routes send to is `Critical` or `Failed` | | Healthy | otherwise | An endpoint the routes send to counts when it knows it cannot send: a RabbitMQ endpoint is `Critical` while the broker blocks its publishing connection (a memory or disk alarm), with the broker's reason, and returns to its computed status by itself when the broker unblocks; any endpoint is `Critical` at a high recent error rate. Such endpoints are listed under `endpoints` in the result's data, by URI with secrets masked, at most ten, the rest counted in `endpointsNotListed`. They make the result Degraded and never Unhealthy, so a broker alarm does not read as a dead process; a readiness probe that fails on Degraded (Tsak's `Tsak:Health:DegradedNotReady=true`) takes the node out of readiness while it lasts. --- ## How It Compares ### Summary | | Apache Camel | MassTransit | NServiceBus | Wolverine | **redb.Route** | |--|--|--|--|--|--| | Platform | JVM | .NET | .NET | .NET | **.NET 10/11** | | License | Apache 2.0 | Apache 2.0 | **Commercial** | MIT | **Apache 2.0** | | Focus | EIP routing | Pub/sub + message bus | Message bus | Mediator + message bus | **Enterprise Service Bus (.NET)** | | Transports | 300+ | 5 | 7 | 4 | **30 + 11 built-in** | | EIP patterns | 80+ | Saga, R/R, Outbox | Saga, R/R | Saga, R/R, Outbox | **30+** | | Expression engine | Simple (expression tree, evaluated at run time) | None | None | None | **Compiled to delegates (System.Linq.Expressions) at route build** | | Configuration | XML or Java DSL | C# fluent | C# fluent | C# fluent | **C# fluent DSL or XML** | | Saga persistence | Yes | **Yes (DB-backed)** | **Yes (DB-backed)** | **Yes (Marten)** | Compensating steps + persistent `IdempotentConsumer` (redb RTTI storage / SQL) for dedup; no built-in state machine | | Outbox | Plugin | **Yes** | **Yes** | **Yes** | Polling outbox via `Sql.Poll(...).OnSuccess(...).Transacted()` + persistent `IdempotentConsumer` | | Publisher confirms / EOS | Yes | Yes | Yes | Yes | **Yes** — RabbitMQ publisher confirms (`MaxOutstandingConfirms`), Kafka transactional producer + `Acks=All` | ### vs Apache Camel If you know Camel, you know redb.Route — same EIP patterns, same `from → process → to` model, same URI endpoint scheme. | Concept | Apache Camel (Java) | redb.Route (.NET) | |---------|--------------------|-----------------| | Route definition | `from().process().to()` | `From().Process().To()` | | Route class | `RouteBuilder.configure()` | `RouteBuilder.Configure()` | | In-process sync | `direct:` | `direct:` | | In-memory async queue | `seda:` | `seda:` | | Periodic trigger | `timer:` | `timer:` | | Message object | `Exchange` + `Message` | `IExchange` + `IMessage` | | Expression language | Simple (expression tree, evaluated at run time) | StringExpression (compiled to delegates with System.Linq.Expressions at route build) | | EIP patterns | 80+ | 30+ (Filter, Choice, Splitter, Aggregator, Multicast, WireTap, Recipient List, Dynamic Router, Resequencer, Scatter-Gather, Claim Check, Idempotent Consumer, Saga, Circuit Breaker, Throttle, Retry, Dead Letter, Loop, Delay, Debounce, Enrich, Timeout, TryCatch, Transacted, …) | | Components | 300+ | 53: 30 transports + 11 built-in + the rest of the package components (Cache, Cron, LLM embeddings, knowledge, speech-to-text, …) | | Configuration | XML DSL or Java DSL | C# fluent DSL or XML | | Runtime / orchestration | Camel K / JBoss Fuse | [redb.Tsak](#running-routes-in-production--redbtsak) | | Platform | JVM | .NET 10 / 11 | The packages target .NET 10 and .NET 11. The 4.7 line stays on .NET 8, 9 and 10 for applications that cannot move yet (Microsoft's support for .NET 8 and .NET 9 ended on 10 November 2026). What redb.Route does differently from Camel: - **No XML.** C# fluent DSL with full IntelliSense. - **Type-safe builders.** `Kafka.Topic("orders").GroupId("svc")` instead of URI strings. - **Native .NET stack.** `IHostedService`, `IServiceCollection`, `ILogger`, `CancellationToken` everywhere. - **OpenTelemetry built in.** Traces and metrics per route and per step. - **Compiled expressions.** `${header.x++}`, arithmetic, JSONPath, XPath compile to `Func` — not interpreted. - **Transactional routes.** `.Transacted()` via `TransactionScope`. - **.NET-specific transports.** SignalR, ASP.NET Kestrel server-side consumers. #### Exchange ids across a hop An exchange that goes on as an exchange of its own gets a new `ExchangeId`, by Camel's table (`ExchangeHelper.createCorrelatedCopy`): | Step | The copy's `ExchangeId` | Its `CamelCorrelationId` property | |---|---|---| | `seda:`, `vm:`, `Multicast`, `RecipientList`, `ScatterGather`, `Split`, `Enrich`, `OnCompletion` | new | the id of the exchange it was copied from | | `WireTap`, `PollEnrich` | new | none | | `direct:`, `direct-vm:`, `Threads`, `Loop` (with `copy`) | the same | unchanged | After two hops the correlation id is the immediate parent's, as in Camel, and the original keeps its own id and its own correlation id when a fan-out merges back. Each copy is an in-flight exchange of its own, in the route it runs in. `IExchange.Clone()` stays the copy that keeps the id; `CorrelatedCopy()` makes the correlated one. Differences from Camel that remain: a `seda:` producer does not hand the exchange's on-completions over to the copy (the original completes when the copy is queued) and does not wait for a reply (`waitForTaskToComplete`); and the copy carries no trace context over the queue, so the consumer's span starts a trace of its own, joined to the sender's by the `redb.correlation.id` tag. #### Migrating from Apache Camel Camel routes translate to redb.Route almost line for line. Method names use PascalCase, predicates are typed, but the structure is identical. | Apache Camel (Java) | redb.Route (C#) | |---------------------|-----------------| | `from("kafka:orders?brokers=...")` | `From("kafka://orders?brokers=...")` | | `.routeId("order-pipeline")` | `.RouteId("order-pipeline")` | | `.choice()` | `.Choice()` | | `.when(header("type").isEqualTo("new"))` | `.When(Header("type").isEqualTo("new"))` | | `.otherwise()` | `.Otherwise()` | | `.end()` | `.EndChoice()` | | `.split(body())` | `.Split(Body())` | | `.aggregate(header("orderId"), strategy)` | `.Aggregate(Header("orderId"), strategy)` | | `.wireTap("seda:audit")` | `.WireTap("seda://audit")` | | `.recipientList(header("dest"))` | `.RecipientList(e => ParseDest(e))` | | `.errorHandler(deadLetterChannel("seda:dlq"))` | `.DeadLetterChannel("seda://dlq")` | | `.onException(IOException.class).maximumRedeliveries(3)` | `OnException().MaximumRedeliveries(3)` | | `.transacted()` | `.Transacted()` | | `.setBody(simple("${header.x}"))` | `.SetBody(Expr("${header.x}"))` | | `.log("got ${body}")` | `.Log("got ${body}")` | | `.to("rabbitmq://events")` | `.To("rabbitmq://events")` | A 200-line Camel `RouteBuilder.configure()` typically becomes a 200-line C# `RouteBuilder.Configure()` with the same shape — only the host (Spring Boot vs `IHost`) and the build system change. ### vs MassTransit | Aspect | MassTransit | redb.Route | |--------|-------------|------------| | Focus | Reliable message bus + Saga | Enterprise Service Bus — 30 transports, 30+ EIP (Enterprise Integration Patterns), transactional pipelines | | Routing model | Consumer classes | Route pipelines (`From → Process → To`) | | EIP patterns | Saga, Request/Response, Outbox | 30+ EIP patterns | | Transports | 5 (RabbitMQ, Kafka, SQS, Azure SB, gRPC) | 30 (+ File, SFTP, SQL, MQTT, TCP, HTTP, FTP, LDAP, IBM MQ, S3, SOAP, AS2, AS4, `llm:`, `mcp:`, …) | | Saga | State machine + **persistent state** (DB-backed) | Compensating steps (forward + reverse) with persistent dedup via `IdempotentConsumer` (redb RTTI storage / SQL backends, two-phase commit) — no built-in state machine | | Outbox | Yes (transactional outbox pattern) | Polling outbox via `Sql.Poll(...).OnSuccess(...).Transacted()` + persistent `IdempotentConsumer` (de-facto outbox) | | Publisher reliability | Yes (RabbitMQ confirms, Kafka EOS) | **Yes** — RabbitMQ publisher confirms, mandatory flag, transacted channels, automatic recovery; Kafka transactional producer + `Acks=All` + `IsolationLevel=ReadCommitted` | | Expressions | None | Compiled engine: 9 types, 17 predicates, `${header.x++}`, arithmetic | | Transactional routes | No | Yes — `.Transacted()` via `TransactionScope` | | License | Apache 2.0 | Apache 2.0 | Use MassTransit for **state-machine sagas with DB persistence** and a built-in transactional outbox table per consumer. Use redb.Route for enterprise integration end-to-end: 30+ EIP patterns, 30 transports, transactional pipelines (`ITransactedAction`), protocol bridging, file processing, and multi-transport pipelines — reliability primitives (publisher confirms, EOS, persistent dedup, polling outbox) composed from DSL building blocks. ### vs NServiceBus | Aspect | NServiceBus | redb.Route | |--------|-------------|------------| | Focus | Message bus (reliable delivery + Saga) | Enterprise Service Bus — 30 transports, 30+ EIP (Enterprise Integration Patterns), transactional pipelines | | Routing model | Message handler classes | Route pipelines | | EIP patterns | Saga (persistent), Request/Response | 30+ EIP patterns | | Transports | 7 (RabbitMQ, Kafka, SQS, Azure SB, SQL, MSMQ, Learning) | 30 (+ File, SFTP, MQTT, TCP, HTTP, gRPC, FTP, LDAP, IBM MQ, S3, …) | | Expressions | None | Compiled expression engine | | Transactional routes | No | Yes — `.Transacted()` via `TransactionScope` | | Monitoring | ServicePulse / ServiceInsight (commercial) | OpenTelemetry + redb.Tsak Web UI | | License | **Commercial** (free up to 2 endpoints/app) | Apache 2.0 | NServiceBus is mature and focused on guaranteed delivery and durable saga. redb.Route is Apache-2.0–licensed and covers enterprise integration end-to-end: 30+ EIP patterns, 30 transports, transactional pipelines (`ITransactedAction`), and a full runtime (redb.Tsak) with clustering, hot-reload, and OTel. ### vs Wolverine | Aspect | Wolverine | redb.Route | |--------|-----------|------------| | Focus | Mediator + message bus + Saga | Enterprise Service Bus — 30 transports, 30+ EIP (Enterprise Integration Patterns), transactional pipelines | | Routing model | Handler discovery + middleware | Route pipelines (`From → Process → To`) | | EIP patterns | Saga, Outbox, Request/Response | 30+ EIP patterns | | Transports | 4 (RabbitMQ, Kafka, Azure SB, SQS) | 30 (+ File, SFTP, SQL, MQTT, HTTP, gRPC, FTP, LDAP, IBM MQ, S3, …) | | Saga storage | Marten / EF Core | In-memory compensating steps | | Expressions | None | Compiled expression engine | | Transactional routes | Outbox-based | `.Transacted()` via `TransactionScope` | | License | MIT | Apache 2.0 | Wolverine is excellent at handler-style messaging with Marten-backed sagas. redb.Route covers enterprise integration end-to-end: 30+ EIP patterns, 30 transports, in-process mediator (`RedbController`), pub/sub (SEDA), transactional pipelines, and a full production runtime (redb.Tsak). --- ## Routing Patterns ```csharp // Content-Based Router .Choice() .When(Header("type").isEqualTo("order")).To("direct://orders") .When(Header("type").isEqualTo("payment")).To("direct://payments") .Otherwise().To("seda://unknown") .EndChoice() // Recipient List — send to multiple dynamic destinations .RecipientList(e => new[] { "direct://audit", "seda://analytics" }) // Dynamic Router — destination computed at runtime .DynamicRouter(e => ComputeNextEndpoint(e)) // Splitter — sub-route style .Split(e => SplitOrderIntoItems(e), sub => sub.Process(async (e, ct) => await ProcessItem(e, ct))) // Splitter — scope style .Split(e => SplitOrderIntoItems(e)) .Process(async (e, ct) => await ProcessItem(e, ct)) .EndSplit() ``` `When(...)` accepts three forms — lambda, `IPredicate`, or string expression: ```csharp .When(e => e.In.GetHeader("type") == "order") // lambda .When(Header("type").isEqualTo("order")) // IPredicate .When("header.type == 'order'") // string expression ``` --- ## Error Handling redb.Route's error handling is designed to be combined: per-step `Retry`, scoped `DoTry/DoCatch`, and one **error scope per route**, as in Apache Camel. From the inside out, the scope is: 1. the route's own `OnException` (declared anywhere in its body); 2. the `OnException` it shares with other routes: those of its `RouteBuilder` — that builder's routes only — and those of its [route configurations](#route-configuration--handlers-apart-from-the-routes); 3. the context's error handling — a local handler of the route (`AddLocalExceptionHandler`), a global handler (`AddGlobalExceptionHandler`), then `context.ErrorHandler` — for a failure **no `OnException` took** (`Handled(false)` included: an `OnException` that matched owns the failure, as in Camel). Among 1 and 2 the handler is chosen as Camel's exception policy chooses it: the failure is matched from its innermost cause up to the exception that was thrown, and the handler whose type is **nearest** wins wherever it is declared — a builder's `OnException` takes an `IOException` from the route's `OnException`. The route's own handler wins a tie; a route configuration's handler is used instead of the builder's handler of the same type. A body that runs after its caller has gone — `.Threads()` for an in-only exchange, a `Debounce` flush, an `Aggregate` completed by timeout, a `Resequence` batch — is wrapped by the same scope, with every handler setting; a redelivery re-runs that body. A `DeadLetterChannel` can route failed messages to any URI when retries are exhausted. ### Retry (per step) Local retry around a step, wrapped in a transaction. Useful when an external call may fail transiently. For route-level retry with backoff and a dead-letter sink, use `OnException(...)` (see Redelivery configuration below). ```csharp .Transacted() .Retry(attempts: 5, delay: TimeSpan.FromSeconds(1)) .To("http://flaky-service/submit") .EndTransaction() ``` ### Dead Letter Channel Routes the failing exchange to a sink endpoint after retries are exhausted. The dead letter channel belongs to the context, as Camel's context-level `errorHandler(deadLetterChannel(...))`: every route sends there a failure no `OnException` took, stamped with `CamelDeadLetterReason` / `CamelDeadLetterExceptionType` / `CamelDeadLetterTimestamp`, and the failure is handled. Redeliveries stay with `OnException`. ```csharp context.ErrorHandler = new DeadLetterErrorHandler(context, "direct://errors"); // The dead-letter route reads the stamped headers and decides what to do From("direct://errors") .Log("DLQ: ${header.CamelDeadLetterExceptionType}: ${header.CamelDeadLetterReason}") .Choice() .When(e => (string?)e.In.Headers["CamelDeadLetterExceptionType"] == typeof(TimeoutException).FullName) .To("seda://retry-later") .Otherwise().To("sftp://archive/failed/") .EndChoice(); ``` ```xml ``` A route whose `OnException` takes a failure keeps it from the context's handler; to dead-letter from inside that handler, send there explicitly: `OnException().Log("...").To("direct://errors")`. ### TryCatch (scoped) A `try/catch/finally` block inside a route. Choose this when only a specific section of the pipeline needs special handling. ```csharp .DoTry() .To("http://external-api/submit") .Process(async (e, ct) => await PostProcess(e, ct)) .DoCatch() .Log("HTTP failure: ${exception.message}") .To("seda://retry-queue") .DoCatch() .Log("Timeout, archiving") .To("sftp://archive/timeouts/") .DoFinally() .Log("Attempt complete (success or failure)") .End() ``` ### OnException — scope form (chain) Defines a handler for a specific exception type with full redelivery configuration. Two placement options: **Inside a route** — handler applies only to that single route: ```csharp From("kafka://orders") .OnException() .MaximumRedeliveries(3) .RedeliveryDelay(TimeSpan.FromSeconds(1)) .UseExponentialBackOff() .BackOffMultiplier(2.0) .Handled() // mark exception as handled, exchange continues .To("seda://timeout-handler") .EndOnException() .Process(...) .To("rabbitmq://processed"); ``` **At RouteBuilder level** — applies to every route of this builder, and to no route of another builder (Apache Camel's RouteBuilder scope; the same holds for a builder's `Intercept*` and `OnCompletion`). Handlers shared by the routes of several builders go into a [route configuration](#route-configuration--handlers-apart-from-the-routes): ```csharp public class OrderRoutes : RouteBuilder { protected override void Configure() { // Builder handlers — apply to all From(...) routes below, not to other builders' routes OnException() .MaximumRedeliveries(5) .UseExponentialBackOff() .Handled() .To("seda://http-failures") .EndOnException(); OnException() .MaximumRedeliveries(2) .UseOriginalBody() // restore original body before sending to handler .To("seda://db-failures") .EndOnException(); // Multiple exception types in one block OnException(typeof(TimeoutException), typeof(SocketException)) .MaximumRedeliveries(3) .To("seda://network-failures") .EndOnException(); From("kafka://orders") .To("http://payments-svc/charge"); From("kafka://shipments") .To("http://logistics-svc/dispatch"); } } ``` ### Route configuration — handlers apart from the routes Apache Camel's Route Configuration: `OnException` declared once, in a class of its own, for the routes of **every** builder of the context. Use it when a module keeps its error handling in one place and its routes in others. ```csharp public sealed class IntegrationErrors : RouteConfigurationBuilder { protected override void Configuration() { // No id: the default — every route of the context that has no configurations assigned. RouteConfiguration() .OnException() .MaximumRedeliveries(3) .UseExponentialBackOff() .Handled() .To("seda://http-failures"); // By id: only the routes that name it. RouteConfiguration("audit") .OnException().Handled().Log("audit failed: ${exception.message}"); } } context.AddRoutes(new IntegrationErrors()); // a configuration builder is added like any builder context.AddRoutes(new OrderRoutes()); // its routes get the default configuration // A route picks configurations by id: exact ids, a wildcard ("audit*") or a regular expression, comma-separated. From("direct://audit").RouteConfigurationId("audit").To("rabbitmq://audit"); ``` - A handler of a configuration has everything a builder's has — redeliveries, `OnWhen`, `Handled`/`Continued`, the handler's steps. The steps are compiled into each route they apply to, so `.SpanTag(..., SpanTarget.Inbound)` there tags the request that failed. - A route with assigned configurations does **not** get the default one. An id is unique within a context, and an exact id that no configuration has fails `Start()`. - Inline, without a class: `context.AddRouteConfiguration(c => c.OnException().Handled()...)` and `context.AddRouteConfiguration("audit", c => ...)`. - Route-XML: `` with `` blocks, in a routes file or in `context.xml`, and ``. - `Intercept*` and `OnCompletion` are not part of a route configuration yet; share them through a base class. ### OnException — several handlers Several handlers are several `OnException` blocks, each with its own redelivery options and its own steps: ```csharp OnException() .MaximumRedeliveries(3) .RedeliveryDelay(TimeSpan.FromSeconds(2)) .UseExponentialBackOff() .Log("Timeout, retry").To("seda://retry") .EndOnException(); OnException() .MaximumRedeliveries(5) .To("seda://http-fail") .EndOnException(); OnException() .To("seda://db-fail") .EndOnException(); ``` ### Redelivery configuration All modifiers below are valid inside an `OnException(...).EndOnException()` scope: | Method | Purpose | |--------|---------| | `MaximumRedeliveries(n)` | Max retry attempts before handler fires | | `RedeliveryDelay(TimeSpan)` | Base delay between attempts | | `BackOffMultiplier(d)` | Multiplier applied to delay between attempts | | `UseExponentialBackOff()` | Switch from fixed to exponential backoff | | `Handled()` / `Handled(false)` | Suppress the failure; the route ends where it failed | | `Continued()` | Suppress the failure and pick the route up at the step after the one that failed (Camel's `continued(true)`) | | `OnWhen(predicate)` | Only fire the handler when predicate matches | | `RetryWhile(predicate)` | Continue retrying only while predicate is true | | `UseOriginalMessage()` | Restore the original message (before processing) for the handler | | `UseOriginalBody()` | Restore only the original body | | `OnRedelivery(action)` / `OnRedelivery(processor)` | Callback fired before each retry attempt | | `OnPrepareFailure(action)` / `OnPrepareFailure(processor)` | Callback fired before invoking the handler | | `OnExceptionOccurred(action)` / `OnExceptionOccurred(processor)` | Callback fired the moment exception is caught; the processor form is what a markup route can name | | `RetryAttemptedLogLevel(level)` | Log level for retry attempt messages | | `RetriesExhaustedLogLevel(level)` | Log level for retries-exhausted message | | `LogStackTrace(bool)` | Whether to log full stack trace | | `LogExhausted(bool)` | Whether to log when retries are exhausted | | `RedeliveryPolicy(policy)` | Apply a pre-built `RedeliveryPolicy` instance | ### Combined example Global policy + route-local override + DLC + per-step retry, all together: ```csharp public class PaymentRoutes : RouteBuilder { protected override void Configure() { // 1. Global policy — transient HTTP errors retry 5x with exponential backoff OnException() .MaximumRedeliveries(5) .RedeliveryDelay(TimeSpan.FromSeconds(1)) .UseExponentialBackOff() .BackOffMultiplier(2.0) .RetryAttemptedLogLevel(LogLevel.Warning) .OnRedelivery(e => Metrics.Inc("redelivery", 1)) .Handled() .To("seda://transient-failures") .EndOnException(); From("kafka://payments?groupId=svc") .RouteId("payment-pipeline") // 2. Route-level dead letter — a failure no nearer handler takes ends up here .OnException() .Handled() .To("seda://payments-dlq") .EndOnException() // 3. Route-local override — timeout policy specific to this route .OnException() .MaximumRedeliveries(2) .UseOriginalBody() .To("seda://payment-timeouts") .EndOnException() .Validate(e => ((Payment)e.In.Body!).Amount > 0) .Process(async (e, ct) => await EnrichWithCustomer(e, ct)) // 4. Per-step retry: wrap the charge in a transaction that retries .Transacted() .Retry(attempts: 3, delay: TimeSpan.FromMilliseconds(500)) .To("http://payments-gateway/charge") .EndTransaction(); From("seda://payments-dlq") .Log("Payment DLQ — ${exception.message}") .To("sftp://archive/payments/failed/"); } } ``` Resolution when several handlers match: the nearest exception type wins among the route's `OnException`, its route configurations' and its builder's — on a tie the route's own, then the configuration's; a failure none of them took goes to the context's handlers and `DeadLetterChannel`, and otherwise stays unhandled (logged and propagated). A failure with causes is matched as Apache Camel's `DefaultExceptionPolicyStrategy` matches it: every exception of the chain, from the innermost cause up to the one that was thrown, finds its nearest handler, and the handler with the smallest distance over the whole chain wins. The innermost cause only breaks a tie, and an exact type ends the search. So a cause does not win just because it is a cause: ```csharp // UniqueViolationException : Exception, thrown with a driver exception inside: // UniqueViolationException -> PostgresException : NpgsqlException : DbException OnException().Handled().SetHeader("HttpStatus", 409); OnException().Handled().SetHeader("HttpStatus", 500); // 500: the thrown exception is one step from Exception, its cause two steps from DbException. ``` To have such a failure taken by the specific handler, add a handler for the exception that is thrown (`OnException()`), or give the wide one an `OnWhen` that leaves it alone. --- ## Message Transformation ```csharp // Set body — static, lambda, or expression .SetBody("static value") .SetBody(e => TransformPayload((Order)e.In.Body!)) .SetBody(JPath("$.order.items")) .SetBody(Expr("${header.orderId}-${body}")) // Transform body .Transform(e => JsonSerializer.Serialize(e.In.Body)) .Transform(JPath("$.order.summary")) // Headers .SetHeader("source", "order-service") .SetHeader("source", e => e.In.GetHeader("origin") ?? "unknown") .SetHeader("total", JPath("$.order.total")) .RemoveHeader("internal-trace-id") // Exchange properties .SetProperty("retryCount", 0) .SetProperty("startedAt", e => DateTimeOffset.UtcNow) .RemoveProperty("temp-flag") // Marshal / Unmarshal .Marshal(typeof(JsonMessageSerializer)) .Unmarshal(typeof(XmlMessageSerializer), typeof(Order)) // HTML form data (built in): the posted fields, repeated names kept .ConvertBody() .SetHeader("claim", e => ((FormBody)e.In.Body!).Get("claim")) ``` ### Attachments A message carries attachments beside its body, as Apache Camel's `AttachmentMessage`: `exchange.In.Attachments` is an ordered list (a name may repeat, as several files of one form field do) of `Attachment` objects with a name, a file name, a content type, part headers and content that is read from the start on every open: bytes, a file, or a `StreamCache`. ```csharp .AddAttachment("note", Expr("${header.comment}"), fileName: "note.txt") // from an expression .AddAttachmentFromBody("invoice", fileName: "invoice.pdf", contentType: "application/pdf") .AddAttachmentFromFile(Header("CamelFileAbsolutePath")) // read from disk on every send .Filter("attachments.size > 0") .RemoveAttachment("note") ``` ```xml ``` - In expressions: `attachments.size`, `attachments[0].fileName`, `attachmentContent(name)` (bytes), `attachmentContentAsText(name)`, `attachmentContentType(name)`, `attachmentHeader(name, header)`, the names of Camel Simple. The content functions read the whole content, so they suit small parts. - Attachments belong to the message: `Clone` and Split parts share their content, a step that writes `Out` with attachments replaces those of `In` and one without leaves them. A content source that holds a resource (a `StreamCache`, a file created with `deleteWithExchange: true`) is released with the exchange, like a body: read or copy it before the exchange ends (an `http:` consumer ends it once the response is written). - A `.Replayable()` checkpoint copies attachment content; above `RedbRoute:Attachments:MaxReplayableBytes` (10 MB by default) the checkpoint is not taken and the exchange is not replayable, from the checkpoint or from the Tsak DLQ. - Transports do not send attachments by themselves: only a producer whose protocol has a place for them does. - `multipart/form-data` uploads and `multipart/mixed` bodies are read into attachments and written back by [redb.Route.DataFormats.Mime](redb.Route.DataFormats.Mime/README.md). - A data format that needs the whole exchange (the content type with its parameters, the body as a stream, the attachments, the engine's stream cache options) implements `IMessageDataFormat`; `Marshal`, `Unmarshal` and `ConvertBody` call it with the exchange, as Camel's `DataFormat` is called. Which headers a transport carries each way between the exchange and the wire is decided by a header filter strategy, as Apache Camel's `HeaderFilterStrategy`: each transport has a default, and `headerFilterStrategy=#name` on an endpoint names one of yours from the registry (HTTP, Kafka, RabbitMQ, AMQP, Azure Service Bus, IBM MQ, gRPC, SQS/SNS, AS2, `vm:` sends). See [Header filter strategy](redb.Route/README.md#header-filter-strategy) and the README of each transport. --- ## Expression Language redb.Route has a compiled expression engine. Templates and predicates compile to `Func` via `System.Linq.Expressions` — no interpreter overhead, the compiled delegates are cached. ### Helpers All helpers are `protected static` methods on `RouteBuilder` — use them directly inside `Configure()`: ```csharp // Message accessors Body() // read message body Header("name") // read header value Property("key") // read exchange property Constant(42) // constant value Exchange(e => e.RouteId) // delegate over IExchange // Structured data JPath("$.order.total") // JSONPath expression JPath("$.order.total") // typed JSONPath XPath("/order/status/text()") // XPath expression XPath("/order/status") // typed XPath // String templates (StringExpression — bridges ${...} to IExpression) Expr("${header.orderId}") // single header interpolation Expr("${header.prefix}-${body}") // multi-value template Expr("header.amount") // raw value expression (no ${}) ``` ### Predicates Every expression supports 17 predicate methods returning `IPredicate` for use in `Filter()`, `When()`, `Validate()`: ```csharp // Comparison Header("status").isEqualTo("active") Header("status").isNotEqualTo("cancelled") Header("amount").isGreaterThan(1000) Header("amount").isLessThan(500) Header("amount").isGreaterThanOrEqualTo(100) Header("amount").isLessThanOrEqualTo(9999) Header("amount").isBetween(100, 5000) // String Header("name").contains("Corp") Header("name").startsWith("Order-") Header("name").endsWith(".pdf") Header("email").regex(@"^[\w.]+@[\w.]+\.\w+$") // Collection Header("type").In("order", "payment", "refund") // Null Header("optional").isNull() Header("required").isNotNull() ``` ### Expressions, templates and conditions The full guide is [EXPRESSIONS.md](EXPRESSIONS.md): positions of the language, operators and functions, templates and types, truthiness, braces and quoting, the `bean:` function, `Method()`, and what `check` / `pack` verify. Every example there is run by the test suite. In short: ```csharp .Filter("header.amount > 1000 AND header.region == 'eu'") // a condition, written bare .SetHeader("routeKey", Expr("${header.region}-${header.id}")) // a template: text with placeholders .SetHeader("total", Expr("${header.qty * header.price}")) // a whole placeholder keeps its type .SetBody(Expr("upper(body)")) // an expression .Filter("bean:loyalty.IsGold(header.customer)") // a registry bean's method in a condition .SetBody(Method("#pricing", "Gross(${header.qty}, 2.5)")) // the same call, typed (Camel's method()) .SetHeader("note", "a>b is not a comparison here") // a plain string is a literal ``` A root of your own (`${order.total}`) is a prefix resolver. Registered on a route context, it serves the expressions of that context only and goes with it, so an unloaded module leaves nothing behind; the process-wide `ExpressionResolver.RegisterPrefixResolver` is consulted after the context's own: ```csharp context.RegisterPrefixResolver("order.", (exchange, path) => orders.Read(exchange, path)); ``` --- ## Other EIP Patterns ```csharp // Wire Tap — send copy to audit without affecting main flow .WireTap("seda://audit") // Multicast — send to multiple endpoints in parallel .Multicast().To("direct://service-a").To("direct://service-b").EndMulticast() // Throttle — rate limiting .Throttle(100) // max 100 messages/second .Throttle(500, TimeSpan.FromMinutes(1)) // max 500 per minute // Circuit Breaker .CircuitBreaker(cb => cb .Threshold(5) .ResetTimeout(TimeSpan.FromSeconds(30))) // Idempotent Consumer — deduplicate (works as outbox-style dedup with persistent backend) .IdempotentConsumer(e => e.In.GetHeader("messageId"), repository) // InMemoryIdempotentRepository — process-local, default // SqlIdempotentRepository — ADO.NET, two-phase commit, survives restarts // RedbIdempotentRepository — redb.Core RTTI storage, two-phase commit, cluster-wide // Claim Check — park a large body, carry a short key through the route .ClaimCheck(ClaimCheckOperation.Set, "order-42") // body → key (original type kept in headers) .To("kafka://orders") // the broker carries the key, not the payload .ClaimCheck(ClaimCheckOperation.Get, "order-42") // key → body // Push/Pop use an exchange-scoped stack instead of a key, and nest .ClaimCheck(ClaimCheckOperation.Push) .Enrich("http://scoring/api") .ClaimCheck(ClaimCheckOperation.Pop) // InMemoryClaimCheckRepository — process-local, the default when none is named // FileClaimCheckRepository — one file per claim with TTL, for very large bodies or a shared FS // context.AddClaimCheckRepository("big-payloads", repo) then .ClaimCheck(op, key, repositoryName: "big-payloads") // Loop — fixed count or conditional; the body runs until End() .Loop(3).Process(e => Retry(e)).End() .Loop(e => !e.In.GetHeader("done")).Process(e => DoWork(e)).End() // Delay .Delay(TimeSpan.FromSeconds(5)) .Delay(e => TimeSpan.FromSeconds(e.In.GetHeader("backoff"))) // Resequencer — reorder messages .Resequence(e => e.In.GetHeader("sequenceNumber")) // Enrich — content enricher .Enrich("http://api/details", (original, enrichment) => Merge(original, enrichment)) // Saga — compensating steps .Saga(s => s .Step( action: async (e, ct) => await ReserveInventory(e, ct), compensate: async (e, ct) => await ReleaseInventory(e, ct)) .Step( action: async (e, ct) => await ChargePayment(e, ct), compensate: async (e, ct) => await RefundPayment(e, ct)) .OnCompletion(async (e, ct) => await PublishOrderCompleted(e, ct))) // Transacted — wrap pipeline step in TransactionScope .Transacted() // Control Bus — manage routes at runtime (start/stop/suspend/resume/restart/status/stats/fail) .ControlBus(ControlBusAction.Stop, "orders") // "current" targets the sending route .To("controlbus:route?routeId=orders&action=restart") // or as a URI // controlbus:notify also exposes route lifecycle events as a consumer (beyond Camel) // Process — inline async with CancellationToken .Process(async (exchange, ct) => { var order = (Order)exchange.In.Body!; var result = await ProcessOrder(order, ct); exchange.In.Body = result; }) ``` ### A Wire Tap runs on a bounded pool Each `WireTap` runs its copies on a pool of its own, built from a thread pool profile as Apache Camel builds one per EIP: at most `MaxConcurrency` copies at a time (20 by default), at most `MaxQueueSize` waiting (1000), and a copy that finds both full is handled by `RejectedPolicy`: | `RejectedPolicy` | What happens | |---|---| | `CallerRuns` (default) | the route's own thread runs the copy before it goes on: nothing is lost, the source slows down | | `Discard` | the copy is dropped, counted and logged; the route goes on at once | | `Abort` | the step fails with `RejectedExecutionException`, which the route can handle | A copy the caller runs is still detached: it runs outside the caller's transaction and without its deferred sends, on the clone, and its failure never fails the route. A tap whose target is slow (an audit store, a remote sink) therefore costs the route's own threads once its pool is full, instead of an unbounded pile of background work; `redb.route.pool.caller_runs` shows when that starts. ```csharp // The default profile for every tap that names none var context = new RouteContext(options: new RouteEngineOptions { DefaultThreadPoolProfile = { MaxConcurrency = 20, MaxQueueSize = 1000 }, }); // A named profile, picked by executorService context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 50, MaxQueueSize = 5000, RejectedPolicy = ThreadPoolRejectedPolicy.Discard, // an audit copy may be lost under overload }); From("direct://orders") .WireTap("seda://audit", executorService: "audit") .To("direct://process"); ``` Named profiles also come from configuration (`RedbRoute:ThreadPoolProfiles:`, and `RedbRoute:DefaultThreadPoolProfile`). A module that builds its routes in code registers its profile with `AddThreadPoolProfile` before its routes start; registering a name again with other bounds throws, and a tap that names an unknown profile fails when its route is built. When the context stops, the copies still running or waiting get the shutdown timeout to finish; what is left is counted (`redb.route.pool.not_drained`) and logged. Metrics, tagged with `profile`, `step` and `route`: `redb.route.pool.active`, `redb.route.pool.queued`, `redb.route.pool.caller_runs`, `redb.route.pool.rejected`, `redb.route.pool.failed`, `redb.route.pool.not_drained`. ### Where an OnCompletion block runs As in Apache Camel, an `OnCompletion` block runs in the caller once the route has finished, and the caller waits for it before it gets the exchange back. `ParallelProcessing()` runs the block on a bounded pool of its own instead (the default thread pool profile), and `ExecutorService("name")` on one built from a named profile; the caller then goes on at once, and the context waits for running blocks when it stops. `ModeBeforeConsumer()` runs the block before the consumer writes its reply. ```csharp From("direct://orders") .OnCompletion().OnCompleteOnly().To("direct://audit").EndOnCompletion() // the caller waits .OnCompletion().ParallelProcessing().To("seda://notify").EndOnCompletion() // the caller does not .To("direct://process"); ``` In every mode the block gets a copy of the exchange and never changes the route's result: a block that fails is logged and counted (`redb.route.oncompletion.failed`). A block after the consumer runs outside the caller's transaction and without its deferred sends, and it never gets the caller's cancellation token: an aborted request does not cut an audit or a cleanup half way. --- ## Bean References User code is called through the `bean:` component, Apache Camel's bean component. Every spelling below, in C# or in XML, produces the same endpoint, so its cache entry, statistics and redaction are the same: ```csharp .To("bean:#pricing?method=Gross(${header.qty}, ${header.price})") // the URI .Bean("#pricing", "Gross(${header.qty}, ${header.price})") // Camel's bean(ref, method) .Bean("Acme.Orders.Pricing, Acme.Orders", "Gross") // an instance the endpoint creates ``` ```xml ``` - **The target.** `#name` is an object in the context registry (`AddToRegistry`, or a `` declaration under `` or ``). `Namespace.Type, Assembly` is an instance created per endpoint; further options (`Currency="EUR"`) set its public properties. - **The method.** `method=Name` calls a method taking `(IExchange)` or `(IExchange, CancellationToken)`. `method=Name(arg, ...)` binds each argument from a route-language expression and converts it to the parameter type; an `IExchange`, `IMessage` or `CancellationToken` parameter is filled in by the binding. Without `method=` the single suitable method is called. - **The result.** A returned value (awaited for `Task` and `ValueTask`) becomes the body; a `void` or `Task` method leaves the body as it was. - **An `IProcessor` object.** `bean:#myProcessor` calls its `Process(IExchange, CancellationToken)` when that is the type's single suitable method. If the type has others, name it: `bean:#myProcessor?method=Process`. - **Lifetime.** An instance lives as long as its endpoint, so equal URIs share it. For a service per exchange, `.Bean((service, exchange) => ...)` resolves `TService` from the exchange's service provider. A registry bean's method can also stand where an expression stands: in a condition, a value or a template. ```csharp .Filter("bean:loyalty.IsGold(header.customer)") // the expression function, bare .SetHeader("total", Expr("${bean:pricing.Gross(header.qty, 2.5)}")) .Filter(Method("#loyalty", "IsGoldAsync(${header.customer})")) // Camel's method(); Task is awaited here ``` ```xml ``` The function is synchronous, as in Apache Camel's Simple language: an asynchronous method is called as a step. `Method()` in a condition awaits a `Task`. The rules are in [EXPRESSIONS.md](EXPRESSIONS.md#11-calling-a-bean-bean). --- ## Request-Response (InOut) For synchronous request-response over HTTP/gRPC/WebSocket, mark the listener as `InOut()` and finish the route with `.Respond()`: ```csharp public class OrderApi : RouteBuilder { protected override void Configure() { From(Http.Listen("/api/orders").Port(8080).InOut()) .Unmarshal(typeof(JsonMessageSerializer), typeof(CreateOrderRequest)) .Process(async (e, ct) => { var req = (CreateOrderRequest)e.In.Body!; var resp = await orderService.CreateAsync(req, ct); e.In.Body = resp; }) .Marshal(typeof(JsonMessageSerializer)) .Respond(); // returns the body to the HTTP client } } ``` The same pattern works for `GrpcDsl.Listen(...)` and `Ws.Listen(...)`. --- ## Concurrency & Parallelism redb.Route separates concurrency into two axes: **consumer-level** (how many messages the source pulls at once — a transport option like `.ConcurrentConsumers(N)` / `.MaxConcurrentCalls(N)` / Kafka partitions) and **processing-level** (how many the pipeline processes at once, via the **`.Threads(N)`** EIP). ```csharp // Serial poll source (File/SQL/S3/IMAP/…) → fan the processing out to a pool of 10: From("file://in").Threads(10).Process(HeavyTransform).To("http://api").End(); // Broker source → use its native competing-consumer knob (keeps delivery/ack semantics): From(Mqtt.Subscribe("telemetry/#").Qos(1).ConcurrentConsumers(5)).Process(Ingest).End(); ``` `.Threads(N)` is an async boundary (like `.To("seda://")`): backpressured bounded queue, own DI scope per exchange, graceful drain-on-stop, errors routed to `OnException` — ordering not preserved when `N > 1`. Full guide, per-transport table, and Camel mapping: **[CONCURRENCY.md](CONCURRENCY.md)**. --- ## Behaviour Guarantees A few behaviours are easy to get wrong from reading a single method, so they are stated here. ### A stopped exchange and `DoFinally` `exchange.Stop()` stops the pipeline from running its remaining steps; it is not an exception. A `DoFinally()` block still runs, because it is the C# `finally` of `TryCatchProcessor`: the body is abandoned at the point of the stop and the finally runs on the way out. A failure and a cancellation behave the same way. `DoCatch` / `DoFinally` therefore give you a cleanup hook that fires whatever happened inside the try. ### A stop in a route called over `direct-vm:` A plain `direct-vm:` call runs the called route on the caller's own exchange. A `Stop()` in the called route therefore ends the caller's route too, and an HTTP consumer further up the chain answers with what the called route left on the exchange: its body, its `redbHttp.ResponseCode` and its headers. The calling route does not get control back: - a check after `.To("direct-vm:...")` does not run, because the caller's route is stopped; - a `DoTry` / `DoCatch` around the call does not catch anything when the called route marked its exception handled (`ExceptionHandled = true`), since no exception is thrown; - `headerFilterStrategy=#name` on the call runs the called route on a linked copy, but the copy hands the stop back with the body, the reply headers, the properties and the exception, so the caller stops the same way. To answer on its own terms, the caller uses `Enrich`. It calls on a linked copy, the stop stays on that copy, and the merge function decides what comes back: the body and the headers of the exchange it returns are written to the original, and so is its exception. Return the original from the merge: ```csharp From("http://0.0.0.0:8080/parties/find-user") .Enrich("direct-vm:auth.check", (original, call) => { var reply = call.HasOut ? call.Out! : call.In; if (reply.Headers.TryGetValue("redbHttp.ResponseCode", out var code) && Convert.ToInt32(code) >= 400) { original.In.Body = "{\"code\":\"parties.not_allowed\"}"; original.In.Headers["redbHttp.ResponseCode"] = 403; original.In.Headers["redbHttp.ResponseContentType"] = "application/json"; original.Properties["refused"] = true; } else original.In.Body = reply.Body; return original; }) // the steps after Enrich run in both cases; ${property.refused} tells them apart ``` ### The Out → In merge between pipeline steps When a step writes `exchange.Out`, the pipeline merges it into `In` before the next step: the body and every header of `Out` are copied over, `ContentType` is copied only when `Out` carries one (a step that leaves it `null` does not wipe the In content type), and `Out` is then cleared. The merge happens only between steps, so the last step's `Out` is left in place for an InOut caller. ### Properties in a Split branch A `Split` branch is a child exchange, as in Apache Camel. A part that is an `IMessage` (a record of a batch consumer, for example) becomes the branch's message: a copy with its own body, headers and content type, without the parent's headers. Any other part becomes the body under a copy of the parent's In headers. The split metadata are exchange properties of the branch, not headers: `CamelSplitIndex`, `CamelSplitSize`, `CamelSplitComplete`, and `CamelCorrelationId` (the parent's exchange id); read them as `${property.CamelSplitIndex}` or `exchange.GetProperty(ExchangePropertyKeys.SplitIndex)`. A streaming split knows the size only at its end: the last part and the parent carry `CamelSplitSize`. The branch inherits the parent's properties: the property dictionary is inherited, and the values are shared, not deep-copied. Writing a property on a branch does not reach the parent; the aggregation strategy decides what goes back. ### `now()` and `delay` - `now()` returns a `DateTime` with `DateTimeKind.Utc`. - `delay` accepts a `TimeSpan`, an `int` / `long` / `double` meaning milliseconds, a string that parses as a number of milliseconds, or a string that parses as `hh:mm:ss`. Anything else throws `InvalidOperationException` at run time. --- ## Reliability redb.Route provides four primitives for at-least-once and exactly-once delivery. They compose: enable confirms on the producer, persistent dedup on the consumer, polling outbox in your service — you have the same guarantees that frameworks bundle as `UseOutbox()`, just spelled out. ### RabbitMQ Publisher Confirms + Deferred Consumer Ack The RabbitMQ producer uses publisher confirms by default with broker-side flow control: ```csharp .To(Rabbit.Queue("orders") .Host("rabbit.local") .ConfirmTimeout(5000) // a send the broker does not confirm in 5 s fails (RabbitMQPublishTimeoutException) .Mandatory() // unroutable messages surface as exceptions (BasicReturn) .Transacted(false) // or use AMQP transactions instead of confirms .AutomaticRecovery(true) // reconnect + re-declare topology on broker restart .TopologyRecoveryEnabled(true)) ``` Every `BasicPublishAsync` call awaits broker confirmation, at most `confirmTimeout` milliseconds, so a broker that blocks its publishers under a memory or disk alarm fails the send instead of holding it; producer back-pressure kicks in when `maxOutstandingConfirms` (a URI parameter, 2048 by default) is reached. `Mandatory(true)` surfaces `BasicReturn` events as exchange exceptions — routing failures fail loudly. ### Deferred Ack — `ITransactedAction` (RabbitMQ, AMQP, IBM MQ, Kafka) The deferred send pattern is implemented uniformly across the brokers. When `.Transacted()` is active, a producer send fires not at the step but after the transaction closed; the consumer settles the incoming delivery after that. Both are registered as `ITransactedAction` instances on the exchange (`exchange.Properties["TRANSACT_ACTION"]`) and execute together when the `TransactionScope` closes. | Transport | Unit of work succeeded | Unit of work failed | |-----------|--------|----------| | **RabbitMQ** consumer | `TxCommit` + `BasicAck(deliveryTag)` | tried again up to `maximumRetryAttempts`, then `BasicReject(requeue=false)` to the dead letter exchange (`rejectAndDontRequeue=false`: `BasicNack(requeue=true)`) | | **RabbitMQ** producer | `BasicPublishAsync` fires | message dropped | | **AMQP 1.0** consumer | `receiver.Accept(msg)` | `receiver.Release(msg)` | | **AMQP 1.0** producer | `sender.Send(msg)` fires | message dropped | | **IBM MQ** consumer | `QueueManager.Commit()` (MQCMIT) | `QueueManager.Backout()` (MQBACK) | | **IBM MQ** producer | MQPUT + MQCMIT | message dropped | | **Kafka** consumer | offset committed after the route, or inside the producer's Kafka transaction (below) | offset not committed; `breakOnFirstError=true` reads the record again | | **Kafka** producer | `ProduceAsync` fires; with `transactionalIdPrefix` the block's sends commit as one Kafka transaction | message dropped | A unit of work ends in one order: the database transaction completes and closes, then the deferred sends go out, then the consumer acknowledges the incoming message. The acknowledgement belongs to the consumer, not to the transaction: a delivery is settled only after the whole unit of work succeeded, and left unsettled when it was not, so the broker redelivers it. See [TRANSACTIONS.md](TRANSACTIONS.md). IBM MQ additionally tracks `BackoutCount`; if it reaches `BackoutThreshold`, the message moves to a backout queue instead of rolling back into the main queue indefinitely (poison message handling). ```csharp // Same .Transacted() syntax regardless of broker From(Rabbit.Queue("orders").Transacted(true)) .Transacted() .Process(async (e, ct) => await SaveToDb(e, ct)) .To(Rabbit.Queue("processed").Transacted(true)); // Commit: the database, then BasicPublish(processed), then BasicAck(orders) // Rollback: send dropped; the delivery is tried again, then rejected to the dead letter exchange From("wmq://ORDERS.IN?transacted=true") .Transacted() .Process(async (e, ct) => await SaveToDb(e, ct)) .To("wmq://ORDERS.OUT?transacted=true"); // Commit: MQCMIT on both consumer and producer // Rollback: MQBACK — message back in ORDERS.IN From(Kafka.Topic("payments").GroupId("svc")) .Transacted() .Process(async (e, ct) => await SaveToDb(e, ct)) .To(Kafka.Topic("processed").TransactionalIdPrefix("payments-svc")); // Commit: the database, then one Kafka transaction with the send and the consumed offset // Rollback: nothing sent, offset not committed ``` ### Lost connections: reconnect, health and your own reaction A connector that runs on the connection supervisor (IBM MQ: poll and batch consumers, the XMS listener, the producer with its reply receivers) does the same when its broker restarts or the network drops: - it reconnects by itself, 1 s after the loss, then 2, 4, 8 ... up to 30 s between attempts; one attempt is given up after 30 s, so a connect that hangs while the broker starts does not stop the next one; - it writes one warning line when the connection is lost and one information line when it is back (failed attempts are logged at debug level), so a long outage does not flood the log; - the endpoint's health says so: `Warning` while the first attempt is pending, `Critical` once an attempt failed, back to the counters when the connection is restored. A `Critical` source endpoint makes its route `Unhealthy` in the route health check, so a consumer that cannot reach its broker is visible on `/health`, not only in the log; - `IEndpointStatistics.Reconnects` counts the losses it recovered from. A loss is not counted in `Errors`: it is not a failed message, so health is `Healthy` again as soon as the connection is back and the error rate stays the rate of failed messages. A producer does not resend: a send that failed on the lost connection may have arrived. The next send reconnects; a send that comes before the next attempt is due fails at once and says when it is due. A transacted send whose commit (MQCMIT) meets the lost connection is reported as in doubt. The schedule is set once for the context, under `RedbRoute:Reconnect`: ```jsonc // appsettings.json { "RedbRoute": { "Reconnect": { "Delay": "00:00:01", // pause before the first attempt "Multiplier": 2.0, // each failed attempt multiplies the pause "MaxDelay": "00:00:30", // longest pause "AttemptTimeout": "00:00:30", // one attempt is given up after this "WarningPeriod": "00:00:00" // > 0: a loss stays Warning (not Critical) for this long } } } ``` `WarningPeriod` is for brokers that restart on purpose, such as nightly maintenance: with `"00:02:00"` a restart that is over within two minutes never turns the route `Unhealthy`. #### Connection events Every change is also an event: `ConnectionLost`, `ReconnectFailed` (an attempt failed) and `ConnectionRestored`. You get them in two ways, both fed from one queue of the context after the change: a listener that is slow or throws holds up nothing, the reconnect goes on. When listeners fall more than 1024 events behind, the oldest events are dropped and one warning line says so. | `ConnectionEvent` property | `controlbus:notify` header | Meaning | |---|---|---| | `Kind` | `controlbus.event` | `Lost`, `AttemptFailed`, `Restored` (headers: `ConnectionLost`, `ReconnectFailed`, `ConnectionRestored`) | | `Endpoint` | `controlbus.endpoint` | the endpoint, short form, secrets masked | | `RouteId` | `controlbus.routeId` | the route that reads from the endpoint; none for a producer or an endpoint several routes read | | `Connection` | `controlbus.connection` | which connection, such as `wmq:ORDERS consumer worker 2` or `wmq:ORDERS listener` | | `State` | `controlbus.connectionState` | `Connected`, `Recovering` or `Disconnected` after the change | | `Error`, `ErrorMessage` | `controlbus.error` | the failure (the header carries the masked message); none on `Restored` | | `Attempt` | `controlbus.attempt` | failed attempts since the loss; 0 on `Lost` | | `NextDelay` | `controlbus.nextDelayMs` | time until the next attempt; none on `Restored` | | `Outage` | `controlbus.outageMs` | how long the connection has been lost; on `Restored`, how long it was | | `Reconnects` | `controlbus.reconnects` | how many times this connection was restored | | `Time` | `controlbus.timestamp` | when, UTC | **A route on `controlbus:notify`** receives each event as a message: the body is the event name, the fields are headers. `events=` filters by name, `routeId=` by route. This works the same from C# and from XML route files: ```csharp // Alert on a lost connection and on its recovery. r.From("controlbus:notify?events=ConnectionLost,ConnectionRestored") .RouteId("connection-alerts") .To("log://connections?level=Warning") .To("http://alerts.internal/hooks/route"); ``` ```xml ``` **A listener in code** overrides `IRouteLifecycleListener.OnConnectionEvent` (all other methods have empty defaults): ```csharp public sealed class ConnectionWatcher(IRouteContext context, ILogger logger) : IRouteLifecycleListener { public async Task OnConnectionEvent(ConnectionEvent e, CancellationToken ct) { logger.LogWarning("{Kind} {Connection} ({Endpoint}): outage {Outage}, {Error}", e.Kind, e.Connection, e.Endpoint, e.Outage, e.ErrorMessage); // Give up on a consumer that has been away for ten minutes: stop its route, a person starts it again. if (e.Kind == ConnectionEventKind.AttemptFailed && e.RouteId is { } routeId && e.Outage > TimeSpan.FromMinutes(10)) await context.StopRoute(routeId, ct); } } // Registration: on the context ... context.AddLifecycleListener(new ConnectionWatcher(context, loggerFactory.CreateLogger())); // ... or from DI services.AddRouteContextConfigurator((sp, ctx) => ctx.AddLifecycleListener(new ConnectionWatcher(ctx, sp.GetRequiredService>()))); ``` #### Deciding what to do: the Control Bus The reconnect itself is not yours to steer; what happens to the route is. The Control Bus (`controlbus:route`, or `.ControlBus(...)` in C#) acts on a route at runtime, and a route on `controlbus:notify` can send to it: | `action` | What it does | |---|---| | `start` | starts a stopped route | | `stop` | stops the route: its consumer and its reconnect loop end; the route stays registered | | `suspend` | the same as `stop` | | `resume` | starts a stopped or suspended route again, honouring its route policy | | `restart` | `stop`, then `start` after `restartDelay` ms (default 1000) | | `fail` | stops the route and marks it `Errored`: the route health check reports it `Unhealthy` | | `status` | puts the route's status on the message body | | `stats` | puts the route's statistics (all routes without `routeId`) on the message body | Options: `routeId` (required except for `stats`; `current` means the route that sends), `action`, `async=true` to act without waiting (default `false`), `restartDelay` (ms), `loggingLevel` (default `Info`). The Control Bus acts within its own context; to control another context, send over `direct-vm:` or `vm:` to a route there. Fail the consumer route once an attempt to reconnect failed, so the health check and your orchestrator see it at once: ```csharp r.From("controlbus:notify?events=ReconnectFailed&routeId=orders-in") .RouteId("orders-in-give-up") .To("controlbus:route?routeId=orders-in&action=fail"); ``` ```xml ``` Stop a route while the broker is away and start it again by hand or from another route (`controlbus:route?routeId=orders-in&action=start`), or restart it after a pause: `controlbus:route?routeId=orders-in&action=restart&restartDelay=5000`. What not to do in a reaction: resend messages (a send that failed on a lost connection may have arrived, a resend can duplicate it), wait for a person or do long I/O inside a listener (alert instead and decide later through the Control Bus), or change addresses and passwords from a reaction (they belong to the endpoint's connection settings). ### Kafka exactly-once (EOS) `TransactionalIdPrefix` switches a Kafka producer to Kafka transactions. The sends it defers in a `.Transacted()` block commit as one Kafka transaction, all or none; when the route consumed from Kafka on the same cluster, the consumed offset commits in that transaction too (`SendOffsetsToTransaction`), so the output and the offset move together. Readers use `read_committed`, librdkafka's default. The database is not part of the Kafka transaction: it commits first, and the idempotent consumer covers a failure between the two. ```csharp From(Kafka.Topic("orders").Brokers("broker1:9092,broker2:9092").GroupId("order-svc")) .Transacted() .To(Kafka.Topic("orders.enriched") .Brokers("broker1:9092,broker2:9092") .TransactionalIdPrefix("order-svc")) // acks=all and idempotence come with it .End(); ``` The prefix names the producer; the connector appends the machine, the process and the producer's number, so nodes deploying one configuration never fence each other. Details in the [Kafka connector README](redb.Route.Kafka/README.md). ### Persistent Idempotent Consumer (de-facto outbox for dedup) `IdempotentConsumer` claims a message's key before its block runs and skips a message whose key is already claimed. With a persistent backend the claim survives restarts and is shared by every node on the same database, the same role an Outbox `processed_messages` table plays in MassTransit / NServiceBus: the database's unique key decides which node processes a message. Three backends ship today: | Backend | Storage | Across nodes | |---------|---------|:--:| | `InMemoryIdempotentRepository` | Process memory | — | | `SqlIdempotentRepository` | ADO.NET table (any provider), DDL ships with the package | Yes | | `RedbIdempotentRepository` | redb object guarded by a unique key | Yes | The key is settled when the exchange's unit of work ends, before the consumer acknowledges the message or hands it back (Apache Camel's defaults): confirmed on success, removed on failure anywhere in the route, so the redelivery is processed again. Inside `.Transacted()` the key follows the transaction instead: it commits with the work and goes with a rollback. Details in [TRANSACTIONS.md](TRANSACTIONS.md#idempotent-consumer). ```csharp // Register a persistent backend under a name context.AddRedbIdempotentRepository("payments-inbound", ttl: TimeSpan.FromDays(7)); // Use it in any route From("kafka://payments") .Transacted() .IdempotentConsumer(Header("messageId"), "payments-inbound") .Process(/* the work */) .EndIdempotentConsumer() .End(); ``` ### Outbox via Sql polling The classic transactional outbox pattern: the service writes the event as a row of an `outbox` table in the same database transaction as the business write, and a relay route polls the rows and publishes them, marking each one only after the broker has taken it: ```csharp // The relay: one exchange per unsent row; onSuccess marks the row once the send went through. From(Sql.Poll("select id, payload from outbox where sent = false order by id") .DataSource("main") .Delay(1000) .OnSuccess("update outbox set sent = true where id = :#id")) .SetBody(ex => ex.In.Headers["payload"]) .To("kafka://order-events"); ``` A failed send leaves the row unmarked and the next poll sends it again; a crash between the send and `onSuccess` sends it twice, so the receiving side deduplicates. The full recipe, both routes, is in [TRANSACTIONS.md](TRANSACTIONS.md#routes-that-do-not-start-from-a-broker-the-outbox-recipe). --- ## Validation ```csharp // JSON Schema .ValidateJsonSchema(""" { "type": "object", "required": ["orderId", "amount"], "properties": { "orderId": { "type": "string" }, "amount": { "type": "number", "minimum": 0 } } } """) // XSD: the schema's text, one file (its imports have no location to resolve from). A schema's own DOCTYPE is // skipped; a message with a DTD is refused. .ValidateXsd(xsdContent) // XSD from a file, with its xs:import and xs:include read relative to it (UBL, ebMS3, any multi-file schema) .ValidateXsdFile("schemas/ubl/maindoc/UBL-Invoice-2.1.xsd", schemaRoot: "..") // Custom predicate .Validate(e => ((Order)e.In.Body!).Amount > 0, "Amount must be positive") // An expression read as a condition, as Filter and When read one; Method() calls a registry bean .Validate(Expr("header.amount > 0"), "Amount must be positive") .Validate(Method("#rules", "IsAllowed(${header.customer})"), "Customer not allowed") // Task is awaited // FluentValidation and DataAnnotations (redb.Route.Validation.Adapters) .ValidateFluent(new OrderValidator()) .ValidateAnnotations() ``` ### Multi-file XSD schemas `ValidateXsdFile(path, targetNamespace, schemaRoot, throwOnFailure)`, `` and `validator:path.xsd?schemaRoot=…` read the schema from its file, so its imports and includes resolve relative to it. The path goes through the context's resource resolver, as `xslt` does. Imports and includes are read only from under `schemaRoot`: a directory relative to the schema's own, which is the default. UBL keeps `maindoc/` next to `common/`, so `schemaRoot=".."` there. What is refused, when the route is built, with a message naming the reference: - an import or include that is not found, even one the schema does not use; - one outside `schemaRoot`, including an absolute `file:` path; - one on the network (`http://…`, such as `http://www.w3.org/2001/xml.xsd`): copy the file into the package and point `schemaLocation` at it. A DOCTYPE in the schema or in an imported file is skipped, never fetched (W3C's `xmldsig-core-schema.xsd` has one). Once imports load, an `xs:any processContents="lax"` over an imported namespace is validated against its declarations. Inline content, `ValidateXsd(string)` and `ValidateXsd(XmlSchemaSet)` are unchanged. --- ## Testing with Mock The built-in `mock:` endpoint records received messages and lets you assert on them — no external broker needed in unit tests. ```csharp // redb.Route.TestKit: SendBodyAndHeader, Mock public class OrderRouteTests { [Fact] public async Task Route_filters_and_forwards_new_orders() { await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://input") .Filter("header.type == 'new'") .To("mock://received")); await context.Start(); await context.SendBodyAndHeader("direct://input", "payload-1", "type", "new"); await context.SendBodyAndHeader("direct://input", "payload-2", "type", "old"); var mock = context.Mock("mock://received"); Assert.Equal(1, mock.ReceivedCount); Assert.Equal("payload-1", mock.ReceivedExchanges[0].In.Body); } } ``` `MockDsl.Endpoint("name").ExpectedMessageCount(n)` also supports awaiting an expected message count with timeout — useful for asynchronous routes. --- ## Telemetry Built-in OpenTelemetry — distributed traces and metrics out of the box. ```csharp // Per-step tracing and metrics — scope style From("kafka://orders") .Traced("order-processing") .SetBody(JPath("$.order")) .Process(async (e, ct) => await Enrich(e, ct)) .EndTraced() .Metered("order-throughput") .To("rabbitmq://processed") .EndMetered(); // Per-step — inline style From("kafka://orders") .Traced("validate", async (e, ct) => await ValidateOrder(e, ct)) .Metered("transform", e => { e.In.Body = Transform(e); }) .To("rabbitmq://processed"); // Configure via options builder.Services.Configure(o => { o.EnableTelemetry = true; // default: true o.EnableMetrics = true; // default: true }); ``` Metrics exposed: `redb.route.messages.processed`, `redb.route.messages.failed`, `redb.route.processing.duration` — per route and per step. ### Finding a trace by a business key — `SpanTag` `.SpanTag(key, value)` puts one attribute on a span, so a trace can be found by an order number, a batch id, a document key. Jaeger's tag search and Tempo's TraceQL (`{ span.sap.order.id = "A-42" }`) find a trace by an attribute on **any** of its spans, not only the root. The value is a literal or, as in `SetHeader`, an expression evaluated per message; the exchange is not touched: ```csharp From("http://0.0.0.0:8080/sap/ack") .Unmarshal("application/json") .SpanTag("sap.order.id", XPath("/Ack/OrderNo")) // the route span .SpanTag("sap.order.id", Header("orderNo"), SpanTarget.Inbound) // the request's server span .Traced("post-to-erp") .SpanTag("erp.batch", Expr("${property.batch}")) // the enclosing Traced span .To("http://erp/api/orders") .EndTraced(); ``` | Target | Span | Nothing set when | |---|---|---| | `Enclosing` (default) | the nearest `Traced` scope, else the route span | the route has `.Tracing(false)` — never falls back to the transport span | | `Inbound` | the server/consumer span of the transport that received the message; a route called through `direct:` uses its caller's | no transport span (in-process sources), or it has already ended (a wire tap running later) | The host's own span (ASP.NET Core) is never written — it belongs to the host. Nothing is set, and the value is not evaluated, when nobody listens or the span is not sampled; a `null` or empty value sets nothing; a value that fails to evaluate is skipped and logged at Debug — telemetry does not change the outcome of a message. The key is checked when the route is built: lowercase, dot-separated (`sap.order.id`), not in the namespaces of the engine and the semantic conventions (`redb.`, `messaging.`, `http.`, `rpc.`, `db.`, `exception.`, `otel.`), and not a secret's name (`*token*`, `*password*`...). The length of a value is the SDK's limit (`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`). > **The value is exported unfiltered.** Never put personal data or credentials in a span attribute. And do not put a > business key in baggage instead: baggage travels to every next service, a span attribute stays in the trace. --- ## Logging ```csharp // Simple log with template .Log("Processing order: ${header.orderId}") // Log with factory .Log(e => $"Order {e.In.GetHeader("orderId")} body size: {e.In.Body?.ToString()?.Length}") // Structured log scope .Log(LogLevel.Information) .Message("Order processed") .Header("orderId") .Header("status") .ShowRouteId() .EndLog() ``` The log step writes exactly what the route author asks for, including a header or property that holds a secret. The masking by value described under `[Sensitive]` applies to endpoint error and warning texts, not to this step. --- ## Fluent Transport Builders Each transport ships a type-safe fluent builder. Builders implement `implicit operator string` so they can be passed straight to `From()` / `To()`. ### Built-in (no extra package) ```csharp .To(Direct.Endpoint("my-service")) // direct:my-service .To(Seda.Send("orders").ConcurrentConsumers(5).Size(1000)) // seda:orders?... .From(TimerDsl.Every("poll").Period(5000).Delay(1000)) // timer:poll?period=5000&delay=1000 .From(TimerDsl.Once("init")) // fire once .To(LogDsl.Info("audit").ShowHeaders().ShowBody()) // log:audit?... .To(MockDsl.Endpoint("result").ExpectedMessageCount(3)) // mock:result?... ``` A `seda:` queue belongs to its consumer's run. When the consumer stops (`context.Stop()`, a stop of its route), it finishes the exchanges already queued and a send fails with `ChannelClosedException` until the consumer starts again, which opens a new queue: a `Stop()` and `Start()` of the same context leaves every seda hop working. An exchange the stop did not get to within its drain timeout is released with a warning in the log when the consumer starts again. ### Selected transport builders ```csharp // Kafka Kafka.Topic("orders") .Brokers("broker1:9092,broker2:9092") .GroupId("order-svc") .AutoOffsetReset("Earliest") .Sasl("PLAIN", Placeholder("{{kafka.user}}"), Placeholder("{{kafka.password}}")) .Acks("All") .Compression("zstd") // RabbitMQ Rabbit.Queue("orders") .Host("rabbit.local").Port(5672) .Exchange("orders-exchange", "topic") .RoutingKey("order.new") .Durable().PrefetchCount(10) .DeadLetterExchange("dlx") .QueueType("quorum") Rabbit.Exchange("ui-notify", "fanout").Declare() // no queue name: each consumer instance gets its own copy // Redis Redis.Subscribe("events") Redis.XRead("orders-stream").ConsumerGroup("svc").ConsumerName("worker-1") Redis.Set("cache-key").Connection("localhost:6379").Ttl(3600) Redis.LPush("work-queue") // SQL Sql.Poll("SELECT * FROM orders WHERE status = 'new'") .DataSource("main").Delay(5000).OnSuccess("UPDATE orders SET status = 'done'") Sql.Execute("INSERT INTO audit (msg) VALUES (@body)").DataSource("main").Transacted() Sql.Procedure("usp_ProcessOrder").DataSource("main").CommandTimeout(30) // HTTP / HTTPS Http.Post("api.example.com/orders").BearerAuth().Timeout(5000).ContentType("application/json") Http.Listen("/webhooks/stripe").Host("0.0.0.0").Port(8080).Cors().InOut() // gRPC GrpcDsl.Call("localhost:50051") GrpcDsl.Listen("0.0.0.0:50051") // SOAP / WSDL (WS-Security, MTOM, SOAP 1.1/1.2, ?wsdl publishing) Soap.Call("https://gds/air.svc").ConnectionFactory("amadeus").Operation("GetFares") Soap.Listen("/svc/orders").Host("0.0.0.0").Port(4090) // or serve it with a controller: .From(Soap.Listen("/svc/air")…).RedbSoapController() // File system FileDsl.Read("/data/inbox").Include("*.csv").Recursive().ReadLock("Changed").Delete() FileDsl.Write("/data/outbox").AutoCreate(true).TempPrefix(".tmp").FileExist("Override") // SFTP Sftp.Directory("/remote/inbox") .Host("sftp.example.com").Port(22) .Username("user").PrivateKey(Constant("/keys/id_rsa")) .Include("*.xml").Delete() // MQTT 5.0 Mqtt.Subscribe("sensors/+/temperature").Broker("mqtt.local").Port(1883).Qos(1).CleanSession() Mqtt.Publish("alerts/temperature").Broker("mqtt.local").Retain() // AMQP 1.0 AmqpDsl.Address("orders").Host("amqp.local").Port(5672).User("admin").Password("admin") // Email Smtp.Send("smtp.gmail.com").Port(587).Username("user").Password("pass").Security("StartTls") .From("noreply@example.com").To("admin@example.com") Imap.Read("imap.gmail.com").Port(993).Username("user").Password("pass").Security("Ssl") .Folder("INBOX").Unseen().Delete() // TCP TcpDsl.Listen("0.0.0.0:9000").TextLine().Delimiter("\n") TcpDsl.Connect("server:9000").LengthPrefixed().Ssl() // WebSocket Ws.Listen("0.0.0.0:8080/ws") Ws.Connect("ws.example.com:8080/stream") // Quartz Cron.Schedule("daily-report", "0 0 9 * * ?") QTimer.Every("heartbeat").Period(5000) ``` Builders for AzureServiceBus, Elasticsearch, Firebase, FTP, IBM MQ, LDAP, S3, and SignalR follow the same pattern — see the per-package README for each one. --- ## Architecture Routes are compiled in two phases. Define-phase records `RouteStep` instances; compile-phase turns them into a processor chain. This separation enables route introspection, validation, and visualization before execution. ```mermaid flowchart TB subgraph Define["1. Define phase"] RB[RouteBuilder] --> Steps[RouteStep records] end subgraph Compile["2. Compile phase"] Steps --> Compiler[RouteCompiler] Compiler --> Pipeline[PipelineProcessor] end subgraph Run["3. Runtime"] Source[From: Consumer] --> Pipeline Pipeline --> Sink[To: Producer] Pipeline --> Telemetry[OpenTelemetry\nActivities + Meters] end ``` ### Core engine — `redb.Route` | Subsystem | Responsibility | |-----------|----------------| | `Definitions/` | `RouteStep` records, `RouteCompiler`, `PipelineProcessor` | | `Processors/` | 30+ EIP processors: Filter, Choice, Splitter, Aggregator, WireTap, Multicast, RecipientList, DynamicRouter, Resequencer, ScatterGather, ClaimCheck, IdempotentConsumer, Saga, CircuitBreaker, Throttle, Loop, Delay, Debounce, Enrich, Timeout, TryCatch, OnException | | `Expressions/` | `Body`, `Header`, `Property`, `Constant`, `Exchange` plus `JPath`, `XPath`, `StringExpression` (compiled via `System.Linq.Expressions`) | | `Predicates/` | 17 predicate types: `isEqualTo`, `isGreaterThan`, `contains`, `regex`, `In`, `isBetween`, `isNull`, etc. | | `Components/` | Built-in transports: Direct, SEDA, Timer, Mock, Log | | `Telemetry/` | OpenTelemetry `ActivitySource` + `Meter` per route and per step | | `ErrorHandling/` | Retry, `DeadLetterChannel`, `TryCatch`, `OnException` (scope and configure forms) | | `Validation/` | JSON Schema, XSD, predicate validation | | `Serialization/` | JSON, XML marshal / unmarshal | | `Transactions/` | `TransactionScope` integration via `.Transacted()` | | `Fluent/` | Type-safe endpoint builders for all transports | ### Component layers ```mermaid flowchart TB subgraph Core["redb.Route — Core Engine"] Defs[Definitions] Procs["Processors\n30+ EIP"] Expr["Expressions\nCompiled IL"] Pred["Predicates\n17 types"] Built["Built-in components\nDirect · SEDA · Timer · Mock · Log"] Tele[OpenTelemetry] Err[Error Handling] Val[Validation] Ser[Serialization] Tx[TransactionScope] end subgraph Transports["redb.Route.* — 30 transports"] Msg["Messaging\nKafka · RabbitMQ · Redis · AzureSB · IbmMq · Amqp"] Data["Data stores\nSql · Elasticsearch · Firebase · S3 · Ldap"] Net["Network\nHttp · Grpc · WebSocket · SignalR · Tcp"] Files["Files\nFile · Ftp · Sftp"] Proto["Protocols / Schedule\nMail · MqttNet · Quartz · As2 · As4"] AI["AI / Process\nLlm · Mcp · Exec"] Sup["Support\nControllers · GenericFile · Validation.Adapters"] end Core --> Transports ``` ### Transports — underlying clients and capabilities | Transport | Underlying client | Notes | |-----------|-------------------|-------| | `Kafka` | `Confluent.Kafka` | Topics, consumer groups, transactions, SASL, compression | | `RabbitMQ` | `RabbitMQ.Client` 7.x | Queues, exchanges, DLX, quorum queues, prefetch | | `Redis` | `StackExchange.Redis` | Pub/Sub, Streams, KV, Lists, Sorted Sets, Geo | | `AzureServiceBus` | `Azure.Messaging.ServiceBus` | Queues, topics, sessions, scheduled | | `IbmMq` | `IBMMQDotnetClient` | Queues, topics, transactions, RPC, SSL | | `Amqp` | `AMQPNetLite` | AMQP 1.0 — Artemis, Azure SB, Amazon MQ; RPC via `ReplyTo`/`CorrelationId` (InOut auto-detected) | | `Sql` | ADO.NET | Polling, batch execute, stored procedures, transactions | | `Elasticsearch` | `Elastic.Clients.Elasticsearch` 8.x | Search, CRUD, 9 operations | | `Firebase` | Firebase Admin SDK | Firestore, Cloud Storage, FCM | | `S3` | `AWSSDK.S3` | AWS S3 + MinIO, multipart, SSE | | `Ldap` | `Novell.Directory.Ldap` | Search, CRUD, auth | | `Http` | `HttpClient` + Kestrel | REST client, webhooks, CORS, InOut | | `Grpc` | `Grpc.Net` | Client + Kestrel server, binary messages | | `Soap` | `System.Xml` + Kestrel | SOAP 1.1/1.2, WS-Security, MTOM, `?wsdl` | | `WebSocket` | `ClientWebSocket` + Kestrel | Text/binary, reconnect | | `SignalR` | `Microsoft.AspNetCore.SignalR` | Hub consumer + producer/broadcast, each hub path isolated on a shared listener | | `SignalR.StackExchangeRedis` | `Microsoft.AspNetCore.SignalR.StackExchangeRedis` | Redis backplane for the hubs, channels keyed on the hub path | | `Tcp` | `System.Net.Sockets` | Text-line, length-prefixed, TLS | | `File` | File system | Polling, atomic writes, glob, locking | | `Ftp` | `FluentFTP` | FTP/FTPS, passive/active | | `Sftp` | `SSH.NET` | Remote files, key auth, proxy | | `Mail` | `MailKit` | SMTP, IMAP, POP3, IDLE push | | `MqttNet` | `MQTTnet` | MQTT 5.0, shared subscriptions, QoS | | `Quartz` | `Quartz.NET` | Cron schedules, interval timers, persistent jobs | | `Exec` | `System.Diagnostics.Process` | Local-process execution; allowlist, working-directory pin, timeout, output caps | | `Llm` | `HttpClient` (OpenAI-compat + Anthropic Messages) | LLM connector with universal OpenAI-compat provider (14 vendors) and native Anthropic provider; tool-loop agent engine; **token-by-token streaming** (`?stream=true` → `IAsyncEnumerable` surfaced as SSE over `redb.Route.Http` with an `event: done` summary trailer / one `Text` frame per token over `redb.Route.WebSocket`) | | `Mcp` | JSON-RPC 2.0 over stdio / HTTP+SSE | Model Context Protocol client. Spawns external MCP servers, runs `initialize` + `tools/list`, projects every remote tool into `IToolDescriptorRegistry` as `McpToolDescriptor`. Producer-only (`mcp://server/tool`). Cancellation forwarded as `notifications/cancelled`. | ### Saga rollback flow ```mermaid sequenceDiagram participant R as Route participant S1 as Step 1: Reserve participant S2 as Step 2: Charge participant S3 as Step 3: Ship R->>S1: action() S1-->>R: ok R->>S2: action() S2-->>R: ok R->>S3: action() S3--xR: throw Note over R: rollback in reverse R->>S2: compensate() R->>S1: compensate() ``` --- ## DSL Reference Quick reference for `IRouteDefinition` methods. All of them return `IRouteDefinition` for chaining unless noted otherwise. **Transform / Enrich**: `SetBody` (×4: static, lambda, `IExpression`, `StringExpression`), `Transform` (×3: lambda, `IExpression`, string), `SetHeader` (×4), `SetProperty` (×4), `RemoveHeader`, `RemoveProperty`, `RemoveBody`, `Marshal`, `Unmarshal` **Filtering**: `Filter` (×3: lambda, `IPredicate`, string expression) **Processing**: `Process` (×4: async, async + `CancellationToken`, sync, `IProcessor`) **Content-Based Routing**: `Choice()`, `When` (×3: lambda, `IPredicate`, string), `Otherwise()`, `EndChoice()` **Multicast / WireTap**: `Multicast` (simple + full params), `WireTap`, `RecipientList`, `DynamicRouter` **Split / Aggregate**: `Split` (lambda or `IExpression`, scope or sub-route), `EndSplit()`, `Aggregate` **Loop / Delay**: `Loop` (count or predicate, scope or sub-route), `Delay` (`TimeSpan` or lambda), `DelayExpression` **Error Handling**: `DoTry()`, `DoCatch()`, `DoFinally()`, `OnException()`, `EndOnException()`, `Retry`, `DeadLetterChannel`, `ThrowException` (×5) **Redelivery Config**: `MaximumRedeliveries`, `RedeliveryDelay`, `BackOffMultiplier`, `UseExponentialBackOff`, `Handled`, `ExceptionHandled` **Logging**: `Log` (template / lambda / scope), `EndLog()` **Validation**: `Validate`, `ValidateJsonSchema` (×2), `ValidateXsd` (×3), `ValidateXsdFile`, `ValidateFluent`, `ValidateAnnotations` **Lifecycle**: `Transacted`, `RollbackAll`, `Respond`, `SetPattern`, `Stop` **Telemetry**: `Traced` (scope or inline), `EndTraced()`, `Metered` (scope or inline), `EndMetered()` **Advanced EIP**: `Saga`, `IdempotentConsumer`, `Throttle`, `CircuitBreaker`, `Resequence`, `Enrich`, `PollEnrich` **Scope**: `End()` — universal scope closer --- ## XML Route Tools Routes can also be written as XML: [redb.Route.Xml](redb.Route.Xml/README.md) loads `*.route.xml` documents into the same route definitions the C# DSL produces. [XmlDemo](demo/XmlDemo/README.md) is a worked example. Two developer tools ship with it; neither is needed on a server. **`redb-route-xml`**, a .NET tool (package `redb.Route.Xml.CodeGen`, runs on .NET 10 and later): ```bash dotnet tool install -g redb.Route.Xml.CodeGen redb-route-xml xsd bin/Debug/net10.0 --out schema # the schema editors validate against redb-route-xml csharp routes/main.route.xml --namespace My.Routes # the fluent C# the XML parses into redb-route-xml mermaid routes/main.route.xml --bin bin/Debug/net10.0 # a flowchart of the routes redb-route-xml new MyRoutes # scaffold a route project redb-route-xml check . # validate a route project redb-route-xml pack . --version 1.0.0 # package it for a worker ``` `--bin` gives `mermaid` the project's build output: a route that names its own types (``) or package elements (``, ``) needs it, a plain one does not. Schemas and other `file=` references resolve in `csharp`, `mermaid` and `check` alike: under the project's `resources/` first (`file="order.xsd"`), then from the project root (`file="resources/order.xsd"`), as they do in the package. Keep the tool on the same version as the runtime. Whenever it reads a bin directory (`xsd`, `elements`, `catalog`, `check`, `pack`, `mermaid --bin`) it compares its own `redb.Route.Xml` with the one there and refuses to run on a mismatch: a tool of another version would read their types as nothing at all. Upgrade it together with the packages: `dotnet tool update -g redb.Route.Xml.CodeGen --version `. **VS Code extension**: completion, validation and enum hints from the XSD, a route tree in the Explorer and a graph editor over the XML text. Source and details: [vscode-redb-route](vscode-redb-route/README.md). The packaged `.vsix` is attached to the [GitHub release](https://github.com/redbase-app/redb-route/releases) of every version; install it with `Extensions: Install from VSIX...`. --- ## URI Scheme Reference | Scheme | Package | Entry point | |--------|---------|-------------| | `direct:` | redb.Route | `Direct.Endpoint("name")` | | `seda:` | redb.Route | `Seda.Consume("name")` / `Seda.Send("name")` | | `timer:` | redb.Route | `TimerDsl.Every("name")` / `TimerDsl.Once("name")` | | `log:` | redb.Route | `LogDsl.Info("name")`; `level=` takes Trace, Debug, Information, Warning, Error, Critical, None or Camel's TRACE, DEBUG, INFO, WARN, ERROR, OFF, any case | | `mock:` | redb.Route | `MockDsl.Endpoint("name")` | | `direct-vm:` / `vm:` | redb.Route | `direct-vm://name` (synchronous) / `vm://name` (queued): between contexts of one process | | `bean:` | redb.Route | `.Bean(...)` / `bean:#name?method=...` | | `controlbus:` | redb.Route | `controlbus:route?routeId=...&action=restart` | | `validator:` | redb.Route | `validator:order.xsd` | | `xslt:` | redb.Route | `xslt:transform.xsl` | | `kafka:` | redb.Route.Kafka | `Kafka.Topic("name")` | | `rabbitmq:` | redb.Route.RabbitMQ | `Rabbit.Queue("name")` | | `redis:` | redb.Route.Redis | `Redis.Subscribe("ch")` / `Redis.Set("key")` / … | | `sql:` | redb.Route.Sql | `Sql.Poll("query")` / `Sql.Execute("stmt")` / `Sql.Procedure("sp")` | | `http:` / `https:` | redb.Route.Http | `Http.Get("path")` / `Http.Listen("path")` / … | | `as2:` / `as2s:` | redb.Route.As2 | `As2.Receive("path")` / `As2.Send("url")` / `As2.ReceiveMdn("path")` | | `as4:` / `as4s:` | redb.Route.As4 | `As4.Receive(...)` / `As4.Send(...)` | | `grpc:` | redb.Route.Grpc | `GrpcDsl.Call("host:port")` / `GrpcDsl.Listen("host:port")` | | `soap:` / `soaps:` | redb.Route.Soap | `Soap.Call("url")` / `Soap.Listen("path")` | | `file:` | redb.Route.File | `FileDsl.Read("dir")` / `FileDsl.Write("dir")` | | `sftp:` | redb.Route.Sftp | `Sftp.Directory("path")` | | `mqtt:` | redb.Route.MqttNet | `Mqtt.Subscribe("topic")` / `Mqtt.Publish("topic")` | | `amqp:` | redb.Route.Amqp | `AmqpDsl.Address("name")` | | `imap:` / `pop3:` / `smtp:` | redb.Route.Mail | `Smtp.Send("host")` / `Imap.Read("host")` / `Pop3.Read("host")` | | `tcp:` | redb.Route.Tcp | `TcpDsl.Listen("host:port")` / `TcpDsl.Connect("host:port")` | | `ws:` / `wss:` | redb.Route.WebSocket | `Ws.Listen("host:port/path")` / `Ws.Connect("host:port/path")` | | `cron:` / `qtimer:` | redb.Route.Quartz | `Cron.Schedule("name", "expr")` / `QTimer.Every("name")` | | `exec:` | redb.Route.Exec | `ExecDsl.Run()` (producer) / `ExecDsl.Run(...).Schedule("5m")` (scheduled consumer) | | `llm:` | redb.Route.Llm | `Llm.Factory("haiku")` / `Llm.Factory("openai")` / `Llm.Factory("groq")` / … | | `embed:` / `knowledge:` / `stt:` | redb.Route.Llm | `embed://factory` (text to vectors) / `knowledge:` (retrieval) / `stt://factory` (speech to text) | | `mcp:` | redb.Route.Llm.Mcp | `mcp://serverName/toolName` — auto-registered from MCP `tools/list` | | `asb:` | redb.Route.AzureServiceBus | `Asb.Queue("name")` / `Asb.Topic("name", "sub")` | | `elasticsearch:` / `es:` | redb.Route.Elasticsearch | `Es.Index("name")` | | `fstore:` / `fbstorage:` / `fcm:` | redb.Route.Firebase | `Firestore.Collection("name")` / `FirebaseStorage.Bucket("b")` / `Fcm.Token("t")` | | `ftp:` | redb.Route.Ftp | `Ftp.Directory("/path")`, FTPS with `.UseFtps()` | | `wmq:` | redb.Route.IbmMq | `Wmq.Queue("name")` / `Wmq.Topic("name")` | | `ldap:` | redb.Route.Ldap | `LdapDsl.Search("baseDn")`, LDAPS with `.Ssl()` | | `s3:` | redb.Route.S3 | `S3.Bucket("name")` | | `sqs:` / `sns:` | redb.Route.Sqs | `Sqs.Queue("name")` / `Sns.Topic("name")` | | `telegram:` | redb.Route.Telegram | `Tg.Receive(token)` / `Tg.Send(token)` | | `signalr:` | redb.Route.SignalR | `SignalR.Hub("/hub")` | | `cache:` | redb.Route.Cache | `.Cache("key", ttl) … .EndCache()` (scope) / `To("cache:region?action=get&key=…")` | > **Note.** There is no `quartz:` URI scheme by design. Quartz scheduling integrates via the > Worker host (`ConfigureQuartz`) and triggers routes through `cron:` (Cron expressions) or > `qtimer:` (interval timers). A `quartz:` URI would conflate scheduling configuration with > route addressing. --- ## Transport Capability Matrix What each transport can do as a source (`From`) and as a sink (`To`), and which advanced features it supports. | Transport | Consumer (`From`) | Producer (`To`) | Request-Response (InOut) | Transactions | Streaming | Notes | |-----------|:--:|:--:|:--:|:--:|:--:|-------| | Direct | Yes | Yes | Yes | — | — | In-process synchronous | | SEDA | Yes | Yes | — | — | Yes | In-memory bounded queue, multi-consumer | | Timer | Yes | — | — | — | — | Periodic / once-off trigger | | Mock | Yes | Yes | — | — | — | Test-only, records messages | | Log | — | Yes | — | — | — | Sink for logging | | Direct-VM | Yes | Yes | Yes | — | — | In-process synchronous, between contexts of one process | | VM | Yes | Yes | — | — | Yes | In-memory queue, between contexts of one process | | Bean | — | Yes | — | — | — | Calls a method of a registry bean or a DI service | | ControlBus | Yes (`notify`) | Yes | — | — | — | Start / stop / restart routes; `notify` publishes route lifecycle events | | Validator | — | Yes | — | — | — | XSD validation of the body | | Xslt | — | Yes | — | — | — | XSLT transformation of the body | | Cache | — | Yes | — | — | — | `get` / `put` / `remove` / `clear` over `IMemoryCache` / `IDistributedCache` | | Kafka | Yes | Yes | — | Yes | Yes | EOS: transactional producer, `Acks=All`, `IsolationLevel=ReadCommitted`, manual commits | | RabbitMQ | Yes | Yes | Yes | Yes | — | Publisher confirms (`MaxOutstandingConfirms`), `Mandatory` flag, transacted channels, automatic recovery, RPC | | Redis | Yes | Yes | — | — | Yes | Pub/Sub + Streams + KV ops | | AzureServiceBus | Yes | Yes | Yes | Yes | — | Sessions, scheduled, RPC | | IbmMq | Yes | Yes | Yes | Yes | — | Queues + topics + RPC | | Amqp | Yes | Yes | Yes | — | — | AMQP 1.0; RPC via `ReplyTo`/`CorrelationId`, `ExchangePattern.InOut` auto-detected. Connects to Amazon MQ (ActiveMQ/RabbitMQ flavour), Azure Service Bus, Apache Artemis | | Sql | Yes (poll) | Yes | — | Yes | — | Polling source, batch sink, stored procs | | Elasticsearch | — | Yes | — | — | — | Index, search, CRUD | | Firebase | Yes (Firestore) | Yes | — | — | Yes | Firestore, Cloud Storage, FCM | | S3 | Yes (poll) | Yes | — | — | Yes | Multipart upload/download | | SQS | Yes (poll) | Yes | — | Yes | — | Amazon SQS — long-poll, `ConcurrentConsumers(N)`, FIFO, visibility timeout + heartbeat, transacted ack | | SNS | — | Yes | — | — | — | Amazon SNS — topic publish, FIFO, SNS→SQS fan-out | | Telegram | Yes (long-poll) | Yes | — | — | — | Bot API — send/document/photo/edit/delete/answer, 429 `retry_after`, inline/reply keyboards, webhook unpack; at-most-once | | Ldap | — | Yes | — | — | — | Search and CRUD | | As2 | Yes (Listen) | Yes | — | — | — | AS2 (RFC 4130): signed and encrypted S/MIME, MDN receipts sync / async; shares the Kestrel host with `Http` | | As4 | Yes (Listen) | Yes | — | — | — | AS4 (ebMS 3.0, eDelivery profile): signed, compressed and encrypted SOAP 1.2, non-repudiation receipt in the HTTP response; shares the Kestrel host with `Http` | | Http | Yes (Listen) | Yes | Yes | — | Yes | Kestrel server + HttpClient | | Grpc | Yes (Listen) | Yes | Yes | — | Yes | Unary + streaming | | Soap | Yes (Listen) | Yes | Yes | — | — | SOAP 1.1/1.2, WS-Security (UsernameToken, XML-Signature, XML-Encryption), MTOM, `?wsdl`; shares the Kestrel host with `Http` | | WebSocket | Yes | Yes | — | — | Yes | Text/binary frames | | SignalR | Yes (Hub) | Yes | — | — | Yes | Hub server + client broadcast | | Tcp | Yes | Yes | — | — | Yes | Text-line and length-prefixed | | File | Yes (poll) | Yes | — | — | — | Atomic writes, file locking | | Ftp | Yes (poll) | Yes | — | — | — | FTP/FTPS | | Sftp | Yes (poll) | Yes | — | — | — | SSH key auth, proxy | | Mail | Yes (IMAP/POP3) | Yes (SMTP) | — | — | — | IDLE push for IMAP | | MqttNet | Yes | Yes | — | — | Yes | MQTT 5.0, shared subscriptions | | Quartz | Yes | — | — | — | — | Cron / interval triggers | | Exec | Yes (scheduled) | Yes | Yes | — | — | Local processes; `AllowedCommands` allowlist, `WorkingDirectory` pin, `TimeoutMs`, byte caps; primary use as `.AsLlmTool("shell")` | | Llm | — | Yes | Yes | — | Yes | LLM connector — universal OpenAI-compat (14 vendors) + native Anthropic Messages API; tool-loop agent engine; persistent conversation/approval/budget/idempotency stores via `AddRedbLlmStorage()` | | Mcp | — | Yes | — | — | — | MCP-client connector — spawns external MCP servers (stdio + HTTP/SSE), auto-discovers tools via `tools/list` and registers them as `ILlmToolDescriptor`. Cancellation forwarded as `notifications/cancelled`; auto-restart on transport failure | Legend: Yes supported · — not applicable. For transports that support transactions, combine with `.Transacted()` to wrap pipeline steps in a `TransactionScope`. For InOut transports, use `From(...InOut()).Process(...).Respond()` to return a response to the caller. --- ## Packages | Package | NuGet | Description | |---------|-------|-------------| | `redb.Route` | [![NuGet](https://img.shields.io/nuget/v/redb.Route?label=)](https://www.nuget.org/packages/redb.Route) | Core engine: DSL, processors, expressions, telemetry | | `redb.Route.Kafka` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Kafka?label=)](https://www.nuget.org/packages/redb.Route.Kafka) | Apache Kafka (Confluent) | | `redb.Route.RabbitMQ` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.RabbitMQ?label=)](https://www.nuget.org/packages/redb.Route.RabbitMQ) | RabbitMQ (official client 7.x) | | `redb.Route.Redis` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Redis?label=)](https://www.nuget.org/packages/redb.Route.Redis) | Redis (StackExchange) — Pub/Sub, Streams, KV, Lists | | `redb.Route.Sql` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Sql?label=)](https://www.nuget.org/packages/redb.Route.Sql) | SQL databases (ADO.NET) — Poll, Execute, Procedures | | `redb.Route.Http` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Http?label=)](https://www.nuget.org/packages/redb.Route.Http) | HTTP/HTTPS — client and Kestrel server | | `redb.Route.Http.Hosting` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Http.Hosting?label=)](https://www.nuget.org/packages/redb.Route.Http.Hosting) | Shared Kestrel host (`SharedHttpServerManager`) reused by HTTP-based transports | | `redb.Route.As2` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.As2?label=)](https://www.nuget.org/packages/redb.Route.As2) | AS2 (RFC 4130) B2B/EDI — signed/encrypted S/MIME + MDN (sync/async/signed), interop-validated vs OpenAS2 | | `redb.Route.As4` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.As4?label=)](https://www.nuget.org/packages/redb.Route.As4) | AS4 (OASIS ebMS 3.0, eDelivery AS4 profile) B2B — signed, compressed and encrypted SOAP 1.2 with attachments, non-repudiation receipts | | `redb.Route.Grpc` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Grpc?label=)](https://www.nuget.org/packages/redb.Route.Grpc) | gRPC — client and Kestrel server | | `redb.Route.Soap` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Soap?label=)](https://www.nuget.org/packages/redb.Route.Soap) | SOAP 1.1/1.2 — WS-Security, MTOM attachments, WSDL-first services | | `redb.Route.File` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.File?label=)](https://www.nuget.org/packages/redb.Route.File) | File system — polling, atomic writes, locking | | `redb.Route.Sftp` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Sftp?label=)](https://www.nuget.org/packages/redb.Route.Sftp) | SFTP (SSH.NET) | | `redb.Route.MqttNet` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.MqttNet?label=)](https://www.nuget.org/packages/redb.Route.MqttNet) | MQTT 5.0 (MQTTnet) | | `redb.Route.Amqp` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Amqp?label=)](https://www.nuget.org/packages/redb.Route.Amqp) | AMQP 1.0 (Artemis, Azure SB, Amazon MQ) | | `redb.Route.Mail` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Mail?label=)](https://www.nuget.org/packages/redb.Route.Mail) | Email — SMTP, IMAP, POP3 (MailKit) | | `redb.Route.Tcp` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Tcp?label=)](https://www.nuget.org/packages/redb.Route.Tcp) | Raw TCP — text-line, length-prefixed, TLS | | `redb.Route.WebSocket` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.WebSocket?label=)](https://www.nuget.org/packages/redb.Route.WebSocket) | WebSocket — client and Kestrel server | | `redb.Route.Quartz` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Quartz?label=)](https://www.nuget.org/packages/redb.Route.Quartz) | Quartz.NET scheduling (Cron + Timer) | | `redb.Route.Core` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Core?label=)](https://www.nuget.org/packages/redb.Route.Core) | Bridge to [redb](https://github.com/redbase-app/redb) typed object storage — `IRedbService` access, idempotent repository | | `redb.Route.AzureServiceBus` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.AzureServiceBus?label=)](https://www.nuget.org/packages/redb.Route.AzureServiceBus) | Azure Service Bus — queues, topics, sessions | | `redb.Route.Elasticsearch` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Elasticsearch?label=)](https://www.nuget.org/packages/redb.Route.Elasticsearch) | Elasticsearch 8.x — search, CRUD, 9 operations | | `redb.Route.Firebase` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Firebase?label=)](https://www.nuget.org/packages/redb.Route.Firebase) | Firebase — Firestore, Cloud Storage, FCM | | `redb.Route.Ftp` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Ftp?label=)](https://www.nuget.org/packages/redb.Route.Ftp) | FTP/FTPS (FluentFTP) | | `redb.Route.GenericFile` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.GenericFile?label=)](https://www.nuget.org/packages/redb.Route.GenericFile) | Base library for File, FTP, SFTP transports | | `redb.Route.IbmMq` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.IbmMq?label=)](https://www.nuget.org/packages/redb.Route.IbmMq) | IBM MQ — queues, topics, transactions, RPC | | `redb.Route.Ldap` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Ldap?label=)](https://www.nuget.org/packages/redb.Route.Ldap) | LDAP / Active Directory — search, CRUD, auth | | `redb.Route.S3` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.S3?label=)](https://www.nuget.org/packages/redb.Route.S3) | AWS S3 / MinIO — upload, download, multipart | | `redb.Route.Sqs` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Sqs?label=)](https://www.nuget.org/packages/redb.Route.Sqs) | Amazon SQS + SNS — queue consume/produce, FIFO, SNS publish + SNS→SQS | | `redb.Route.Telegram` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Telegram?label=)](https://www.nuget.org/packages/redb.Route.Telegram) | Telegram Bot API — long-poll consumer + send/document/photo/edit/delete/answer producer, 429 handling, inline/reply keyboards, webhook unpack | | `redb.Route.SignalR` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.SignalR?label=)](https://www.nuget.org/packages/redb.Route.SignalR) | SignalR — Hub server and client/broadcast producer | | `redb.Route.SignalR.StackExchangeRedis` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.SignalR.StackExchangeRedis?label=)](https://www.nuget.org/packages/redb.Route.SignalR.StackExchangeRedis) | Redis backplane for the SignalR transport — scales hubs out across replicas | | `redb.Route.Llm` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Llm?label=)](https://www.nuget.org/packages/redb.Route.Llm) | LLM connector — `llm:` URI, fluent DSL, agent loop, universal OpenAI-compatible provider (14 APIs), native Anthropic Messages API provider, `AddRedbLlmStorage()` (5 stores / 9 schemas) | | `redb.Route.Llm.Abstractions` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Llm.Abstractions?label=)](https://www.nuget.org/packages/redb.Route.Llm.Abstractions) | LLM tool-capability contracts — `ILlmToolDescriptor`, `LlmToolCapability`, `RouteToolBridge`, `[ExposeAsLlmTool]`, `.AsLlmTool()` DSL aspect | | `redb.Route.Llm.Tools` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Llm.Tools?label=)](https://www.nuget.org/packages/redb.Route.Llm.Tools) | Utility LLM tools — HttpFetch, JsonPath, XPath, MathEval, RegexExtract, Tavily web search | | `redb.Route.Llm.Mcp` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Llm.Mcp?label=)](https://www.nuget.org/packages/redb.Route.Llm.Mcp) | MCP-client connector — `mcp:` URI, stdio + HTTP/SSE transports, auto-discovery via `tools/list`, cancellation forwarded as `notifications/cancelled`, auto-restart on transport failure | | `redb.Route.Exec` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Exec?label=)](https://www.nuget.org/packages/redb.Route.Exec) | Local-process execution — `exec://run` producer + scheduled consumer, allowlist, working-directory pin, timeout, output caps | | `redb.Route.Controllers` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Controllers?label=)](https://www.nuget.org/packages/redb.Route.Controllers) | Controller dispatch — attribute routing, parameter binding, action filters, InOut | | `redb.Route.Validation.Adapters` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Validation.Adapters?label=)](https://www.nuget.org/packages/redb.Route.Validation.Adapters) | Validation adapters — FluentValidation + DataAnnotations | | `redb.Route.Cache` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Cache?label=)](https://www.nuget.org/packages/redb.Route.Cache) | Caching as an EIP — a `.Cache(key, ttl)` scope and the `cache:` component over `IMemoryCache` / `IDistributedCache` | | `redb.Route.JsonTransform` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.JsonTransform?label=)](https://www.nuget.org/packages/redb.Route.JsonTransform) | Declarative JSON-to-JSON transformation (JSONata) | | `redb.Route.Templates` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Templates?label=)](https://www.nuget.org/packages/redb.Route.Templates) | Payload templates (Scriban) — the PayloadFactory analog | | `redb.Route.Xml` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Xml?label=)](https://www.nuget.org/packages/redb.Route.Xml) | Declarative XML routes — `.route.xml` files load into the same fluent DSL | | `redb.Route.XPath2` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.XPath2?label=)](https://www.nuget.org/packages/redb.Route.XPath2) | XPath 2.0 expressions (regex, sequences, dates, `for`/`some`/`every`) on XPath2.Net | | `redb.Route.DataFormats.Avro` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.DataFormats.Avro?label=)](https://www.nuget.org/packages/redb.Route.DataFormats.Avro) | Apache Avro data format (Chr.Avro) — binary marshal/unmarshal | | `redb.Route.DataFormats.Csv` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.DataFormats.Csv?label=)](https://www.nuget.org/packages/redb.Route.DataFormats.Csv) | CSV data format (CsvHelper) — POCO collections, dictionaries, raw rows | | `redb.Route.DataFormats.Mime` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.DataFormats.Mime?label=)](https://www.nuget.org/packages/redb.Route.DataFormats.Mime) | MIME multipart data format (MimeKit): form fields and files as attachments, `multipart/mixed` the Camel way | | `redb.Route.DataFormats.Protobuf` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.DataFormats.Protobuf?label=)](https://www.nuget.org/packages/redb.Route.DataFormats.Protobuf) | Protocol Buffers data format (Google.Protobuf), optional Confluent Schema Registry | | `redb.Route.DataFormats.Yaml` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.DataFormats.Yaml?label=)](https://www.nuget.org/packages/redb.Route.DataFormats.Yaml) | YAML data format (YamlDotNet) — POCOs and dynamic documents | | `redb.Route.DataFormats.XmlJson` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.DataFormats.XmlJson?label=)](https://www.nuget.org/packages/redb.Route.DataFormats.XmlJson) | XML to JSON and back without a class (Json.NET notation); arrays from the XSD or `arrays=` paths | | `redb.Route.TestKit` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.TestKit?label=)](https://www.nuget.org/packages/redb.Route.TestKit) | Test kit — AdviceWith, mock expectations, NotifyBuilder | | `redb.Route.Xml.CodeGen` | [![NuGet](https://img.shields.io/nuget/v/redb.Route.Xml.CodeGen?label=)](https://www.nuget.org/packages/redb.Route.Xml.CodeGen) | `redb-route-xml` .NET tool — fluent C#, Mermaid diagrams and the XSD from `.route.xml`; not part of the runtime | 52 packages total: core engine + 30 transports (incl. `llm:`, `mcp:` and `as4:`) + the SignalR Redis backplane + 19 support libraries (Core, Controllers, GenericFile, Http.Hosting, Validation.Adapters, Llm.Abstractions, Llm.Tools, Cache, JsonTransform, Templates, Xml, XPath2, the six DataFormats, TestKit), plus the `redb-route-xml` .NET tool. --- ## Running Routes in Production — redb.Tsak Writing routes is one thing; running them in production is another. **[redb.Tsak](https://github.com/redbase-app/redb-tsak)** is the runtime container for redb.Route — a .NET equivalent of [Apache Karaf](https://karaf.apache.org/) / [Camel K](https://camel.apache.org/camel-k/). It hosts route contexts, manages their lifecycle, distributes them across a cluster, schedules jobs, captures metrics and logs, and exposes the lot through a REST API, a CLI and a Blazor dashboard. ```mermaid flowchart TB subgraph Tsak["redb.Tsak runtime"] Worker[Worker / IHostedService] Modules[(ModuleAssemblyLoadContext\nhot-reload)] Ctx[Context Manager\nstart / stop / restart] Cluster[Cluster Coordinator\nleader election + rebalance] Quartz[Quartz Scheduler\nAdoJobStore] Metrics[Metrics + Watchdog\nring-buffer logs] Sec[API Key Auth\nroles + audit] end subgraph Surfaces["Operator surfaces"] REST[REST API\n17 controllers / 75 endpoints] CLI[tsak CLI\n13 top-level / 58 commands] UI[Blazor Dashboard\n11 pages] end subgraph Storage["Persistent state"] Redb[(redb\nPostgres / MSSql)] end Modules --> Worker Worker --> Ctx Worker --> Cluster Worker --> Quartz Worker --> Metrics Worker --> Sec Tsak --> Surfaces Cluster --> Redb Sec --> Redb Quartz --> Redb ``` ### Project layout | Project | Purpose | |---------|---------| | `redb.Tsak.Core` | Controllers, services, security, hot-reload, monitoring | | `redb.Tsak.Worker` | Host (`IHostedService`), DI, Serilog, Quartz schema init | | `redb.Tsak.Core.Pro` | Cluster (leader election, node registry, assignment, cordon), cluster health and metrics | | `redb.Tsak.Contracts` | Wire DTOs (System.Text.Json), shared by Core / Client / Web / CLI | | `redb.Tsak.Client` | Typed HTTP client for the REST API | | `redb.Tsak.CLI` | `tsak` command — System.CommandLine, profiles, watch mode | | `redb.Tsak.Web` | Blazor Server dashboard | | `redb.Tsak.Web.Pro` | PRO web (extended auth) | ### Module loading & hot-reload Tsak distinguishes **two** load locations and they are not interchangeable: | Path | Default | ALC | Loaded when | Purpose | |------|---------|-----|-------------|---------| | `Libs/shared/` | `HotReloadOptions.SharedPath` | **Default** ALC | Boot, before module discovery | Connectors, common DTOs, contracts, native deps — anything that must have **a single type identity** across all modules | | `Libs/modules/` | `Tsak:Modules:AssemblyPaths` | **Isolated** `ModuleAssemblyLoadContext` per package (`pkg:{Name}`) | Boot + on `.tpkg` change | Application route modules, isolated so versions cannot collide | - **Versioning** — `ModuleVersion` format `yyyy.MM.dd.HHmm`; `KeepVersions` previous builds retained for rollback. - **Hot-reload** — `HotReloadService` watches the directories; new DLL → load into fresh ALC → graceful swap → rollback on failure. - **Collectible ALCs** — opt-in (`Collectible=true`); with it on, GC reclaims old versions once nothing outside the module refers to them, and Tsak logs and counts a version that stays. - **Services of a collectible module's beans** — a bean or component built by redb.Route (`bean:`, ``, ``) gets its constructor services from the host's container, except a service closed over one of the module's own types: the host's container would keep that type, and the module with it, for as long as the process lives. For such a type redb.Route builds what the host would answer itself: `ILogger` from the host's `ILoggerFactory`, `IOptions`, `IOptionsSnapshot`, `IOptionsMonitor`, `IOptionsFactory` and `IOptionsMonitorCache` over the type's default instance (nothing in the host configures a module's type), and an empty `IEnumerable`. Any other service over a module's type is absent. Module code that asks the host's container itself (`context.GetServiceProvider()`) for a service over its own type pins the module: take `ILoggerFactory` and call `CreateLogger()` instead. - **`.tpkg` packages** — ZIP archive with `manifest.json` (`Name`, `Version`, `EntryPoints[]`, `Dependencies[]`), module DLLs, and per-module `{ModuleName}.config.json`. Atomic deploy / undeploy. - **`SharedAssemblyLoader`** — scans `Libs/shared/`, loads via `AssemblyLoadContext.Default.LoadFromStream`, registers per-assembly **native library resolvers** (probes native subdirs), tracks file timestamps for change detection, tolerates `FileLoadException` (version conflict logged, not fatal). - **`LoadedAssemblyTracker`** — central registry preventing **type identity split-brain**: same assembly name → single `Assembly` instance across all ALCs. Registers a one-time `Default.Resolving` handler. `LoadOrReuse(name, bytes)` uses `Lazy` for thread-safe one-load-per-name; `Replace` enables hot-reload force-replace (old stays in memory — Default ALC is immutable). When a `.tpkg` is opened, entry points go into the isolated ALC, but companion DLLs go to Default via the Tracker so types match across modules. - No custom `AssemblyDependencyResolver` / `.deps.json` parsing — relies on `Default.Resolving` + standard runtime probing. #### Module manifest (`manifest.json`) ```jsonc { "Name": "OrdersModule", // required "Version": "2026.05.06.1130", // informational "EntryPoints": [ "OrdersModule.dll" ], // loaded into pkg:Orders ALC "Dependencies": [ "SharedContracts" ] // loaded via Tracker into Default } ``` ### Cluster mode (PRO) Enabled by `Tsak:Cluster:Enabled=true`. State is persisted in redb — no extra coordination service (no ZooKeeper, no etcd, no Consul). The cluster forms a tree-based topology: ``` cluster:default (_tsak_clusters) └── group:default (_tsak_groups) └── node:NODE_ID (_tsak_nodes) ``` | Component | Role | |-----------|------| | `RedbLeaderElection` | Distributed lock via redb with TTL expiry + **epoch fencing** (split-brain prevention) | | `RedbNodeRegistry` | Heartbeat tracking, dead node cleanup | | `ClusterCoordinator` | Background loop: heartbeat → leader election → (if leader) detect dead nodes + rebalance assignments | | `AssignmentManager` | Distributes contexts / modules across nodes | | `IContextCustomizer` | Plugin point — cluster mode injects `ClusteredRoutePolicy` to coordinate route ownership | The coordinator starts **before** module discovery to avoid races during boot. Quartz `AdoJobStore` shares scheduled jobs across all nodes — only the elected leader for a job fires it. ### Lifecycle & graceful shutdown ```mermaid stateDiagram-v2 [*] --> Created Created --> Started: Start Started --> Running: routes ready Running --> Stopping: Stop Stopping --> Stopped: drain in-flight Stopped --> Started: Restart Stopped --> [*]: Remove ``` **Hosted-service startup order** (Worker DI): 1. `QuartzSchemaInitializer` — applies Quartz DDL (Postgres/MSSql) idempotently via raw ADO.NET (no redb dependency, avoids bootstrap deadlocks) 2. `QuartzHostedService` — starts the scheduler (RAM or AdoJobStore) 3. `MetricsCollectionService` — periodic process / GC sampling into circular buffer 4. `TsakHostedService` (BackgroundService) — main coordinator: shared assembly loader → module discovery → context start → cluster register 5. `RouteWatchdogService` (BackgroundService) — hung-exchange detector **Shutdown sequence** (`TsakHostedService.StopAsync`): 1. Logs `"Tsak graceful shutdown, stopping all contexts..."` 2. Runs `ITsakLifecycleHook.OnStoppingAsync()` **in reverse order** — last hook to start is first to stop. Cluster deregistration is a hook → leadership released **before** contexts stop. 3. For every context: calls `ITsakContextManager.StopContextAsync()` with a **separate `CancellationToken.None`** — deliberately does *not* propagate the host shutdown token, so one slow context cannot cancel the drain of the others. Each context owns its internal drain timeout for in-flight exchanges. 4. `base.StopAsync()` releases hosted-service resources. 5. Quartz scheduler stops, log sinks flush. Stop / restart REST responses include `DrainTimeMs` and `InflightAfter` — operators see exactly how long the drain took and whether anything was force-killed. SIGTERM handling is delegated to the standard .NET host (`IHostApplicationLifetime`). - **Graceful stop** — each context drains its in-flight exchanges for up to `RedbRoute:ShutdownTimeout` (default 30 s), the contexts one after another; force-stop after the timeout. - **Lifecycle hooks** — `ITsakLifecycleHook` runs before module discovery and after shutdown (reverse-order on stop). - **Lifecycle audit** — `LifecycleAuditService` records every start / stop / error event, queryable via `/api/lifecycle`. - **Watchdog** — `RouteWatchdogService` flags long-running and hung in-flight exchanges; configurable thresholds, optional auto-restart. An exchange the engine holds on purpose (a redelivery delay of `onException`, `Retry` or the dead letter channel, a `delay` step) is not counted while it waits, and is measured from the end of the wait afterwards: the engine marks such waits in the in-flight registry (`IInflightRepository.BeginWait`, `InflightExchange.WaitingUntil` / `LastWaitEndedAt` / `BusySince`). ### REST API — 17 controllers, 75 endpoints The main areas below; the full map is in the [redb.Tsak README](https://github.com/redbase-app/redb-tsak#controllers). | Area | Endpoints | |------|-----------| | **Auth** | `POST /api/auth/keys`, `GET /api/auth/keys`, `DELETE /api/auth/keys/{id}` | | **Modules** | `GET /api/modules`, `GET /api/modules/{name}`, `DELETE /api/modules/{name}` | | **Contexts** | `GET`, `POST start/stop/restart`, `DELETE`, `POST reset-route-states`, `GET endpoints` | | **Routes** | `GET`, `POST start/stop/force-stop`, `GET inflight`, `GET metrics` (per context) | | **System** | `GET /api/system/health`, `/metrics`, `/metrics/history`, `/info` | | **Scheduler** | `GET status/jobs/running`, `POST start/standby/pause/resume` | | **Logs** | `GET /api/logs` (ring buffer), `GET /api/logs/files`, `GET /api/logs/files/{name}` | | **Health probes** | `GET /api/health/startup` + `/live` + `/ready` (Kubernetes-friendly), `GET /api/health/deploy` + `/deploy/cluster` (hot swap or cold deploy) | | **Cluster** (PRO) | `GET /api/cluster status/nodes`, `POST rebalance`, `POST nodes/{id}/cordon` + `/uncordon` | | **Exchanges** | dead-letter queue: list / replay / discard | | **Lifecycle** | `GET /api/lifecycle` (audit events) | | **Dashboard** | `GET /api/dashboard` (summary) | | **Diagnostics** | `GET /api/diagnostics` (full dump, per-route dump) | | **Watchdog** | `GET /api/watchdog status/alerts`, `POST enable/disable` | | **Users** | `GET / POST / PUT / DELETE /api/users` (redb-backed storage) | ### CLI — `tsak` System.CommandLine-based. 13 top-level commands (12 groups and `audit`), 58 commands in all, profile management, three output formats. | Group | Commands | |-------|----------| | `system` | `health`, `metrics`, `info`, `config`, `deploy-advice` | | `context` | `list`, `get`, `start`, `stop`, `restart`, `remove` | | `route` | `list`, `get`, `start`, `stop`, `force-stop`, `inflight` | | `module` | `list`, `get`, `remove`, `keygen`, `sign`, `deploy`, `validate`, `rollback` | | `scheduler` | `status`, `jobs`, `running`, `start`, `standby`, `pause`, `resume`, `fire` | | `cluster` | `status`, `nodes`, `rebalance`, `cordon`, `uncordon` | | `log` | `get` (with `--limit`, `--level`) | | `dlq` | `list`, `replay`, `discard` | | `audit` | the persisted admin-action trail | | `auth` | `list`, `create`, `revoke` | | `watchdog` | `status`, `alerts`, `enable`, `disable` | | `diagnostics` | `lifecycle`, `dump`, `route`, `dashboard` | | `profile` | `list`, `add`, `remove`, `use` (local — no API call) | Global options: `--profile/-p`, `--url/-u`, `--key/-k`, `--output table|json|quiet`, `--watch` + `--interval` (live polling), `--yes/-y` (skip confirmations), `--no-color`, `--timeout`. Profiles persist in `~/.tsak/profiles.json`; environment variables `TSAK_URL` / `TSAK_KEY` override. ```bash # Switch profile, watch routes live tsak profile use prod tsak route list orders --watch --interval 2 # Cluster ops tsak cluster status tsak cluster rebalance --yes # Hot-deploy a module via REST + scheduler ops tsak module list -o json tsak scheduler jobs tsak scheduler pause orders.daily-report ``` ### Web UI — Blazor Server dashboard | Page | Route | Purpose | |------|-------|---------| | **Dashboard** | `/` | Overview: contexts, routes, metrics, alerts | | **Cluster** | `/cluster` | Topology, leader, node registry, heartbeats | | **Node detail** | `/node/{id}` | Per-node tabs: contexts, modules, health | | **Routes** | `/node/{id}/routes` | Per-context route list, status, inflight | | **Route view** | `/node/{id}/routes/{ctx}/{routeId}` | Processors, metrics, in-flight exchanges | | **Endpoints** | `/node/{id}/endpoints` | HTTP endpoints, from/to per route | | **Logs** | `/node/{id}/logs` | Ring-buffer log viewer with level filters | | **Watchdog** | `/node/{id}/watchdog` | Active alerts, hung exchanges | | **Auth** | `/auth` | API key management (create / revoke) | | **Login** (PRO) | `/login` | Authentication page | Chart.js for metrics, table components, periodic refresh (SignalR-ready for push). ### Quartz scheduler | Mode | Job store | Use | |------|-----------|-----| | Standalone | `RAMJobStore` (in-memory) | dev, single-node without DB | | Single-node + redb / Cluster | `JobStoreTX` (`AdoJobStore`) | jobs survive restart and are shared across cluster | `QuartzSchemaInitializer` is an `IHostedService` that runs **before** the Quartz scheduler — it applies embedded DDL for Postgres and MSSql idempotently (raw ADO.NET, no redb dependency to avoid bootstrap deadlocks). Each `IRouteContext` receives an `IScheduler` via DI; the Quartz transport (`cron:` / `qtimer:`) is the front door for triggers. ### Authentication & security - **API keys** — `Authorization: Bearer tsak_XXX` or `X-Api-Key: tsak_XXX`. - **HMAC-SHA256** validation with constant-time comparison (timing-attack safe). - **Roles** — comma-separated, enforced by `AuthorizeProcessor`. - **Expiry + revocation** — keys can have `ExpiresAt`; revoke is immediate, cache (5-min TTL) is invalidated. - **User linkage** — if `IUserProvider` is registered, keys link to Users and inherit `Disabled` flag. - **Storage** — `ConfigApiKeyStore` (appsettings, dev) or `RedbApiKeyStore` (RTTI storage, cluster-replicated). - **Audit** — every create / revoke / validate event is logged (`LogAdminAuditService`); `[AuditAdminAction]` attribute marks audit-worthy endpoints. ### Observability #### OpenTelemetry & Prometheus First-class OTel integration via NuGet packages: - `OpenTelemetry.Extensions.Hosting` - `OpenTelemetry.Exporter.Prometheus.HttpListener` - `OpenTelemetry.Instrumentation.Process` - `OpenTelemetry.Instrumentation.Runtime` When `Tsak:Metrics:Prometheus:Enabled=true`, Tsak calls `.AddOpenTelemetry().WithMetrics(b => b.AddPrometheusHttpListener(...))` and exposes a Prometheus-format endpoint on **`http://*:9464/`** (port configurable via `Tsak:Metrics:Prometheus:Port`). The OTel pipeline registers the redb.Route `ActivitySource` (`RouteActivitySource.SourceName`) so any tracing emitted by route processors is collected automatically — point an OTLP collector / Jaeger / Tempo at the activity source, or scrape `:9464/metrics` from Prometheus. ```jsonc "Tsak": { "Metrics": { "Prometheus": { "Enabled": true, "Port": 9464 } } } ``` #### Health probes — Kubernetes-ready | Endpoint | Probe type | Returns 200 when | |----------|-----------|------------------| | `GET /api/system/health/startup` | startup | process is up | | `GET /api/system/health/live` | liveness | process is not deadlocked | | `GET /api/system/health/ready` | **readiness** | contexts are running **and** healthy (stricter than liveness) | `HealthCheckService` aggregates probes (worst status wins: Unhealthy > Degraded > Healthy) and never throws — exceptions inside a probe become Unhealthy. Modules can contribute custom probes by implementing `IModuleHealthContributor`. PRO ships `ClusterHealthContributor` which reports leader / member health. #### Metrics & logs - **Process metrics** — CPU, working set, threads, GC Gen0/1/2, total memory; circular buffer with configurable history (default 24h). - **Per-context metrics** — messages processed, errors, throughput. - **Log capture** — Serilog `RingBufferSink` (in-memory circular buffer, size via `Tsak:Logs:BufferSize`, default 2000) plus optional file/console sinks declared in `appsettings.json`. `MemoryUsageEnricher` annotates every log event with a `MemoryUsage` field (KB). - **Lifecycle audit** — every context / route start / stop / error queryable via `/api/lifecycle`. - **Admin audit** — `[AuditAdminAction]` endpoints emit structured WRN logs by default; PRO can swap the sink for a redb-backed store. ### Deployment modes | Mode | State store | Quartz | API keys | Cluster | |------|-------------|--------|----------|---------| | **Standalone** | `InMemoryTsakStateStore` | `RAMJobStore` | `ConfigApiKeyStore` (appsettings) | off | | **Single-node + redb** | `RedbTsakStateStore` (Postgres / MSSql) | `AdoJobStore` | `RedbApiKeyStore` (RTTI storage) | off | | **Cluster** | `RedbTsakStateStore` shared | `AdoJobStore` shared | `RedbApiKeyStore` shared | `RedbLeaderElection` + `RedbNodeRegistry` | Minimal config: ```jsonc { "Tsak": { "Redb": { "Provider": "postgres", "ConnectionString": "..." }, "Modules": { "AssemblyPaths": [ "Libs/modules", "Libs/shared" ] }, "HotReload": { "Collectible": false, // true to enable GC reclaim of old versions "KeepVersions": 3 }, "Cluster": { "Enabled": true, "ClusterName": "default", "GroupName": "default", "NodeId": null, // null = auto-generate / pick from ENV "HeartbeatIntervalSeconds": 5, "LeaderLockTtlSeconds": 10 } }, "Quartz": { "quartz.jobStore.type": "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" } } ``` ### Kubernetes deployment Tsak ships a ready `Dockerfile` (multi-stage, `mcr.microsoft.com/dotnet/runtime:9.0`, EXPOSE 9090) and is designed from the ground up for container deployment. #### K8s probes Health endpoints are **auth-exempt** by default (`Tsak:Api:AuthExempt`): ```yaml startupProbe: httpGet: { path: /api/system/health/startup, port: 9090 } failureThreshold: 30 periodSeconds: 4 # up to 120s to boot livenessProbe: httpGet: { path: /api/system/health/live, port: 9090 } periodSeconds: 10 failureThreshold: 3 # 30s before pod restart readinessProbe: httpGet: { path: /api/system/health/ready, port: 9090 } periodSeconds: 5 failureThreshold: 2 # 10s before removal from lb ``` **Liveness** does not check module health — that avoids a restart loop during rolling updates. **Readiness** is stricter: Degraded status → pod removed from service endpoints (no restart), allowing the cluster to rebalance. #### Graceful termination K8s sends SIGTERM and then SIGKILL after `terminationGracePeriodSeconds`. Tsak drains its contexts one after another, each for up to `RedbRoute:ShutdownTimeout` (default `00:00:30`; the `_system` context keeps the 30 s default), so the grace period must exceed cluster deregistration plus one `ShutdownTimeout` per module context plus 30 s. The shutdown sequence: ``` SIGTERM → cluster deregister (hook, reverse-order) → context drain (one context at a time, each up to its ShutdownTimeout) → Quartz shutdown → log flush ``` #### Pod identity in cluster mode When running as a StatefulSet or with a headless service, inject pod metadata via the downward API: ```yaml env: - name: POD_NAME valueFrom: { fieldRef: { fieldPath: metadata.name } } - name: POD_NAMESPACE valueFrom: { fieldRef: { fieldPath: metadata.namespace } } - name: POD_IP valueFrom: { fieldRef: { fieldPath: status.podIP } } - name: Tsak__Cluster__NodeId valueFrom: { fieldRef: { fieldPath: metadata.name } } ``` Tsak uses `Tsak:Cluster:NodeId` as its cluster identity. Mapping it to `metadata.name` gives stable, predictable node IDs across pod restarts (important for assignment rebalancing). #### Prometheus scraping ```yaml annotations: prometheus.io/scrape: "true" prometheus.io/port: "9090" prometheus.io/path: "/metrics" ``` Set `Tsak:Metrics:Prometheus:Enabled=true` to serve `/metrics` on the Tsak API port (`Tsak:Api:Port`, default 9090). The OTel Prometheus exporter listens on `localhost` only, at `Tsak:Metrics:Prometheus:Port` (default 9464), and the API's `/metrics` route proxies it, so 9464 is never exposed. `/metrics` needs no API key unless `Tsak:Metrics:Prometheus:RequireAuth=true`. #### Pluggable cluster backends All cluster coordination is behind **abstract interfaces** (`ILeaderElection`, `IDistributedLock`, `INodeRegistry`, `IClusterCoordinator`, `IClusterBootstrap`, `IAssignmentManager`) in `redb.Tsak.Core.Pro`. The shipped implementations use redb (Postgres / MSSql): `RedbLeaderElection`, `RedbDistributedLock`, `RedbNodeRegistry`, `RedbAssignmentManager`, with the assignment strategies `round-robin` and `least-loaded`. These are interfaces you can implement: `AddTsakCluster()` registers the redb ones, so register your own implementation after that call; the last registration of a service wins. ### Why redb.Tsak (vs Apache Karaf / Camel K) - **No JVM, no OSGi.** Pure .NET 10/11 with native `AssemblyLoadContext` isolation instead of OSGi bundles. - **Cluster without external coordination.** Leader election + node registry persisted in your existing redb (Postgres / MSSql). No ZooKeeper, no etcd, no Consul. - **Built-in Blazor dashboard.** Full management UI ships with the runtime — Karaf needs Hawtio, Camel K needs Kamel CLI + external dashboards. - **CLI + REST + Web symmetric.** Same DTOs (`redb.Tsak.Contracts`) across all three surfaces; the CLI is just a thin client over the API. - **Type-identity safe module loading.** `LoadedAssemblyTracker` prevents the classic OSGi-style “two versions of the same type” bugs without forcing manifest gymnastics on module authors. - **OpenTelemetry + Prometheus out of the box.** `:9464/metrics` Prometheus endpoint, OTel `ActivitySource` registered for redb.Route — plug a collector / Jaeger / Tempo straight in. - **Kubernetes-native probes.** Distinct startup / liveness / readiness endpoints under `/api/system/health/*`. - **Idempotent schema init.** Quartz tables and redb schemas are bootstrapped on startup — no manual DDL step. - **Hot-reload with rollback.** Atomic `.tpkg` packages, version retention, automatic rollback on failure. - **Deterministic shutdown ordering.** Hooks fire in reverse order; per-context drain isolated by `CancellationToken.None` so one slow context cannot abort the rest. For a deeper feature reference and deployment recipes, see the [redb.Tsak repository](https://github.com/redbase-app/redb-tsak) — its `README.md`, `API_GUIDE.md` and `DEPLOYMENT.md` cover the runtime container end to end. --- ## Upgrading What changes from one version to the next, and what to do about it: [UPGRADING.md](UPGRADING.md) for the steps a breaking change needs, [CHANGELOG.md](CHANGELOG.md) for every release. --- ## Contributing Contributions are welcome. Areas where help is most valuable: - Bug reports with minimal reproductions - Documentation improvements - New transport connectors - Examples and tutorials --- ## License Apache License 2.0 — see [LICENSE](LICENSE). Part of the [RedBase](https://github.com/redbase-app) ecosystem. Path: redb-route/SECURITY.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/SECURITY.md ---- # Security Policy ## Supported Versions | Version | Supported | |---------|-----------| | 1.0.x (preview) | :white_check_mark: | ## Reporting a Vulnerability If you discover a security vulnerability in redb.Route or any of its transport packages, please report it responsibly: 1. **Do NOT** open a public GitHub issue 2. Email: **support@redbase.app** 3. Include: - Affected package(s) and version - Description of the vulnerability - Steps to reproduce or proof-of-concept code - Potential impact assessment We will acknowledge receipt within 48 hours and provide a timeline for a fix. ## Scope This policy applies to all packages in the redb.Route family: - `redb.Route` (core engine) - `redb.Route.Kafka`, `redb.Route.RabbitMQ`, `redb.Route.Redis` - `redb.Route.Http`, `redb.Route.Grpc`, `redb.Route.Tcp`, `redb.Route.WebSocket` - `redb.Route.Sql`, `redb.Route.File`, `redb.Route.Sftp`, `redb.Route.Ftp` - `redb.Route.MqttNet`, `redb.Route.Amqp`, `redb.Route.AzureServiceBus` - `redb.Route.Kafka`, `redb.Route.IbmMq`, `redb.Route.Ldap` - `redb.Route.Mail`, `redb.Route.S3`, `redb.Route.Elasticsearch` - `redb.Route.Firebase`, `redb.Route.SignalR` - `redb.Route.Controllers`, `redb.Route.Core`, `redb.Route.Validation.Adapters` ## Security Notes for Users ### Credentials in route definitions Route endpoint URIs and fluent builder options frequently contain credentials (passwords, API keys, connection strings). **Never hardcode credentials** in source code. Use: ```csharp // Good — read from configuration var brokerPass = configuration["Kafka:Password"]; From(Kafka.Topic("orders") .Brokers(configuration["Kafka:Brokers"]) .Sasl("PLAIN", configuration["Kafka:User"], configuration["Kafka:Password"])) .To("direct://process"); ``` The same rule holds for every transport: keep credentials in configuration or a secret store and pass them through the typed builder — never inline them into an endpoint URI. Since 3.4.0 a credential that does reach a URI is redacted everywhere it would otherwise surface (logs, telemetry tags, health metadata, the Tsak dashboard) — see the Security section of `CHANGELOG.md`. ### TLS / certificate validation All transports that support TLS (HTTP, gRPC, TCP, SFTP, SMTP, MQTT, AMQP, IBM MQ, LDAPS) default to validating server certificates. Do not disable certificate validation in production: ```csharp // DANGEROUS — never in production Smtp.Send("smtp.example.com") .TrustAllCertificates() // only for local dev/testing ``` ### Expression injection The `Expr("${...}")` string expression engine evaluates header and property values at runtime. Avoid constructing expressions from untrusted external input, as this could expose internal message state. ### Input validation Use `.Validate()`, `.ValidateJsonSchema()`, or `.ValidateFluent()` on consumer routes that accept data from external systems (webhooks, queues, TCP) to reject malformed or malicious payloads early. Path: redb-route/TRANSACTIONS.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/TRANSACTIONS.md ---- # Transactions: committing the database, the messages and the dedup key together A route usually does three things at once: it writes to a database, it sends messages onward, and it remembers that it already handled this delivery. This guide is about making those agree — and about what happens when they cannot. ## TL;DR - There is **one** primitive: `.Transacted()` (alias `.Transaction()`). - Inside it, every piece of `redb` work shares **one connection per (transaction, database)** and commits or rolls back with the block. - A unit of work ends in one order: **database, then the deferred sends, then the acknowledgement**. - A broker send inside the block **joins it by default** and leaves after the commit. `transacted=false` on the endpoint sends at once, outside the transaction. - `.Retry(n)` wraps the transaction. One attempt is one unit of work. - Put `.IdempotentConsumer(...)` **inside** `.Transacted()` so the dedup key commits with the work. - Put the outgoing `.To(broker)` **after** `.EndIdempotentConsumer()`: the key guards the work, not the announcement. - Keep a transacted route to **one database**, and do not run parallel branches inside a transaction. ## The model `.Transacted()` opens a `System.Transactions.TransactionScope` around the enclosed steps. Under that scope the core hands every piece of `redb` work — `SaveAsync`, `redb.Context`, stores that open their own DI scope, the key generator — the **same** connection for a given database. The work commits together when the block completes, and any failure before completion rolls all of it back. ```csharp From("sftp://inbound/orders") .Transacted() .Unmarshal() .ProcessWithRedb(async (redb, ex, ct) => await redb.SaveAsync((Order)ex.In.Body!, ct)) .To("kafka://orders.created") .End(); ``` - **SQL Server and PostgreSQL** enter the transaction when the connection opens. - **SQLite** issues `BEGIN IMMEDIATE` and holds the write lock for the whole block. - Two commands at once on the transaction's connection are refused, and so is a command issued after the transaction ended. Both say why. ## One route, end to end ```csharp From("rabbitmq://orders?queue=orders.in&transacted=true") .Transacted() // one transaction per attempt .Retry(3, TimeSpan.FromSeconds(2)) // wraps the transaction, does not live inside it .DeadLetterChannel("rabbitmq://orders?exchange=orders.dlq") .IdempotentConsumer(Header("messageId"), "orders-inbound") .Unmarshal() .ProcessWithRedb(async (redb, ex, ct) => { var order = (Order)ex.In.Body!; await redb.SaveAsync(order, ct); // Raw SQL that must commit with the redb work goes through redb.Context — the transaction's // own connection. A `sql:` step here would be a second connection; see "One database" below. await redb.Context.ExecuteAsync( "update orders_flat set state = $1 where id = $2", ["processed", order.Id], ct); }) .EndIdempotentConsumer() .To("kafka://orders.created") // after the dedup block; deferred until the commit .End() .Log("done: ${messageHistory('compact')}"); ``` What happens to one message: 1. **The consumer takes the delivery and leaves it unsettled.** Acknowledging is its job, and it comes last. 2. **The attempt opens its transaction.** The dedup key, the redb object and the raw SQL all run on one connection inside it, because they address the same database. 3. **`To("kafka://…")` publishes nothing yet.** It registers a deferred action on the exchange. 4. **The attempt succeeds:** the database transaction completes and closes, then the Kafka message goes out, then the consumer acknowledges the delivery. In that order. 5. **The attempt fails:** the database rolls back, the dedup key with it, so the redelivery is processed rather than skipped; the deferred Kafka message is discarded and the action set is emptied. `Retry` waits two seconds and opens a **new** transaction. Nothing is held open during the wait. 6. **All three attempts failed:** the exchange goes to the dead-letter channel, and the delivery is still not acknowledged, so the broker redelivers it by its own rules. 7. **Kafka fails after the database committed:** the database cannot be taken back. The failure is logged as exactly that and propagates, and the delivery stays unacknowledged. On the redelivery the dedup key, now committed, skips the block with the work, while the send stands after the block and goes out. The work is done once and the message is not lost. ### Announce after the dedup block In the example the `.To("kafka://…")` stands **after** `.EndIdempotentConsumer()`, not inside it, and that is the difference between losing a message and not. The idempotent consumer skips a duplicate whole: its block does not run, and the route goes on with the step after the block. The one window the database-first order leaves open is "the work is stored, the message did not go out". The broker delivers the message again, and the dedup key recognises it. | Where the send stands | The redelivery after a failed send | |---|---| | Inside the dedup block | The block is skipped whole, the send with it. The work is in the database and the message never goes out. | | After the block, inside `.Transacted()` | The block is skipped and the work is not repeated. The send runs and goes out after the commit. | The rule: **the dedup key guards the work, not the announcement of it.** The work under the key happens exactly once; the announcement goes out at least once, so the receiver handles a repeated message like any at-least-once consumer does. ### The same route without redb: `sql:` as the database work A `sql:` step opens its own connection, and under `.Transacted()` that connection **joins the ambient transaction** instead of starting one of its own. So a route whose database work is plain SQL is transacted the same way — just keep it to one data source and do not mix it with `redb` against the same database (see [One database per transacted route](#one-database-per-transacted-route)). ```csharp From("rabbitmq://orders?queue=orders.in&transacted=true") .Transacted() .Retry(3, TimeSpan.FromSeconds(2)) .DeadLetterChannel("rabbitmq://orders?exchange=orders.dlq") .Unmarshal() .To("sql:insert into orders (id, state) values (:#id, 'new');" + " update orders_flat set state = 'processed' where id = :#id" + "?dataSource=#main" + "¶m.id=${body.Id}") .To("kafka://orders.created") // joins the transaction: leaves after the commit .End(); ``` The statement runs inside the route's transaction, the Kafka message leaves only after that transaction committed, and the delivery is acknowledged after the message went out. A failure anywhere rolls the statement back and publishes nothing. Several `sql:` steps in one block are fine when they use the **same data source**: each step opens a connection, runs its statement and closes the connection before the next step, and PostgreSQL's and SQL Server's drivers hand the next step the same enlisted connection, so the transaction stays local and the steps commit or roll back together (measured on both). What the one-database rule forbids is a second connection **while another is open** in one transaction: a `sql:` step next to `redb` work against the same database (below); a `StreamList` reader (refused inside a transaction); parallel branches (see [Parallelism](#parallelism)); or two data sources. Several statements can also go in one step, as above, or through the connector's batch mode. ## The order things commit in 1. **The database transaction completes and closes.** Everything `redb` and raw SQL did on the block's connection is durable. 2. **The deferred sends go out.** Every `.To(broker)` inside the block published nothing until now; the messages leave only once the work they announce is stored. 3. **The consumer acknowledges the incoming message.** Last, and only if the two steps above went through. The reason is the service on the other side: a message tells it something happened, and it then reads the work by id. Announcing first would let it look up rows that do not exist yet, or never will. Committing first leaves the opposite window, work stored but not yet announced, which the broker closes by redelivering and an [idempotent consumer](#idempotent-consumer) keeps from being done twice. A send that fails after the database committed is logged for what it is and propagates, so the message is never acknowledged and the broker delivers it again. ### Several sends in one block The deferred sends leave in the order the route made them. Where the broker has a transaction of its own, the sends of one producer in a block are committed in it, so they arrive together or not at all: | Broker | The sends of one producer in a block | |---|---| | IBM MQ | one unit of work: every put under syncpoint, one `MQCMIT`; a failed put backs them all out | | RabbitMQ | one channel transaction on a channel of the producer's own: the publishes, then one `tx.commit` | | Kafka with `transactionalIdPrefix` | one Kafka transaction: the produces, the consumed offset when the route started from Kafka on the same cluster, then one commit; any failure aborts it | | AMQP 1.0 with `localTransactions` | one AMQP local transaction: declare, the sends, one discharge; a send that cannot complete discharges it as failed. The broker must support it (Artemis, Qpid, Azure Service Bus) | | Azure Service Bus with `batchCommit` | one Service Bus batch, taken whole or not at all; a block whose messages do not fit in one batch sends nothing | | Kafka, AMQP 1.0, Azure Service Bus without these options; SQS, SNS, Redis | one after another, in order; a failure part-way leaves the earlier ones sent | - Atomic means **per producer**, that is per connection. Sends through two producers, or to two brokers, are committed one after the other: making them one would take a distributed transaction (XA), which the route does not use. - A producer's batches take turns on its connection, because a broker transaction belongs to the connection. On RabbitMQ a channel transaction is also markedly slower than publisher confirms; that is the price of the guarantee. - Where the earlier sends of a failed commit stay sent, the message is not acknowledged and comes back, so they go out again: the receiving side deduplicates them, as it does for any at-least-once delivery. - A Kafka transaction that carries the consumed offset makes a Kafka-to-Kafka route exactly-once within Kafka: the output and the offset move together, and the consumer does not commit the offset itself. The database still commits before it, not with it. See the Kafka connector's README. ## Which steps join the transaction The rule is Camel's: inside a transacted route, a send through a transactional endpoint is part of the unit of work. The endpoint's `transacted` parameter only states an exception to that rule. | Step inside `.Transacted()` | `transacted` unset | `transacted=false` | `transacted=true` | |---|---|---|---| | RabbitMQ, AMQP 1.0, Kafka, IBM MQ, Azure Service Bus, SQS, SNS producer | leaves after the commit | leaves at once | leaves after the commit | | Redis `PUBLISH`, `XADD` | leaves after the commit | leaves at once | leaves after the commit | | Other Redis writes (`SET`, `INCR`, lists, hashes, sets) | runs at once | runs at once | runs after the commit | | Request-reply (`replyTo=true`) | leaves at once | leaves at once | refused when the route starts | | `sql:`, `redb` | part of the database transaction | | | - **Outside a block** everything runs at once, and `transacted=true` fails the step: nothing would ever commit the send, and failing is better than losing it. - **Leaving at once** is for a message that must go out even if the work rolls back: an alert, a trace. It goes out before the database commits and is not taken back, so the next service must not act on it as on a done piece of work. For a copy that should not even share the exchange, use `.WireTap(...)`. - **Request-reply** always leaves at once: a request held back until the commit would wait for a reply that cannot come before it. - **Redis** is a store first. A `SET`, an `INCR` or a `SETNX` lock exists for its effect and its result right now, so only an explicit `transacted=true` holds it back, and then the route does not get its result. `PUBLISH` and `XADD` announce work like a broker does and follow the block; the entry id and the recipient count reach the exchange headers after the commit. Reads and pops (`GET`, `LPOP` and the like) refuse `transacted=true` when the route starts. - **HTTP, mail, files, MQTT, WebSocket** and the other non-transactional endpoints run at once wherever they stand. To announce through them only after the commit, put the step after `.End()`. The AMQP 1.0 and Azure Service Bus clients enlist a send in the ambient `System.Transactions` transaction by themselves. redb.Route never lets them: a send that leaves at once runs with the ambient transaction suppressed, and a deferred one runs after the transaction closed. A broker therefore never becomes a second resource next to the database, which would escalate the transaction to a distributed one. ## Blocks inside blocks Nesting follows the transaction policy, as propagation does in Camel and Spring: - **`Required`** (the default) or **`Mandatory`** inside a running block **joins** it. The inner block commits nothing of its own: its database work joins the outer transaction, its sends wait for the outer commit, and a failure in it marks the whole unit of work for rollback. - **`RequiresNew`** or **`Suppress`** is a unit of work **of its own**. When it ends, its own database work and its own sends are settled; the outer block's sends stay with the outer block. A failure inside it rolls back only its own work, and the outer block decides what to do with the exception. `.BeginTransaction()` ... `.CommitTransaction()` / `.RollbackTransaction()` follows the same rules and commits in the same order, the database first and the sends after it. Inside an enclosing `.Transacted()` a `Required` imperative block joins it and leaves the commit to it. An **asynchronous hand-off** ends the block's reach, as in Camel, where a transaction belongs to the thread that opened it. The exchange that `seda:`, `vm:` or an InOnly `.Threads()` passes on is a unit of work of its own: sends on the other side are not part of the sending block. The same holds for a copy that outlives its block, such as an exchange an aggregator or a resequencer releases later: it sees no block, so an unset `transacted` sends at once and `transacted=true` fails instead of waiting for a commit that already happened. ## What counts as a failure The transaction ends the way the **exchange** ends, not the way the last step returned: | Exchange after the body | Transaction | Broker consumer | |---|---|---| | Completed, or `OnException` with `Handled(true)` | commit | ack, offset commit | | A step threw | rollback | nack, release, no commit | | `OnException` **without** `Handled(true)`: the exception stays on the exchange and the route returns normally, also from a sub-route called through `direct://` | rollback | nack, release, no commit | `Handled(true)` means "this exchange is done, the failure is consumed". Without it the failure travels through the transaction and out of the consumer exactly as a thrown one would. `.RollbackAll()` is Camel's `markRollbackOnly()`: a rollback **without** an exception. The route stops at that step, the transaction rolls back the database and the deferred sends, and the transaction logs no error. The consumer handles the message as a failed delivery and does not acknowledge it: the broker delivers it again (Kafka follows its `breakOnFirstError` setting, a file consumer takes its failure path, `moveFailed`). `Retry` does not repeat the attempt, because nothing failed. Use it when the route decides the work must not stand, for example after a validation step that finds the message not yet processable. A **streamed reply** is read after the transaction: an HTTP, WebSocket or gRPC consumer writes a streamed body (a `sql:` `StreamList`, say) to the caller once the route, and so `.Transacted()`, has finished and committed. A failure while the stream is written goes past `OnException` and cannot roll the committed work back; the caller sees a broken response. It is the same in Camel. When the reply must be all-or-nothing with the work, materialize it inside the block instead of streaming it. ## `Retry` wraps the transaction ```csharp .Transacted() .Retry(3, TimeSpan.FromSeconds(1)) .ProcessWithRedb(...) // its own transaction, its own deferred sends .To("kafka://orders") .End() ``` - A failed attempt rolls back its own database work **and** its own deferred sends, so the attempt that finally succeeds publishes only its own messages. - No transaction is held open across the retry delays, so a retrying route does not hold database locks for the whole sequence. ## Who acknowledges the incoming message The consumer does, never the transaction. RabbitMQ, AMQP 1.0, Kafka, IBM MQ, Redis Streams, Azure Service Bus and SQS settle a delivery after the whole unit of work succeeded, and leave it unsettled when it did not. Rolling an acknowledgement back would mean nacking, that is telling the broker to deliver the message again. That is an action on the broker, not an undo of the work, and with `Retry` outside the transaction it would start a redelivery while the local retry was still working on the same message. Outgoing sends are the opposite case and stay inside the transaction: not sending is a real undo. When the consumer settles is one option with the same name and meaning on every broker consumer, `ackMode`: | `ackMode` | Settled | Delivery | RabbitMQ | AMQP 1.0 | Kafka | SQS | Service Bus | Redis Streams | |---|---|---|---|---|---|---|---|---| | `manual` (default) | after the route, by its outcome | at-least-once | ack / nack-requeue | accept / modified, delivery-failed | offset commit | delete / visible again | PeekLock complete / abandon | `XACK` / stays pending | | `auto` | on receipt, before the route | at-most-once | broker auto-ack | accept | offset commit | delete | ReceiveAndDelete | `XREADGROUP NOACK` | It replaces `autoAck` (RabbitMQ), `autoAccept` (AMQP), `enableAutoCommit` (Kafka), `deleteAfterRead` (SQS), `receiveMode` (Service Bus) and `streamNoAck` (Redis); each of those is refused with its replacement named. The `false` settings of `autoAccept`, `enableAutoCommit` and `deleteAfterRead` settled nothing at all and have no successor. IBM MQ settles through its syncpoint and has no `ackMode`. `.WireTap(...)` is deliberately outside all of this. The tapped branch runs detached, with the ambient transaction suppressed, so it can publish even when the transaction later rolls back. Use it for notifications and copies, not for a message the next service will act on. ## Writing your own `ITransactedAction` `Commit` is called after the database transaction has closed, so `Transaction.Current` is null inside it. An action that needs to take part in the database transaction is not a deferred action at all: do that work in a route step. Register the action with `TransactedActions.Register(exchange, key, action, endpoint)`, under a key unique to the message, or hand a prepared send to `TransactedActions.RegisterSend(exchange, key, send, endpoint)`. The set of actions belongs to the enclosing block (`.Transacted()`, or `.BeginTransaction()` ... `.CommitTransaction()`) and exists only while the block runs. Outside a block, or after it has ended, nothing would ever commit the action, so registration throws instead. A producer of your own decides with `TransactedActions.Defers(exchange, transacted)`, where `transacted` is its `bool?` parameter: unset follows the block, `false` sends at once, `true` defers and fails outside a block. The built-in producers do exactly that. ## One database per transacted route A `TransactionScope` with **two independent durable connections** escalates to a distributed transaction (MSDTC), which .NET does not support on Linux. Keep a transacted route to a single database. Brokers never take part as `System.Transactions` resources: their sends are deferred and committed by the route, or leave at once with the ambient transaction suppressed, so they never cause escalation. This is also why a `sql:` step and `redb` must not share one transaction against the same database: the `sql:` connector opens its own connection. SQL Server refuses it, PostgreSQL breaks the commit, SQLite writes in autocommit past the transaction. Raw SQL that must commit with the redb work goes through `redb.Context` inside `ProcessWithRedb`, which is the transaction's own connection. ## Scope timeout The scope timeout defaults to **30 seconds** (`TransactionPolicy.Timeout`). Long work inside a transaction holds locks for that whole time, so keep transacted blocks short. A block that needs longer says so: `.Transacted(new TransactionPolicy { Timeout = TimeSpan.FromMinutes(2) })`. ## Parallelism A parallel `.Split()`, `.Multicast()`, `.RecipientList()` or `.ScatterGather()` **inside** a transaction is not refused. Each branch runs under a dependent clone of the route's transaction (`DependentClone(BlockCommitUntilComplete)`): the transaction commits only after every branch finished, and a branch that fails rolls the whole transaction back, best-effort mode (`stopOnException=false`) included: the fan-out still aggregates and returns, but the block cannot commit. The broker sends of the branches join the block and leave after the commit, as any send in it does. Database work in the branches is another matter: each parallel branch has a DI scope of its own and opens its own connection while the other branches hold theirs, and two connections at once in one transaction need a distributed transaction (see [One database per transacted route](#one-database-per-transacted-route)): SQL Server refuses it, PostgreSQL breaks the commit. Apache Camel binds a transaction to its thread, so its parallel branches run outside the transaction altogether. For parallel database work, keep the parent **without** `.Transacted()` and open a transaction **inside each sub-route**: ```csharp From("rabbitmq://batches?queue=batches.in") .Split(ex => ((Batch)ex.In.Body!).Items) // the parent is NOT transacted .To("direct://process-one"); // each sub-route is transacted on its own From("direct://process-one") .Transacted() .ProcessWithRedb(/* ... */) .End(); ``` ## Idempotent consumer Deduplicating a message and doing its work must commit together, or a crash between them loses the message. Place `.IdempotentConsumer(...)` **inside** `.Transacted()`: ```csharp .Transacted() .IdempotentConsumer(Header("messageKey"), "inbound-files") // ... work ... .EndIdempotentConsumer() .End() ``` | Placement | Behaviour | |---|---| | **Inside `.Transacted()`**, redb-backed repository | The key insert joins the transaction. A rollback removes the key, and a hard crash before the commit leaves nothing at all, no key and no work, so the redelivery is processed. Committed means both, and the key stays even if a later step fails (a send after the commit): the redelivery skips the committed work. The processor does **not** call `Remove`: another node may already hold the key again. | | **Inside `.Transacted()`**, repository outside the transaction (in memory) | The key follows the transaction all the same: the processor removes it when the transaction rolls back and keeps it when it commits. | | **Outside a transaction**, persistent repository | The key commits on its own and follows the exchange: it is confirmed when the exchange completes and removed when the exchange fails, anywhere in the route, after the block too, or is marked with `.RollbackAll()`. If the process dies between the key commit and the work, the key stays and the redelivery is skipped as a duplicate: an at-most-once loss window. | | **No database at all**, for example an HTTP call as the work | Atomicity is impossible and the loss window is inherent. Rely on the downstream being idempotent. | Rule of thumb: if the work is a database write, wrap the idempotent consumer in `.Transacted()`. If it is not, treat delivery as at-most-once across a hard crash. The key's fate is settled when the exchange's unit of work ends, before the route returns to its consumer: the key is back before the message goes back to the broker, so a redelivery that another node picks up at once is not skipped. This is Apache Camel's default (`completionEager=false`, `removeOnFailure=true`). Two details differ from Camel because `OnException` redelivers the whole route rather than the failed step: the exchange that holds a key is not a duplicate of itself, so a block that failed runs again on the redelivery and a block that succeeded is skipped, without the `CamelDuplicateMessage` mark. A Split or Multicast branch is a unit of work of its own, as in Camel. A repository tells the processor whether its writes join the transaction through `IIdempotentRepository.JoinsAmbientTransaction` (true for `RedbIdempotentRepository`, false by default). ## Routes that do not start from a broker: the outbox recipe Database first, sends after it, leaves one window: the work is stored, and the process dies before the message goes out. A route that starts from a broker closes it by itself, because the unacknowledged message comes back. A route that starts from an HTTP call, a timer or a file has nothing that comes back, and the announcement is lost for good. The answer is the transactional outbox, built from two routes, as it is in Camel. The event is written as a row in the same transaction as the work, so both stand or neither does; a second route polls the rows and sends them, marking each one only after the broker has taken it. ```csharp // 1. The work and the event commit together: the event is a row in the same database. From(Http.Listen("/orders").Host("0.0.0.0").Port(8080).Methods("POST")) .Transacted() .Unmarshal() .ProcessWithRedb(async (redb, ex, ct) => { var order = (Order)ex.In.Body!; await redb.SaveAsync(order, ct); await redb.Context.ExecuteAsync( "insert into outbox (id, payload, sent) values ($1, $2, false)", [Guid.NewGuid(), JsonSerializer.Serialize(order)], ct); }) .End(); // 2. The relay: one exchange per unsent row; onSuccess marks the row once the send went through. From(Sql.Poll("select id, payload from outbox where sent = false order by id") .DataSource("main") .Delay(1000) .OnSuccess("update outbox set sent = true where id = :#id")) .SetBody(ex => ex.In.Headers["payload"]) .To("kafka://orders.created"); ``` - A failed send leaves the row unmarked, and the next poll sends it again. - A crash between the send and `onSuccess` sends the row twice: the relay is at-least-once, like every broker delivery, so the receiving side deduplicates, for example with an [idempotent consumer](#idempotent-consumer). - Change data capture (Debezium, reading the outbox table from the database log) is the other common relay; it needs no polling and no `sent` column. A built-in outbox with its own table and background dispatcher, as MassTransit or NServiceBus ship, is deliberately not part of redb.Route: the two routes above are ordinary steps you can shape to your schema. ## Migrating off `BeginRedbTransaction()` `BeginRedbTransaction()` and the `Transacted(Suppress)` plus `BeginRedbTransaction()` pattern are obsolete. Under `.Transacted()` redb joins the transaction by itself, and opening a redb transaction under an ambient scope is rejected by the core. ```csharp // before .Transacted(TransactionPolicy.Suppress) .BeginRedbTransaction() // ... work ... .End() // after .Transacted() // ... work ... .End() ``` ## Known limitations - **`sql:` and `redb` in one transaction against the same database.** Not supported, see "One database per transacted route" above. Use `redb.Context` for raw SQL that must commit with redb work. Idempotency for a redb-backed route is the redb-backed repository; the SQL one is for routes without redb. - **Freeing stuck keys.** Idempotent keys left unconfirmed by an older release are not released automatically yet. A lease policy, where an unconfirmed key older than N becomes available again, is planned. ## See also - [METRICS.md](METRICS.md) — reading a route's own measurements, including `messageHistory()` used in the example. - [CONCURRENCY.md](CONCURRENCY.md) — `.Threads(N)` and consumer-level parallelism. Path: redb-route/UPGRADING.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/UPGRADING.md ---- # Upgrading redb.Route What to check and change when moving to a new version. Each section lists the changes that need action; [CHANGELOG.md](CHANGELOG.md) has the full list of what changed. ## 4.8.0 ### An agent without `AddRedbLlmStorage` deduplicates tool calls in the process `AddRedbRouteLlm()` now registers `InMemoryToolIdempotencyStore` as the default `IToolIdempotencyStore`, as it registers the other in-memory stores. Before, a setup without `AddRedbLlmStorage()` had no store, and a tool call the model repeated with the same tool-use id in a conversation ran the tool again; now the second call returns the stored output of the first. Only tools that are not `ReadOnly` are deduplicated, as with the redb store. - The store lives in the process: a restart forgets it, and each node of a cluster keeps its own. For deduplication that survives a restart or spans nodes, use `AddRedbLlmStorage()`. - A completed call is remembered for 24 hours after it completed, then forgotten on a later reservation (no timer); a call still in flight is never aged out, so a second run of it cannot start while the first is running. For another value, register the store yourself: `new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), ttl)`. - `AddRedbLlmStorage()` and a store you register yourself still replace it, before or after `AddRedbRouteLlm()`. - It does not roll back with a route's `.Transacted()`, nor does `InMemoryConversationStore`: after a rollback the conversation keeps the rolled-back run's tool calls and their results, so a redelivered message may not call the tool again. A run inside a transaction that uses either store logs a warning once per route and connection factory. Use `AddRedbLlmStorage()` for an `llm:` step inside `.Transacted()`, or move the step out of the block. ### An LLM store called without an exchange opens a redb scope of its own The stores of `AddRedbLlmStorage()` called without an exchange (a host calling a store directly, the eval runner) used the context's single `IRedbService`; they now open a redb scope of their own for each call, so concurrent calls no longer share one connection. A call with an exchange is unchanged: it works in the exchange's scope. What changes for you, only where your code calls a store without an exchange: - Inside a `TransactionScope` nothing changes: the call's own scope joins the ambient transaction, as every redb connection does, and rolls back with it. - Inside a transaction begun on the context's shared `IRedbService` (`ExecuteAtomicAsync`, `BeginTransaction`) the call is no longer part of it: it commits on its own and stays when that transaction rolls back. Pass the exchange, or put the work in a `TransactionScope`, where the store's writes must go with yours. - Outside any transaction each call commits at once, as before; your code undoes what it wrote when its own work fails. The list is in the README of redb.Route.Llm, "Calling the stores from your own code". ### `log:` `level=` takes the Camel names and refuses any other The `level` option of a `log:` endpoint takes the .NET names (Trace, Debug, Information, Warning, Error, Critical, None) and Apache Camel's (TRACE, DEBUG, INFO, WARN, ERROR, OFF), in any case. - `level=WARN` now logs at Warning and `level=OFF` logs nothing; both logged at Information before. - Any other value, a number included, is refused when the endpoint is created, so the route does not start; before it logged at Information without a word. Write one of the names above. ### The AMQP fluent entry point is `AmqpDsl` The static class `redb.Route.Amqp.Amqp` is renamed `AmqpDsl`, as the entry points `TimerDsl`, `GrpcDsl`, `TcpDsl` and `LdapDsl`. Under its old name the root namespace `Amqp` of AMQPNetLite shadowed it, so the short form `Amqp.Address("orders")` did not compile in a consumer's file; only the full name `redb.Route.Amqp.Amqp.Address(...)` reached it. Affected: code that writes `redb.Route.Amqp.Amqp.Address(...)`, or an alias of that class. Change it to ```csharp AmqpDsl.Address("orders") // with using redb.Route.Amqp; ``` The URIs it builds, the `amqp:` options and Route-XML are unchanged. ### A failed branch of a parallel ScatterGather or RecipientList rolls the transaction back A parallel `ScatterGather` or `RecipientList` inside `.Transacted()` (or `BeginTransaction()`) now runs each branch under a dependent clone of the route's transaction, as a parallel `Split` and `Multicast` already did. Until now its branches ran on the route's transaction itself, all at once, which System.Transactions does not allow across threads. What a route sees: - Before: in best-effort mode (`stopOnException=false`, the default) a failed branch was aggregated, the block committed, and the other branches' deferred sends went out. - Now: a failed branch rolls the whole block back, best-effort mode included. The fan-out still aggregates and returns, but the block cannot commit: the deferred sends are dropped, the database work rolls back, and the message comes back from the broker. To keep the old outcome, take the fan-out out of the transaction: - keep the parent **without** `.Transacted()` and open a transaction in each recipient route, so each branch commits on its own; or - make the fan-out sequential (`ParallelProcessing(false)`, `parallelProcessing: false`): sequential branches run on the route's transaction one after the other and are not isolated, so a failed branch in best-effort mode leaves the block able to commit. ### .NET 10 and .NET 11 only The redb.Route packages target `net10.0` and `net11.0`. The `net8.0` and `net9.0` builds are gone: .NET 8 and .NET 9 reached end of support on 10 November 2026. The `redb-route-xml` tool (`redb.Route.Xml.CodeGen`) runs on .NET 10, and the route project `redb-route-xml new` creates targets `net10.0`. Action: an application on .NET 8 or .NET 9 either stays on 4.7.x or moves its target framework to `net10.0` (or `net11.0`) before taking this version. A route project created by an earlier `redb-route-xml new` with `net9.0` changes it to `net10.0`. Nothing changes in the API. The `redb-route*` templates of redb.Templates create a `net10.0` module and no longer take `--framework`: a script that passes it drops the option. ### A consumer that failed to start is started again A consumer whose `Start` threw while its context started (a broker, a database or a server not up yet) used to leave its route `Errored` until someone started it by hand or restarted the process. The context now starts that consumer again in the background: first after 2 seconds, then with the pause doubling up to one minute, with no limit on attempts. The route stays `Errored` while it waits, so `RouteHealthCheck` reports it unhealthy, and becomes `Started` (with `OnRouteStarted` to the lifecycle listeners) once the consumer starts. Each failed retry logs a Warning with the next pause. The start-up line "started successfully: all N endpoints operational" is written only when every route started; otherwise a Warning names the `Errored` routes. What to check: - A route whose consumer is expected to fail at start and stay down (a test, a disabled connection) now retries. Give it `AutoStart(false)`, or set the retry options. - A listener or monitor that took `OnRouteErrored` after start-up as final now also sees `OnRouteStarted` later. - Routes with `AutoStart(false)` and routes a route policy starts (a clustered route waits for its lock) are not retried by the context; the policy keeps starting them as before. The options are `RouteEngineOptions.ConsumerStartRetry` (`RedbRoute:ConsumerStartRetry` for a host that binds `RouteEngineOptions` from the `RedbRoute` section; a Tsak worker binds it for every module context): | Option | Default | Meaning | |---|---|---| | `Enabled` | `true` | `false` keeps the old behaviour: the route stays `Errored`. | | `Delay` | `00:00:02` | Pause before the first retry. | | `Multiplier` | `2` | Factor the pause grows by after each failed retry (1 or more). | | `MaxDelay` | `00:01:00` | Longest pause between two retries. | | `MaxAttempts` | `0` | Number of retries; `0` retries until the context stops. | | `UnhealthyOnRestarting` | `true` | An `Errored` route waiting for a retry is Unhealthy; `false` reports it Degraded. | | `UnhealthyOnExhausted` | `true` | An `Errored` route no retry waits for is Unhealthy; `false` reports it Degraded. | ```csharp var context = new RouteContext(options: new RouteEngineOptions { ConsumerStartRetry = { Delay = TimeSpan.FromSeconds(5), MaxAttempts = 20 }, }); ``` ### A RabbitMQ send fails when the broker does not confirm it in 5 seconds A RabbitMQ send used to wait for the broker's confirm for as long as it took. A broker that blocks its publishers (a memory or disk alarm, often because a consumer stopped reading and a queue filled the disk) sends no confirm, so every send waited for as long as the alarm lasted, and the threads of the routes that sent piled up. A send now fails with `RabbitMQPublishTimeoutException` when the broker has not taken it within `confirmTimeout` milliseconds, 5000 by default as Apache Camel's. The timeout covers the wait for the channel, the publish and the confirm; in a transacted block, its publishes and the `tx.commit`; in a request-reply call, the request's publish (`timeout` still bounds the wait for the reply). What to check: - A route that sends large messages to a slow broker, or that is meant to wait out an alarm, gets a longer `confirmTimeout` (`Rabbit.Queue(..).ConfirmTimeout(30000)`, or `confirmTimeout=30000` on the URI). - A route that should survive a timed-out send handles it: `OnException()` takes it, and so does a handler for `TimeoutException`, its base type. Without one the send fails the exchange as any other failed send does. - A timed-out message may still reach the queue later, when the broker resumes. A route that sends again after a timeout can deliver it twice; the receiving side deduplicates, as for any at-least-once send. ### A Wire Tap runs on a bounded pool A `WireTap` used to start every copy as background work of its own, with no limit: a tap whose target slowed down (an audit store, a broker under an alarm) piled up copies and threads until the process ran out of them. Each tap now runs its copies on a pool of its own built from a thread pool profile, as Apache Camel does: at most 20 at a time and 1000 waiting by default; a copy that finds both full is run by the route's own thread before it goes on (`CallerRuns`). That copy still runs outside the caller's transaction and never fails the route. What to check: - A route whose tap target is slow now slows down itself once the pool is full, instead of growing without bound. Watch `redb.route.pool.caller_runs`. Give such a tap a profile of its own, larger or with `RejectedPolicy = Discard` when a lost copy is acceptable: `context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 50 })` and `.WireTap(uri, executorService: "audit")`. - The default profile for all taps is `RouteEngineOptions.DefaultThreadPoolProfile` (`RedbRoute:DefaultThreadPoolProfile`); named profiles are `RouteEngineOptions.ThreadPoolProfiles` (`RedbRoute:ThreadPoolProfiles:`) or `IRouteContext.AddThreadPoolProfile`. A name registered twice with other bounds throws; a tap that names an unknown profile fails when its route is built. - When the context stops, copies still running or waiting get the shutdown timeout; the number left is logged. - `IRouteContext` has two new members, `AddThreadPoolProfile` and `GetThreadPoolProfile`; a class of your own that implements it implements them too. ### An OnCompletion block runs in the caller, which waits for it A caller of a route with an `OnCompletion` block now waits for that block before it gets the exchange back; to keep the old behaviour, add `.ParallelProcessing()` to the block. This is Apache Camel's rule: a block runs in the caller unless `parallelProcessing` or an `executorService` gives it a pool. Before, every block after the consumer started as background work of its own, without limit. What to check: - A route whose consumer must answer fast (an HTTP request, a broker message acknowledged after the route) and whose block is slow: add `.ParallelProcessing()`, or `.ExecutorService("name")` with a profile of its own (see "A Wire Tap runs on a bounded pool"). The block then runs on a bounded pool, and the context waits for running blocks when it stops. - Nothing else changes for the block: it gets a copy, runs outside the caller's transaction and cancellation, and never changes the route's result; `ModeBeforeConsumer()` blocks run as before. ### An encrypted unsigned AS2 message has its MIC over the part with its headers The MIC of an AS2 message that is encrypted and not signed (compressed or not) is now computed over the decrypted, uncompressed part with its MIME headers, as RFC 4130 §7.3.1 and RFC 5402 §4.2 require and OpenAS2 computes it. Before, redb hashed the content alone, so such a message to OpenAS2 or another conforming partner came back with edbAs2.mdnMicStatus = mismatch and edbAs2.mdnConfirmed = false. Signed messages and unsigned unencrypted ones, compressed or plain, keep their MIC. What to check: - Two redb sides, one before and one after this change, on an agreement with Sign=false and Encrypt=true: every MDN reports mismatch, so mdnConfirmed is alse; the message itself is delivered. With RequireValidMdn the sending exchange fails and the route's error handling takes over; without it the MDN is logged and left to the route. Upgrade both sides, or agree Sign=true until both have. - A route that worked around the mismatch with such a partner (ignoring mdnMicMatch for unsigned encrypted agreements) can branch on mdnConfirmed again. ### An AS2 receiver refuses with 503 and Retry-After 30, and bounds its asynchronous MDNs An AS2 receive endpoint that refuses a request now answers `503 Service Unavailable` with `Retry-After: 30`, where it answered `429` with `Retry-After: 1`: the defaults of `rejectStatusCode` and `retryAfterSeconds` changed. A resend carries the whole message again, so the partner is told to wait for the load to pass. The same answer now also refuses a message that asks for an asynchronous MDN when every slot of the new pool is taken (`asyncMdnPoolSize`, 20 by default): the slot is taken before any work and kept until the receipt is posted. Before, every receipt was posted as background work of its own, without limit, and tried once; it is now tried up to `asyncMdnAttempts` (3) times. What to check: - A partner or a monitor that expects `429` from the receiver: set `rejectStatusCode=429` and `retryAfterSeconds=1` on the endpoint to keep the old answer. - A receiver that takes bursts of more than 20 messages asking for an asynchronous MDN at once: raise `asyncMdnPoolSize`; the refused ones are counted in `redb.route.as2.mdn.async_rejected` and in the endpoint's `Rejected`. - A partner MDN endpoint that answers `5xx` may now get the same receipt up to three times, with the same `Message-ID`; `asyncMdnAttempts=1` keeps one attempt. - The receiver is now bounded by default: 32 requests at once and 32 waiting (`maxConcurrentRequests=32`, `requestQueueLimit=32`), where it admitted every request. A burst past 64 is refused and resent by the partner. `maxConcurrentRequests=0` keeps the old unlimited admission; a receiver that set only `maxConcurrentRequests` now also queues 32, and `requestQueueLimit=0` keeps refusing at once. ### The SQL idempotent table has a `claim_id` column A claim now carries an id. `IIdempotentRepository.Lease` hands it out, and `Confirm(key, token)` and `Release(key, token)` act only while that claim still holds the key. The AS2 and AS4 receivers use them: a node whose claim was taken over after `inFlightClaimTimeout` no longer confirms or removes the new holder's claim. The SQL repository keeps the id in a new nullable `claim_id` column; the redb repository keeps it in a new field of its props class, which the scheme sync adds by itself. A repository of your own keeps compiling and behaves as before: the default `Lease` hands out no id, and the token methods then confirm or remove the key as before. What to do: - `SqlIdempotentRepository` with `CreateTable = true` (the default): nothing. The repository adds the column the first time it touches the table. - With `CreateTable = false`, add the column before any 4.8.0 node starts. Until then the first claim fails with a message that names this statement: ```sql -- PostgreSQL, MySQL, MariaDB, SQLite ALTER TABLE ADD COLUMN claim_id VARCHAR(36) NULL; -- SQL Server ALTER TABLE
ADD claim_id NVARCHAR(36) NULL; ``` `Add` (the idempotent consumer) does not need the column. - Order: run the ALTER first, then roll the nodes, with no downtime. A 4.7 node keeps working on the altered table because its insert names its columns. - Claims in flight during the upgrade have no claim id. They are answered as before: confirmed is a duplicate, and unconfirmed is in flight until `inFlightClaimTimeout`, after which it is taken over. Their 4.7 holders confirm or remove them unconditionally, as before. A token never matches a row without a claim id. ### A copy that goes on as an exchange of its own has a new id As in Apache Camel, the copy a `seda:` or `vm:` producer queues, and the copies of `Multicast`, `RecipientList`, `ScatterGather`, `Enrich` and `OnCompletion`, get a new `ExchangeId` and the `CamelCorrelationId` property set to the id of the exchange they were copied from (`Split` did so already). A `WireTap` copy and the exchange of a `PollEnrich` get a new id and no correlation id. `direct:`, `direct-vm:`, `Threads` and `Loop` keep the id. Until now every one of these copies kept the original's id. What changes for you: - A log search, an alert or a store that joins the two sides of one of these hops by `ExchangeId` joins on `CamelCorrelationId` of the copy (`exchange.GetProperty(ExchangePropertyKeys.CorrelationId)`, the `redb.correlation.id` span tag) instead. A wire tap's copy carries no link back: set a header or property in `onPrepare` if the tapped side needs one. - The in-flight list, the watchdog and the Tsak dashboard show each copy as its own entry, in the route it runs in. A message waiting in a `seda:` consumer used to be counted under the sending route's entry, with the sender's id. - After a `Multicast`, `ScatterGather` or `Split` that merges its results back, the original no longer takes a part's `CamelCorrelationId`: it keeps its own. - An `IExchange` of your own (a test double) that is used with these steps implements `CorrelatedCopy()` and `CorrelatedCopyLinked()`; the default members throw `NotSupportedException`. ### Split metadata are exchange properties, and a message part keeps its own headers As in Apache Camel, `Split` now publishes `CamelSplitIndex`, `CamelSplitSize` and `CamelSplitComplete` as exchange properties of each part, no longer as message headers, in both the ordinary and the streaming split. A part also carries `CamelCorrelationId`, the parent's exchange id. A part that is an `IMessage` (a record of a batch consumer, for example) becomes the part's message: a copy with its own body, headers and content type, without the parent's headers. Any other part becomes the body under a copy of the parent's headers, as before. What to change: - A route that reads the metadata as a header reads the property: `${header.CamelSplitIndex}` becomes `${property.CamelSplitIndex}`, `exchange.In.Headers["CamelSplitIndex"]` becomes `exchange.GetProperty(ExchangePropertyKeys.SplitIndex)`; the same for `CamelSplitSize` and `CamelSplitComplete`. - The metadata no longer reach a broker or a file with the part. A route that relied on that sets a header of its own from the property. - A streaming split now reads one part ahead, to know whether the current part is the last one: the last part has `CamelSplitComplete` set to `true` and carries `CamelSplitSize`; the parent carries `CamelSplitSize` after the split, as before. The source is therefore pulled one element earlier: the next element is fetched before the current part runs, not after it. A source that waits for its next element (a live stream, a channel) holds the current part back until that element or the end arrives; a source with side effects per element (a cursor, a queue read) has done them for one element more when a part stops the split (stopOnException). A splitter of your own must yield parts that stay valid after the next one is read. - A route that splits a list of `IMessage` and expected the parent's headers on each part sets them itself. ### The intercepted target is the `CamelToEndpoint` property `InterceptSendToEndpoint` publishes the target URI in the exchange property `CamelToEndpoint`, as Apache Camel does. The headers `redb.toEndpoint` and `CamelToEndpoint` are no longer set. What to change: - `${header.redb.toEndpoint}` and `${header.CamelToEndpoint}` become `${property.CamelToEndpoint}`; in C# `exchange.GetProperty(ExchangePropertyKeys.ToEndpoint)`. The value is the URI without its secrets, as before. - The target no longer travels with the message to the endpoint the intercept sends to. A route that needs it there sets a header of its own from the property. ### A forwarded reply-to is not carried on RabbitMQ, IBM MQ and AMQP producers used to copy a reply-to header into the outgoing message on every send. A message consumed with its sender's reply-to and forwarded to another queue therefore asked the next service to answer into the first sender's reply queue, a queue of another system that was not waiting for that answer. As in Apache Camel's JMS, an ordinary (not request-reply) send now leaves the reply-to out: the `ReplyTo` header on RabbitMQ, the `redbIbmMq.ReplyToQueue` and `redbIbmMq.ReplyToQueueManager` headers on IBM MQ, the `ReplyTo` and `ReplyToGroupId` headers on AMQP. The correlation id, the message id and the expiration are carried as before, and a request-reply send (`replyTo=true`) sets its own reply-to as before. What to change: - A bridge that must hand the sender's reply address on to the next service sets `preserveMessageQos=true` on the producer endpoint (`.PreserveMessageQos()` in the fluent builders). - A route that names a reply address on an ordinary send by setting the reply-to header does the same: the header is used only with `preserveMessageQos=true`. ### Kafka batch mode is `batching=true` with `maxBatchMessages` The Kafka consumer's batch mode follows the batch contract every broker of redb.Route shares, with Apache Camel's option names. `maxPollRecords` used to switch batch mode on and size it, and `pollTimeoutMs` was a fixed window from the start of collection. What to change: - `maxPollRecords=N` becomes `batching=true&maxBatchMessages=N` (`.MaxPollRecords(N)` becomes `.Batching().MaxBatchMessages(N)`). `maxPollRecords` is refused as an unknown option, naming its replacement. `maxBatchMessages` defaults to 500; `maxBatchMessages` without `batching=true` fails the start. - `pollTimeoutMs` in batch mode is now the idle timeout: the batch is sent on once no record came for that long, and every record restarts it. A steady stream therefore fills a batch to `maxBatchMessages`. To keep the old upper bound on how long a batch waits, set `batchingIntervalMs` to the old `pollTimeoutMs`. - The header `redbKafka.BatchSize` is gone: the size is `body.Count`, `${body.size}` in the expression language. - The batch message now carries `redbKafka.Topic` and `redbKafka.Partition` when every record of the batch agrees. ### A failed RabbitMQ message is tried 5 times, then rejected to the dead letter exchange The RabbitMQ consumer used to nack a delivery the route failed on with requeue, every time and at once: a message that always fails (a poison message) went round between the queue and the route forever, and never reached a dead letter exchange. As in Apache Camel's spring-rabbitmq, the consumer now tries the delivery again itself, `maximumRetryAttempts` times in all (default 5, the first included), `retryDelay` milliseconds apart (default 1000), and then rejects it without requeue (`rejectAndDontRequeue=true`, the default). A route error handler that handles the failure still ends it at once with an acknowledgement, and a delivery interrupted by the consumer's stop is requeued. What to do: - Declare a dead letter exchange for the queues whose failed messages must be kept: `deadLetterExchange` (and `deadLetterRoutingKey`) on the endpoint with `declare=true`, or `x-dead-letter-exchange` on a queue declared elsewhere. Without one, the broker drops a message that failed every attempt. - A failing delivery now holds its consumer slot for up to `(maximumRetryAttempts - 1) * retryDelay` milliseconds (4 s by default) before it is settled. With `concurrentConsumers=1` the queue behind it waits that long: a burst of 100 failing messages holds the messages after them for about 7 minutes (100 x 4 s). Camel's spring-rabbitmq does the same (its retries block the listener thread). Raise `concurrentConsumers`, or lower `retryDelay` or `maximumRetryAttempts`, where that matters. - The old behaviour, requeue at once on every failure: `maximumRetryAttempts=1&rejectAndDontRequeue=false`. ### IBM MQ `batchSize` is gone, batch mode is `batching=true` The IBM MQ option `batchSize` was declared and validated but read by nothing: a consumer with it received one message at a time. It is gone; an endpoint that names it fails to start, naming the replacement. Batch mode is now real: `batching=true` with `maxBatchMessages` (default 100), `pollTimeoutMs` and `batchingIntervalMs`, read with MQGET under syncpoint and committed once after the route (poll receive mode, and `backoutQueue` required). What to change: - Remove `batchSize` from IBM MQ URIs. Where a batch was wanted, write `batching=true&maxBatchMessages=N&backoutQueue=Q`, and change the route to take a `List` body (or `Split` it). ### An SQS list of IMessage goes out by SendMessageBatch, enableBatch is gone The SQS producer had a second way to send many messages: `enableBatch=true` sent any list body as `SendMessageBatch` entries, each element turned into text (a list of `IMessage` became the JSON of the message objects) with the parent's headers as attributes of every entry. Every producer of redb.Route now reads a list of `IMessage` the same way, one message per element with its own body and headers, so the option has nothing left to switch: `enableBatch` and `batchMaxMessages` are gone, and an endpoint that names them fails to start as with any unknown option. What to change: - Remove `enableBatch` and `batchMaxMessages` from SQS URIs (`.EnableBatch()` from the builder). - To send many messages, make the body a `List`: each element goes out with its own body and attributes, 10 per `SendMessageBatch` call; on a FIFO queue each element takes its own `redbSqs.messageGroupId` and `redbSqs.messageDeduplicationId` headers, else the endpoint's options. The parent's headers are not copied to the elements: set them on each element. - A list of strings or other values, with or without `enableBatch` before, is now one message, its JSON. To send its elements as separate messages, make them `IMessage` (`new Message(value)`). - Entries SQS refuses do not throw. Read `redbSqs.batchSuccessful`, `redbSqs.batchFailed` and `redbSqs.batchFailedEntries` after the send where a refused entry matters. ### An S3 or Firebase Storage object is kept when the route rolls back The S3 and Firebase Storage consumers deleted or moved an object only when its exchange succeeded, but they read success as "no unhandled exception": a route that marked the exchange rollback-only with `.RollbackAll()` (Camel's `markRollbackOnly()`) returns without an exception, and its object was deleted or moved as if it had been processed. Such an exchange now counts as failed, as it already did for the file, FTP and SFTP consumers and the message brokers: the object stays where it is and is offered again on the next poll, the idempotent mark is not written, and on Firebase Storage `moveFailed`, when set, moves it to the quarantine prefix. This follows Apache Camel's aws2-s3, which deletes or moves an object only when the exchange commits. S3 has no `moveFailed`, as in Camel. What to check: - A route that calls `.RollbackAll()` to skip an object it does not want, and relied on the delete to get rid of it: that object now comes back on every poll. Filter it out with `include`/`exclude`, or end the route normally (`.Stop()`) so the object is deleted, or set it aside on Firebase Storage with `moveFailed`. ### An MQTT message the route fails on is settled by one rule The MQTT consumer settled a failed message in two ways. Serial mode (the default) left the acknowledgement to MQTTnet, which acknowledged on return from the handler, so a failure was acknowledged like a success. Concurrent mode (`concurrentConsumers` above 1) left a failure unacknowledged and did nothing more; MQTT has no negative acknowledgement, the broker sends such a message again only when the client connects again to a session it kept, and it sends no more unacknowledged messages than the receive window (20 on Mosquitto by default), so after enough failures the consumer got no more messages. Both modes now follow Apache Camel's paho-mqtt5 consumer as corrected by CAMEL-25793 (merged in October 2026, not yet in a Camel release): - Every QoS 1 and QoS 2 message is acknowledged by the consumer after the route. - A failed message (an exception the route did not handle, or `.RollbackAll()`) of QoS 0, or on a session that ends with the connection, is acknowledged and logged as an error. The broker does not send it again. - A failed QoS 1 or QoS 2 message on a kept session stays unacknowledged; the consumer disconnects and connects again after a pause (1 s, doubling per failure in a row up to `maxReconnectDelay`, default 128000 ms; a success resets it), and the broker sends it again. The client speaks MQTT 5.0, where a session without a Session Expiry Interval ends with the connection, so `cleanSession=false` alone kept nothing before and keeps nothing now: the new option `sessionExpiryInterval` (seconds) keeps it. What to do: - A route that relies on the broker to send a failed message again: set `cleanSession=false`, a fixed `clientId` and `sessionExpiryInterval` (for example 3600), and make the route tolerate a message that comes twice (an idempotent consumer): after the reconnect the broker also sends again the messages not yet acknowledged at the disconnect. - A route on the default `cleanSession=true`: a failed message is acknowledged and lost to MQTT, as serial mode did before. Keep it with the route's error handling: an error handler with redelivery and a dead letter channel. - A kept session keeps its subscription when the consumer stops (it no longer unsubscribes), so the messages waiting in it reach the next start. ### The mail consumer selects mails by Camel's searchTerm, searchQuery is gone The IMAP option `searchQuery` was documented as not applied: the consumer never read it. It is gone, and an endpoint that names it fails to start, naming the replacement. The IMAP and POP3 consumers now take Apache Camel's `searchTerm`, in Camel's names, so a Camel URI carries over: - `searchTerm.unseen` (default `true`), `searchTerm.subjectOrBody`, `searchTerm.subject`, `searchTerm.body`, `searchTerm.from`, `searchTerm.to`, `searchTerm.fromSentDate`, `searchTerm.toSentDate`, `searchTerm.fromReceivedDate`, `searchTerm.toReceivedDate`. The terms are ANDed; a date is `yyyy-MM-dd HH:mm:ss` or `now` with an offset (`now-24h`). - `searchTerm=#name`: a MailKit `SearchQuery` registered under that name, sent to the IMAP server as it is; the `searchTerm.*` options are not read beside it. - A set search term replaces `fetchFilter`; setting both is refused at start. What to change: - Remove `searchQuery` from mail URIs (`.SearchQuery(...)` from the builder). Where it held a search, write the `searchTerm.*` options (`.SearchTerm(t => t.Subject("invoice"))`), or register a MailKit `SearchQuery` and name it with `searchTerm=#name`. - An endpoint with both `fetchFilter` and `searchTerm`: drop `fetchFilter`. `fetchFilter=All` is `searchTerm.unseen=false`; the other filters (Flagged, Answered, Recent) are a registry `SearchQuery`. - POP3 checks the terms on the client; `searchTerm=#name` and the received dates stop a POP3 route at start, since POP3 has no search and no arrival time. ### A Service Bus list body goes out as one batch, enableBatch is gone The Service Bus producer sent a list body as one message (its JSON), and as a batch only with `enableBatch=true`, where each item became a message under the parent's properties, a list of `IMessage` included. As Apache Camel's azure-servicebus sends an `Iterable` body, and as every producer of redb.Route now reads a list of `IMessage`, any list body is sent as one Service Bus batch, one message per element, which the entity takes whole or not at all: `enableBatch` and `batchMaxMessages` are gone, and an endpoint that names them fails to start, naming the rule. What to change: - Remove `enableBatch` and `batchMaxMessages` from Service Bus URIs (`.EnableBatch()`, `.BatchMaxMessages()` from the builder). `batchMaxSizeBytes` still bounds the batch. - A list of `IMessage` now sends each element with its own body and its own headers as application properties; the parent's headers are not copied to the elements. Set what each message needs on the element. - A list that was sent as one message (its JSON) before, without `enableBatch`, is now sent element by element. To keep one message, serialize the list in the route (`.Marshal("application/json")`). ### Kafka headers take Apache Camel's names, and a record's partition is chosen as in Camel The Kafka component's headers now have camel-kafka's names and types (`KafkaConstants`), so a route written for Camel reads and sets them unchanged. The old names are not read: a route that still uses one finds no header. | Before | Now | |---|---| | `redbKafka.Topic` | `CamelKafkaTopic` (`string`) | | `redbKafka.Partition` | `CamelKafkaPartition` (`int`) | | `redbKafka.Offset` | `CamelKafkaOffset` (`long`) | | `redbKafka.Timestamp` (a `DateTime`) | `CamelKafkaTimestamp` (`long`, milliseconds since the Unix epoch) | | `redbKafka.Key` | `CamelKafkaKey` | | `redbKafka.Sent.Topic`, `.Sent.Partition`, `.Sent.Offset`, `.Sent.Timestamp` | `CamelKafkaRecordMeta`: a `List`, one entry per sent record (`Topic`, `Partition`, `Offset`, `Timestamp` as the broker stored it) | | (none) | `CamelKafkaPartitionKey`: the partition of a sent record, per message | | (none) | `CamelKafkaHeaders`: the consumed record's `Confluent.Kafka.Headers` | The `KafkaHeaders` constants keep their member names (`KafkaHeaders.Key` and so on), so code that uses them only needs a rebuild; `KafkaHeaders.Sent*`, `KafkaHeaders.Prefix` and `KafkaHeaders.IsRedbHeader` are gone. Three behaviour changes come with it: - **The partition.** A producer sends to the endpoint's `partitionKey` (Camel's name), which takes precedence over the `CamelKafkaPartitionKey` header; without either, Kafka's partitioner places the record by its key. `partitionNumber` is the consumer's alone: a producer that names it fails to start, naming `partitionKey`. - **The key is kept with an explicit partition.** It used to be dropped when a partition was set. - **The metadata header.** `recordMetadata=true` (default `false`, as in Camel) puts one list in `CamelKafkaRecordMeta` instead of the four `Sent.*` headers; a list body gives one entry per element. The default `KafkaHeaderFilterStrategy` is Camel's: headers whose names start with `Camel`, `camel`, `org.apache.camel.` or `kafka.` neither go on a sent record nor come in from a consumed one. `keyFromHeader` is gone, as Camel has no such option: the `key` option wins, else `CamelKafkaKey` is the key. What to change: - Replace the old header names in routes, expressions and XML: `${header.redbKafka.Partition}` becomes `${header.CamelKafkaPartition}`, `` becomes ``. - Read `CamelKafkaTimestamp` as a `long` (`DateTimeOffset.FromUnixTimeMilliseconds`), not a `DateTime`. - Read the sent metadata from `CamelKafkaRecordMeta` (`((List)header)[0].Offset`). - A producer with `partitionNumber=n`: write `partitionKey=n` (`.Partition(n)` in the builder is now `.PartitionKey(n)`; a consumer's `.PartitionNumber(n)`). - `keyFromHeader=false`: remove the `CamelKafkaKey` header before the send instead (`.RemoveHeader(KafkaHeaders.Key)`). - A route that set a header beginning with `Camel` or `kafka.` to carry it to the next hop: rename it; such headers stay off the record, as in Camel. ### The tool idempotency reservation of an agent is kept in the agent's redb `AddRedbLlmStorage()` keeps the reservation of a tool's idempotency key next to the tool's stored output, by one rule: in the instance an `llm:` endpoint's `?redb=` names, else the one `AddRedbLlmStorage("")` names, else the context's default redb. It is an entry of redb.Route's idempotent repository (the `Route Idempotent Entry` scheme, processor name `llm-tool-idempotency`); the repository creates the scheme on first use. Before, a reservation without a name went through an `IIdempotentRepository` the host registered in DI, so it could sit in another database than the output, or only in memory: after a restart such a reservation was gone and a tool with side effects ran again. What changes for you: - `AddRedbLlmStorage()` alone is enough. The `IIdempotentRepository` you registered in DI for it is no longer used by the LLM storage; remove it unless something else needs it. - `RedbToolIdempotencyStore` is constructed as `new RedbToolIdempotencyStore(context, defaultRedbName)`; the `IIdempotentRepository` parameter is gone. Code that builds the store itself drops that argument. - A context with no redb it can open (no `IRedbService` registered on it or in its container, and no name) fails at the first reserved tool call with a message naming `AddRedbLlmStorage` and what is missing. - Reservations made before the upgrade are not found afterwards where they are not kept by this rule: those without a name (they sat in the host's repository), and, for an agent with a name, those made before the name was followed. A run that crosses the upgrade and retries a tool call it had reserved, or had completed, before finds no reservation and runs the tool again, so a tool with side effects can act twice for such a run. Let the agent runs finish before the upgrade (stop the `llm:` consumers and wait for the open runs), then roll the nodes. The old entries in the host's repository are not read again; its TTL, if one is set, removes them. ## 4.7.5 ### An IBM MQ consumer with a backout threshold needs somewhere to put a poison message A transacted IBM MQ consumer with a backout threshold (the `backoutThreshold` option, or the input queue's BOTHRESH) and neither a backout queue (`backoutQueue`, or the queue's BOQNAME) nor a dead letter queue on the queue manager (DEADQ) no longer starts. It fails with: ```text IBM MQ consumer on '': a backout threshold of is in force, but there is neither a backout queue (backoutQueue, or the queue's BOQNAME) nor a dead letter queue on the queue manager (DEADQ): a poison message would have nowhere to go. ``` Before, such a consumer started, and a message over the threshold was redelivered through the route without end. What to configure, one of: - `backoutQueue=` on the endpoint, or BOQNAME on the input queue (`ALTER QLOCAL() BOQNAME()`); - a dead letter queue on the queue manager (`ALTER QMGR DEADQ()`): a poison message then goes there behind a dead letter header; - or no threshold at all (BOTHRESH 0 and no `backoutThreshold`), with an error handler in the route that decides what happens to a message that keeps failing. A consumer that already had `backoutQueue` set behaves as before, and now also honours the queue's own BOTHRESH and BOQNAME when the endpoint sets neither. ## 4.7.0 ### An unclosed `${` is an error A `${` that no `}` closes used to be read as plain text, or as an empty value when a later `}` closed it by accident (`${a ${b}` gave nothing). It now fails where the template is compiled: ``` unclosed '${' at position 6 of "text ${body": the placeholder has no closing '}'. ``` A route file fails to load with that message at the element's position, and `check` / `pack` report it as an error at the attribute. In C#, the `StringExpression`, `SetBody`, `SetHeader` or endpoint option that holds the template throws when the route is built. To find offenders before upgrading, run `check` over the route files and search code for `${` without a closing `}`. A literal `${` is written `\${`. `ExpressionResolver.IsTemplate` now returns `true` for a string with an unclosed `${` (it returned `false`), so a caller that branches on it sends such a string to the compiler and gets the error. ### An unended string literal is an error A quoted literal that never closes (`header.kind == 'order`) used to be read cut short by one character, silently. It now fails where the expression is compiled, at load for a route file: ``` unterminated string literal starting at position 13 within the expression "header.kind == 'order". ``` Close the quote. A literal that needs a quote character inside writes it escaped: `'it\'s'`. ### `AND` and `OR` short-circuit The right side of `AND` / `&&` and `OR` / `||` used to be evaluated even when the left side already decided. It now runs only when it matters, as in C#. The results are the same; what stops is a side effect on that right side (`header.n++`, a `bean:` call) and an error it would raise. A route that relied on such a side effect running moves it out of the condition. `XOR` still evaluates both sides. `??` follows the same rule: its right side runs only when the left side is `null` (it used to run always in a compiled expression). The value is unchanged. ### A payload template's `expr(...)` evaluates its text `expr(x)` in a payload template, and `ExpressionResolver.ResolveExpression`, now read `x` exactly as the inside of a `${x}` hole. They used to evaluate it only when it held an operator written with spaces, a function call or an index, and passed any other text through as it was. So `expr('1>0')` gave the text `1>0`, `expr('42')` the text `42`, and a `bean:` call came back unevaluated. Now the text is an expression: a quoted literal gives its content (`expr("'yes'")` gives `yes`), a number or a boolean keeps its type, and a comparison is evaluated with or without spaces. A bare word or a path with `/` or `.` is a lookup, as in a `${}` hole, and gives empty when nothing answers (`expr('application/json')`); an unquoted `jpath`/`xpath` path is allowed, as in a hole. A constant belongs in the template text, not in `expr(...)`. ### Incrementing a value that is not a number is an error An increment or decrement of a header or property that holds something other than a number (`'abc'`) used to treat it as 0 and overwrite it with 1 or -1, silently. It now fails with `header.x++: the value 'abc' (String) is not a number.` and leaves the value as it was. A missing value still starts at 0, and a numeric text (`'7'`) still counts. ### Comparing numbers of different types A comparison of two numbers of different types, or of a number with a numeric text, used to be true whenever the left value was the smaller one: with `header.qty` = 3 (an `int`), `header.qty == 5.0` and `header.qty == '5'` were true. Such pairs are now equal only when their values are equal. This applies to `==`, `!=`, `in`, `not in` and `.contains(...)` on a collection. What to look for: filters, `when` branches and validations that compare an `int` or `long` header with a decimal literal (`5.0`), with a quoted number (`'5'`) or with a number read from text (a JSON, XML or form field). Their outcome may change, and the new one is the correct one. Same-type pairs (`int` with `int`, text with text) are unchanged. ### A method call on a value fails loudly Every expression is compiled and run by one engine now, so a method called on a value (`${header.s.toUpper()}`, `Expr("header.o.Check()")`, `header.o.Check(header.x)` in a condition) reads the same everywhere. These readings change: - A method that throws used to read as `null`; it is now an error naming the call, its position and the exception: `header.o.Boom() at position 1 threw InvalidOperationException: boom`. - A method the value's type does not have used to read as `null`; it is now an error naming it: `'nosuch' is not a method of String at position 1 (in header.s.nosuch())`. - A method call inside a comparison (`header.s.length() > 10`) used to fail to compile; it now works. - A bare `exception.Message` used to be the text itself; it now reads the exception's message, as `${exception.Message}` always did (`null` when there is no exception). A value that is `null` still gives `null` (`header.missing.toUpper()`), and text that is not an expression is still the text itself (`hello`, `plain text`, `key=value`). What to look for: expressions, templates and conditions that call methods of headers, properties or the body and silently relied on a `null` when the call failed. To keep a text that looks like a call, quote it (`'header.o.Check()'`) or set it as a constant. ### A format suffix in a placeholder formats A placeholder that ends in a colon and a standard .NET format, `${header.total.CostUsd:F4}`, used to drop the suffix silently and write the plain value (`0.125`). It now formats the value as `format(value, 'F4')` does, with the invariant culture (`0.1250`). The suffix is one letter and up to two digits (`F2`, `N0`, `D8`) after a path or a call. What to look for: templates with `:F`, `:N` or `:D` before the closing brace, such as log lines and messages that show amounts. Their text now carries the decimals the author asked for. To keep the old output, drop the suffix. ### `ExpressionSandboxViolationException.TargetType` can be null A `ref:name` or `env:NAME` refused in a template's sandbox calls no method, so the exception's `TargetType` is `null` for it (the type is now `Type?`) and `Written` holds the spelling. Code that catches the exception and reads `TargetType` checks it before use; a build with nullable warnings as errors points at such a read. ### Text after a complete expression is an error The engine used to stop where an expression was complete and drop the rest: `header.b == 3 garbage` compared `header.b == 3`, and `${exception.type|message}` rendered empty. Now the rest fails the route when it is built, naming it: `unexpected '|' at position 15 within the expression: the expression ends before it.` `check` and `pack` report it as an error at the attribute, where they used to warn. What moves: - trailing text after an expression, in `${...}`, in an expression attribute and in a condition: remove it, or quote it as text (`'garbage'`); - a file key in capitals in a template, `${FILE:NAME}`: the message says `file keys are lowercase: ${file:name}` (in the file components' own options, such as `moveTo`, capitals still work); - an Apache Camel spelling the language does not know, such as `${exception.type|message}` or `${a ${b}}`: write it in this language (`${exception.Message}`); - `${header.x y}` with a space in the name part: it is an expression now, and one that does not compile is the error. A one-word name (`${header.Content-Type}`, `${header.user.name}`) still reads the header; - `expr(...)` of a payload template with plain text (`expr('plain text')`): quote the text, `expr("'plain text'")`. Text with no operator in a value position is unchanged: `plain text` and `header.b 3` still read as the text itself, and `check` warns about the second, since in a condition it is always true. ### File keys in consumer options resolve or fail The file consumers' options `moveTo`, `preMove`, `moveFailed`, `doneFileName` and `idempotentKey` (File, FTP, SFTP) and S3's `doneFileName` used to know only `${file:name}` and `${file:name.noext}`. Any other key stayed as written: `moveTo=done/${file:ext}` moved files into a directory literally named `${file:ext}`. Now every key of the file language resolves (`${file:ext}` gives `csv`, `${file:parent}`, `${file:size}`, `${file:modified}` and the rest), and a key that is not one of them fails when the endpoint is created, listing the keys. Keys still match ignoring case in these options. What to look for: a directory under the polled one whose name starts with `${file:`. Rename or move its files where the option now puts them, or fix the key the error names. The file producers' `tempFileName` (File, FTP, SFTP) takes the same keys, read from the file being written: `tempFileName=${file:name}.part` writes `order.xml.part` and renames it to `order.xml`. Before, every key stayed as written, so all writes shared one temp file literally named `${file:name}.part`. A value without keys is unchanged; an unknown key fails when the endpoint is created. What to look for: a leftover file whose name starts with `${file:` in a target directory, left by a write that stopped halfway. Delete it. Firebase Storage's `moveAfterRead` and `moveFailed` take the same keys, read from the object, and stay prefixes: the object name follows them. A prefix with a `${file:...}` in it used to be written as is. What to look for: objects whose name starts with `${file:`; move them where the prefix now puts them. A subclass of `GenericFileConsumer` that moves files itself: override `PostProcessAsync(GenericFileInfo, string, CancellationToken)` and `OnProcessingFailedAsync(GenericFileInfo, string, CancellationToken)` to see the size and the time of the file. The forms with `(filePath, fileName, basePath)` still work: the consumer calls them for a subclass that overrides them. ### Bare text that breaks off as arithmetic is an error In an expression (`expr=`, `Expr(...)`, a condition), a text with `+`, `-`, `*` or `/` outside quotes is arithmetic. It used to be computed from whatever pieces could be read: `1 +` gave `1`, `header.a+b` gave `2b`, and a text such as `application/json` gave `null`, silently. Now such a text must be whole arithmetic, or it fails where the route is built, naming the place: - `1 +`: `the expression ends after '+' at position 3, where a value is expected` - `header.a+b`: `'b' at position 10 is not a value: write header.b, property.b or the text 'b' in quotes` - `header.Content-Type`: `'header.Content-Type' at position 1 reads as a subtraction: a name with a dash is written ${header.Content-Type}` What to look for: an expression attribute or `Expr(...)` holding text that looks like a MIME type (`application/json`), a path (`some/path/file.txt`) or a parameter list (`text/plain; charset=utf-8`). Write such a text in quotes (`expr="'application/json'"`), or as a constant (`value="application/json"`, `.SetHeader("k", "application/json")`). A dashed name goes inside `${...}`. Text without an arithmetic operator is unchanged: `hello` and `key=value` still read as the text itself. ### `AstNode.Evaluate` runs the compiled expression Code that parses an expression itself (`new Parser(new Tokenizer(text).GetAllTokens()).Parse()`) and calls `Evaluate` on the tree now gets what the engine gives for that text: the tree is compiled once and the compiled delegate runs. It used to be a separate evaluator, in which `++` / `--` did not write back and method calls on values were not supported; an expression that does not compile now throws `ExpressionCompilationException` on the first `Evaluate`. ### IBM MQ `connectionFactory` connects through the registered factory `wmq:` endpoints with `connectionFactory=name` used to ignore the registered `IbmMqConnectionFactory`: the name only split the connection pool, and the connection was built from the inline options on the URI or their defaults (`localhost:1414`, `DEV.APP.SVRCONN`, `QM1`, no credentials). Now the registered factory is the connection, and it takes priority over the inline options; a name nothing is registered under stops the route when it starts. What to look for: `wmq:` URIs (and `IbmMqDsl` builders) with `connectionFactory=`. What to do: make the registered factory hold the host, channel, queue manager and credentials the endpoint should use (the inline values on the same URI no longer count), or remove `connectionFactory` and keep the inline options. ### An XSD file reads its imports `` and `validator:schema.xsd` used to read the file as text, so its `xs:import` and `xs:include` had no location: each one was skipped without a word, and a schema that used an imported type failed with "Type … is not declared". Now the schema is read from its file and its imports and includes resolve relative to it, from under `schemaRoot` (the schema's directory unless set). Inline content and `ValidateXsd(string)` read one schema as before. Three things change for a file schema that loaded before: - **An import that does not load is an error.** One that is not found, lies outside `schemaRoot` (an absolute `file:` path included) or points to the network (`http://www.w3.org/2001/xml.xsd`) used to be skipped when the schema did not use it; now the route fails to start, naming the reference. What to look for: `schemaLocation=` in the schema and in the files it imports. What to do: copy the referenced files into the package, point `schemaLocation` at them, and set `schemaRoot` when they sit above the schema's directory (`..` for UBL's `maindoc/`). - **Lax wildcards are validated.** An `xs:any processContents="lax"` over a namespace whose schema is now imported checks the elements there against their declarations; before, no declaration was known and anything passed. What to look for: `processContents="lax"` in the schema. What to do: fix the documents the validator now rejects, or narrow the wildcard's `namespace=`. - **Generated code keeps the file.** `redb-route-xml` writes `` as `ValidateXsdFile("…", …)` instead of `ValidateXsd(…)` with the file's text inlined, so the generated project needs the schema files at runtime, found through the context's resource resolver as for `xslt`. What to do: ship the schema directory with the project, or regenerate after moving it. ### A mail whose exchange fails is left as it is `imap://` and `pop3://` used to apply `postProcess` to every message whose exchange returned, also when it carried an unhandled exception or was marked rollback-only with `.RollbackAll()`: under `postProcess=Delete` a failed mail was deleted, under the default `MarkRead` it was marked read. Now they follow Apache Camel's mail consumer. Only a successful exchange is committed (`postProcess`, `moveTo`, the headers `redbMail.Delete`, `redbMail.MoveTo` and `redbMail.CopyTo`); a failed one leaves the message as it is. A handled exception (`OnException(...).Handled(true)`, a dead letter channel) is a success, as before. `peek` now does what Camel's does, and its default is `true`. - **IMAP: a failed mail stays unseen and is fetched again.** With `fetchFilter=Unseen` (the default) it is routed again on every poll until its exchange succeeds. What to look for: `imap://` routes that leave failures unhandled and relied on `postProcess` to mark failed mails read or delete them. What to do: handle the failure; the exchange then commits like any success. Under the default `MarkRead` that is all: the mail is marked read and not fetched again. Under `postProcess=Delete` it would be deleted, so set `redbMail.Delete=false` in the handler to keep it, marked read. Or set `peek=false`, which marks each mail read when it is fetched, so a failed one stays read without a handler. - **POP3: a failed mail stays on the server and is routed again on every poll.** POP3 has no read flag, so `peek` does not apply. The mails after it are still routed and deleted. What to look for: `pop3://` routes that leave failures unhandled. What to do: handle the failure (under `postProcess=Delete` the mail is then deleted; with `redbMail.Delete=false` it is kept and fetched again). To route a kept mail only once, set `idempotentRepository` to a persistent repository with `idempotentRepositoryRemoveOnCommit=false`: its key is confirmed when the exchange commits and the mail is skipped whenever it is fetched again. A failed exchange releases the key, so the failed mail is still routed again. - **An explicit `peek=false` now marks mails read at fetch.** It used to have no effect. What to look for: `peek=false` on `imap://` URIs. What to do: remove it to keep mails unseen until their exchange is committed. ### A step on the side its component lacks fails when the route is built Some components have one side only (Apache Camel's `producerOnly` / `consumerOnly`): bean, cache, embed, fcm, knowledge, log, mcp, smtp, sns, stt, validator and xslt only send; imap, pop3, timer, cron and qtimer only receive. A route that started from a send-only component failed when the context started; a step that sent to a receive-only one failed only when the first exchange reached it, so a route with such a step in a branch never taken ran without a word. Now the mistake fails when the route is built or loaded, in one message: "timer has no producer side: a route cannot send to it (timer is consumer-only). Use it as a From() source." - **XML:** the loader refuses the route with the position of the step, in both the `uri=` and the structured form, and `check` reports it (the core components always, the connectors with `--bin`). - **C#:** a static target (`To`, `WireTap`, `Enrich`, `PollEnrich`, the endpoints of a load balancer or a scatter-gather) fails the route build, so `Start()` throws (`ThrowOnCompilationError`, the default) or the route is skipped and logged. A `From` on a send-only component throws at `Start()` as before. - **Dynamic targets** (`ToD`, `RecipientList`, `RoutingSlip`, `DynamicRouter` with a computed URI) still fail on the exchange, with the new message. - The exception is `NotSupportedException`, as before; its text is the new one. What to look for: one of the send-only schemes in `` or `From(...)`, or one of the receive-only schemes as a target, in particular in a branch that is rarely or never taken; and code that matches the old exception texts. What to do: remove the step, or use the scheme the message's hint names. ### A mail option the other side reads is refused `imap://`, `pop3://` and `smtp://` share one set of options. An option only the other side reads used to bind and do nothing: `subject` on an `imap://` URI, `postProcess` on an `smtp://` one. Now the endpoint refuses it when it is created, naming the parameters and never their values: "smtp producer 'smtp://mail.example.com' sets postProcess: only an imap or pop3 consumer reads it." A consumer option on `smtp://` is no longer validated either: `delay=-1`, `maxMessages=-1` or `postProcess=Move` without `moveTo` used to fail an smtp endpoint with a consumer's reason, and now the refusal names the option. What to look for: - `smtp://` URIs (and `Smtp.Send(...)` builders) that carry `folder`, `additionalFolders`, `delay`, `initialDelay`, `fetchFilter`, `maxMessages`, `postProcess`, `moveTo`, `sortBy`, `idle`, `idleTimeout`, `fetchBody`, `fetchAttachments`, `maxAttachmentSize`, `peek`, `idempotent`, `searchQuery`, `minAge`, `maxAge`, `subjectFilter`, `fromFilter`, `mapMimeHeaders` or `keepRawMessage` (and the 4.7 additions `delete`, `copyTo`, `idempotentRepository`, `idempotentRepositoryRemoveOnCommit`); - `imap://` and `pop3://` URIs (and `Imap.Read(...)` / `Pop3.Read(...)` builders) that carry `from`, `to`, `cc`, `bcc`, `replyTo`, `subject`, `contentType`, `alternativeBody` or `attachments`. What to do: remove the option; it had no effect on that side. ## 4.5.0 ### A Redis consumer starts only when it receives A `redis:` consumer (SUBSCRIBE, PSUBSCRIBE, XREAD, XGROUP, BLPOP, BRPOP) now subscribes, creates its consumer group and pins its XREAD position before `Start()` returns. Before, it did that in the background after the route had started: a message published or an entry added in between was lost, and a Redis that was down at start left a consumer that looked started and never received anything, with an error in the log only. What the operator sees now: when Redis does not answer at start, the route, and with it the context, fails to start with `InvalidOperationException: Redis consumer redis:: cannot start, Redis did not answer: ...`. In a Tsak worker the context shows as failed instead of running. Check that Redis is reachable from the worker before the context starts. Once a consumer has started, a later outage is handled as before: StackExchange.Redis reconnects and subscribes again. Start waits up to the connect and command timeouts of the connection (5 s each by default) before it gives up. ### An AMQP consumer starts only when the broker accepted its link An `amqp:` consumer now waits in `Start()` until the broker has answered every receiver link it attaches, as it did for `dynamic=true` only. Before, a link the broker refused (an address it does not serve, a routing type the address does not have, no permission to read it) was logged by the receive loop, and the consumer looked started and never received anything. On a MULTICAST address the subscription is the link itself, so it is now in place when `Start()` returns. What the operator sees now: the route, and with it the context, fails to start with `InvalidOperationException: AMQP consumer amqp:
cannot start: the broker refused the receiver link (: ).`, or `... the broker did not answer the receiver link within s.` after the endpoint's `timeout` (30 s by default). In a Tsak worker the context shows as failed instead of running. Fix the address, the routing type or the permissions the message names. ### An MQTT publish goes to its endpoint topic An `mqtt:` publish no longer reads `redbMqtt.topic` as its target. The connector writes that header itself, with the topic a message was received on and the topic of every publish, so a second publish in a route went to the first topic, and a received message republished to `mqtt://alerts/...` went back to the topic it came from. A route that set `redbMqtt.topic` to choose where a publish goes sets `redbMqtt.overrideTopic` (`MqttHeaders.OverrideTopic`) instead; `redbMqtt.topic` stays readable as the topic of the last receive or publish. ### An MQTT publish takes its endpoint QoS and retain flag An `mqtt:` publish no longer reads `redbMqtt.qos` and `redbMqtt.retain`. The consumer writes them with the QoS and retain flag of the received message, so a republished message kept the QoS it arrived with, and a retained message was retained again on the new topic. A publish now uses the endpoint's `qos`, `qosExpression` and `retain`. A route that set `redbMqtt.qos` or `redbMqtt.retain` to choose them sets `redbMqtt.overrideQos` (`MqttHeaders.OverrideQos`: 0, 1 or 2) or `redbMqtt.overrideRetain` (`MqttHeaders.OverrideRetain`: true or false) instead, as a number or bool from C# or as text from markup (``). Another value fails the publish. A route that wants a republish to keep the incoming flags copies them over: `exchange.In.Headers[MqttHeaders.OverrideRetain] = exchange.In.Headers[MqttHeaders.Retain];`. The MQTT 5 properties (`redbMqtt.contentType`, `redbMqtt.responseTopic`, `redbMqtt.correlationData`, `redbMqtt.messageExpiryInterval`, `redbMqtt.userProperties`) still pass through to a publish. ### XML structure limits XML that redb.Route reads from outside goes through `SafeXml`, and `SafeXml` now checks the structure of a document while it reads it. A document over a limit is refused with `XmlLimitException`, an `XmlException`, before it is built. The limits every caller gets: | Limit | Default | |---|---| | Nesting depth, the root counting as 1 | 256 | | Attributes on one element, namespace declarations included | 1024 | | Namespace declarations on one element | 256 | Size, element count and namespace declarations in the whole document are not bounded by default. These limits apply to XPath over a message body, the SOAP receiver and sender, Route-XML markup and templates. A document deeper than 256 levels used to be read and is refused now; search for such documents (generated XML, recursive structures) before upgrading. Code that reads XML through `SafeXml` itself can pass its own `XmlLimits`: `SafeXml.Parse(xml, XmlLimits.Default with { MaxDepth = 1024 })`. **SOAP receiver.** A request is checked once against these limits before anything parses it, and again after the body is decrypted; a request over a limit is a `Client` / `Sender` fault naming the limit. The request body is now bounded by `maxRequestBodySize`, 100 MB by default; it was not bounded before. `maxRequestBodySize=0` restores no bound. **AS4 receiver and sender.** The envelope has tighter limits, the shape of an eDelivery envelope: depth 32, 32 attributes and 16 namespace declarations on an element, 4096 namespace declarations in the envelope, and `maxEnvelopeCharacters` as before. A received envelope over them is a SOAP `Sender` fault; a partner's answer over them is an invalid receipt. A message must carry exactly one `xenc:EncryptedKey`, and each payload is decrypted once; anything else is `EBMS:0102`. Domibus, Holodeck B2B and this connector send messages well within all of this. ### AS4 refusals in their own counter An AS4 receiver used to count every message it refused (a malformed envelope, a failed signature or decryption, a message the agreement does not allow) in `Errors`, so a partner with a broken configuration turned the route red. These are now counted in `IEndpointStatistics.Refused`, with the reason of the last one in `LastRefusalMessage`, and no longer in `Errors`, the last error or health. `EBMS:0004` (a failure on our side) and route failures stay errors. An alert that watches `Errors` of an AS4 receive endpoint for refused messages should watch `Refused` instead; in a route, `stats('current', 'refused')`. ### `attachments` in an expression A bare `attachments` in an expression (`${attachments}`, `attachments.size`) now reads the attachments of the In message, as `${attachments}` does in Camel Simple. It used to fall back to an exchange property of that name, for example the list an `smtp:` route put in `exchange.Properties["Attachments"]`. An expression that meant the property writes `property.attachments`. ### Mail and SOAP attachments are message attachments `smtp:`, `imap:`, `pop3:` and `soap:` now work with the message attachments, `exchange.In.Attachments` (see the README, "Attachments"). The old conventions are removed with no transition period. **Nothing warns you.** `smtp:` no longer reads the exchange property `Attachments`. That property is an ordinary property now, so a route still setting it gets no error, and its mail goes out **without the files**. Search the code for `Properties["Attachments"]`, `MailAttachment` set on an exchange property, `SoapHeaders.Attachments`, `redbSoap.attachments`, `SoapHeaders.HasAttachments`, `redbSoap.hasAttachments` and `SoapAttachment`, and migrate each one as shown below. **Mail: files from code, before `smtp:`.** ```csharp // before exchange.Properties["Attachments"] = new List { new("orders.zip", zip, "application/zip") }; // after exchange.In.Attachments.Add(new Attachment { Name = "orders.zip", FileName = "orders.zip", ContentType = "application/zip", Content = AttachmentContent.FromBytes(zip) }); ``` **Mail: file paths, before `smtp:`.** ```csharp // before exchange.Properties["Attachments"] = new List { @"C:\out\report.pdf" }; // after: the file is read when the mail is sent exchange.In.Attachments.Add(new Attachment { Name = "report.pdf", FileName = "report.pdf", ContentType = "application/pdf", Content = AttachmentContent.FromFile(@"C:\out\report.pdf") }); // or a route step: .AddAttachmentFromFile(@"C:\out\report.pdf", contentType: "application/pdf") ``` The `attachments=` endpoint option (comma separated paths) stays as it was. **Mail: received mail.** `imap:` and `pop3:` also put the attachments of a mail on the message attachments. `MailMessageBody`, its `Attachments` and the `redbMail.*` attachment headers stay as they were, so routes reading them need no change. Two behaviors are new: a received mail sent on to `smtp:` carries its attachments (before, they were dropped), and its text (`MailMessageBody` converts to its text; before, the type name was sent as the text). **SOAP: sending attachments (producer, or a consumer reply).** ```csharp // before msg.Headers[SoapHeaders.Attachments] = new List { new("doc-1", "application/pdf", pdfBytes) }; // after msg.Attachments.Add(new Attachment { Name = "doc-1", ContentId = "doc-1", ContentType = "application/pdf", Content = AttachmentContent.FromBytes(pdfBytes) }); ``` A consumer route that replies with attachments replaces the request ones: `e.In.Attachments.Clear()`, then `Add`. As before, a reply that still holds exactly the request attachments is sent without them. **SOAP: reading attachments.** ```csharp // before var parts = e.In.GetHeader>(SoapHeaders.Attachments); byte[] bytes = parts![0].Content; bool any = e.In.GetHeader(SoapHeaders.HasAttachments); // after var part = e.In.Attachments.Find("doc-1"); // named by the Content-ID byte[] bytes = part!.Content.ReadAllBytes(); bool any = e.In.Attachments.Count > 0; // in an expression: attachments.size > 0 ``` `SoapAttachment.ContentId`, `ContentType` and `Content` map to `Attachment.ContentId` (also its `Name`), `ContentType` and `Content.ReadAllBytes()`. A producer reply's attachments are on `exchange.Out.Attachments`, and on `In` after the pipeline moves on. ## 4.4 ### Unknown URI options stop the context `direct-vm:` now reads its URI parameters, and it reads them strictly, like every connector that is not lenient. Before 4.4 it ignored every parameter, so a URI such as `direct-vm://orders?inOut=true` started without a word. In 4.4 the endpoint refuses such a parameter, and the context fails to start: ``` System.ArgumentException: 'inOut' is not an option of the DirectVm endpoint. ``` `direct-vm:` has one option, `headerFilterStrategy=#name`, and it applies to the caller side only. Drop anything else from its URIs. A direct-vm call always returns the reply to the caller, so `inOut=true` was never needed. Options taken from Apache Camel's direct-vm (`block`, `timeout`, `failIfNoConsumers`, `propagateProperties`) are refused the same way. This is the rule that every strict connector has followed since 4.2.0. An application that comes from a version before 4.2.0 meets it on every connector except `http:`, `sql:` and `bean:`, which take extra parameters on purpose: - **An unknown name** is refused with `'' is not an option of the endpoint.`, followed by the nearest option (`Did you mean 'period'?`) or by the connector's note on what replaced it. - **A value that does not convert** is refused with `'