Bundle: redb-route / demo/SerialNumbersDemo (demo.SerialNumbersDemo.txt), 79 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/demo/SerialNumbersDemo/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/demo/SerialNumbersDemo/Directory.Build.props
----
net10.0enableenablefalse4.3.0false10.0.15
Path: redb-route/demo/SerialNumbersDemo/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/demo/SerialNumbersDemo/README.md
----
# SerialNumbersDemo: a partner integration hub on redb and redb.Route
A small but complete integration project, meant as a template for your own: trading partners send
serial number requests as XML files over **SFTP** or **AS2**, the hub stores everything, decides each
request, issues serial numbers in **SQL Server** and sends the answer back over the partner's
transport. A product API lets a web page, or code in the same process, activate a product, and the
requests that waited for it are answered without the partner sending anything again.
Needs redb and redb.Route **4.1.0** or later: one transaction path with `.Transacted()`, file consumer
backoff, path filters on the file consumers and an async `InitRoute.main` are used throughout.
It shows the pieces a real integration needs, each in the place it belongs:
| Concern | How |
|---|---|
| Transports | `Sftp.Directory(...)`, `As2.Receive(...)` / `As2.Send(...)`, `FileDsl.Write(...)`, `Sql.Poll(...)` |
| Connection settings | one named connection factory per partner in the registry, no secrets in routes |
| Durable archive | a raw copy of every received file, before anything can fail on its content |
| Routing by content | `Choice()` with `XPath(...)` |
| Validation | `ValidateXsd(...)` + `Unmarshal("application/xml")` inside `DoTry` / `DoCatch` |
| Atomic processing | `.Transacted()`: redb objects, flat tables through `redb.Context` and an EF Core `DbContext`, one transaction |
| Duplicate requests | the request id of the partner is the unique key of the request object, checked in the same transaction |
| Business rules | a pure function in the domain project, a `Choice()` branch in the route |
| Requests that wait | a request for a draft product is put on hold, and released from the archive when the product is activated |
| Web and in-process calls | REST DSL `PUT /api/products/{gtin}/status`, and a `ProducerTemplate` to the same `direct:` endpoint |
| Serial numbers | one random number per block of 10 000, issued by one set-based SQL statement |
| Polling while things fail | SFTP consumer backoff: fewer polls while the server or the database is down |
| Several directories of one partner | one consumer on their parent with `Recursive()` and `AntInclude(...)`, so one connection serves them all |
| Seeing messages flow | `.Log(...)` at every stage, `.MessageHistory()` on the intake and request routes |
| Context-wide error handling | `OnException().Handled(true)` in its own route builder |
| Reliable delivery | an outbox table written in the same transaction, read by `Sql.Poll` with `OnSuccess` / `OnFailure` |
| Scheduled work | `Cron.Schedule(...)` (Quartz.NET): a quota usage report from a flat table and redb objects |
## Layout
```
SerialNumbersDemo/
├─ Directory.Build.props <- target framework, redb and EF Core package versions, in one place
├─ SerialNumbers.Domain/ <- redb entities + the business rules (depends on redb.Core only)
│ ├─ Entities/ <- Partner, Product, InboundMessage, SerialNumberRequest, SerialNumberResponse
│ └─ Services/ <- SerialRequestPolicy (pure), statuses, reasons, transports
├─ SerialNumbers.Core/ <- the Tsak module
│ ├─ InitRoute.cs <- entry point (async): components, connections, database, routes
│ ├─ SerialNumbers.Core.config.json <- the module's configuration layer
│ ├─ ModuleSettings.cs <- settings from the context, passwords from the environment
│ ├─ Catalog/ <- product status changes: the EF Core journal and the API contract
│ ├─ Infrastructure/ <- context-wide exception handling
│ ├─ Integration/Xml/ <- wire formats of the partner messages + XSD
│ ├─ Routes/Inbound/ <- one SFTP consumer / AS2 endpoint per partner
│ ├─ Routes/Processing/ <- intake (archive, route by type) and the request transaction
│ ├─ Routes/Catalog/ <- the product API and the release of requests on hold
│ ├─ Routes/Outbound/ <- outbox polling and one delivery route per partner
│ ├─ Routes/Reports/ <- a cron route: the quota usage report
│ ├─ Services/ <- the steps the routes call (redb objects, SQL through redb.Context)
│ └─ Database/schema.sql <- the flat tables and the EF Core journal table
├─ SerialNumbers.Worker/ <- debug host + two simulated partners (ACME on SFTP, GLOBEX on AS2)
├─ SerialNumbers.deploy/ <- pack-tpkg.ps1, docker-compose.dev.yml, docker-compose.tsak.yml, .env.example
└─ samples/ <- partner files for every path through the hub
```
## Where the data lives
- **redb objects** for the business model: partners, products, every inbound message, requests and
responses. Partners and products carry their natural key (code, GTIN) as the unique key of the object.
- **Flat tables** in the same database for what is volume rather than model: one row per serial
number (a request can ask for tens of thousands), the yearly allocation ledger the quota is checked
against, and the outbox.
- **An EF Core model** for the product status journal, standing in for the part of a data model an
existing application keeps in EF Core.
- **One transaction** covers all three, as the next section shows.
## Run it
Requirements: .NET 10 SDK, Docker.
```bash
docker compose -f SerialNumbers.deploy/docker-compose.dev.yml up -d
dotnet run --project SerialNumbers.Worker
```
The worker creates the `serials_demo` database, the redb tables, the flat tables, self-signed AS2
certificates, two partners and three products (one of them a draft), then starts the hub and the
simulated partners. Relative paths resolve against the current directory: everything the worker writes
goes under `runtime/`.
Coming from the first version of the demo? Its flat tables have a different shape. Start from a clean
database: `docker compose -f SerialNumbers.deploy/docker-compose.dev.yml down`, then `up -d` again.
Drop sample files into a partner's outbox:
```bash
cp samples/acme/*.xml runtime/partners/acme/outbox/ # uploaded to the hub over SFTP
cp samples/globex/*.xml runtime/partners/globex/outbox/ # sent to the hub over AS2
```
Responses arrive in `runtime/partners//inbox/`, the raw copies in `runtime/archive/`, and a
quota usage report lands in `runtime/reports/` every minute.
## One transaction
This is the core of the request route (`Routes/Processing/SerialNumberRequestRouteBuilder.cs`):
```csharp
.Transacted()
.ProcessWithRedb(SerialRequestService.RegisterAsync)
.Choice()
.When(e => DecisionOf(e) == MessageStatuses.Accepted)
.ProcessWithRedb(SerialRequestService.AllocateAsync)
.ProcessWithRedb(SerialRequestService.QueueResponseAsync)
.When(e => DecisionOf(e) == MessageStatuses.Rejected)
.ProcessWithRedb(SerialRequestService.RejectAsync)
.ProcessWithRedb(SerialRequestService.QueueResponseAsync)
.EndChoice()
.EndTransaction()
```
- `.Transacted()` opens a transaction around the block. redb takes part in it by itself: every step
that works through `IRedbService`, raw SQL through `redb.Context` included, runs on the connection the
transaction holds. Everything commits together or nothing does.
- **Duplicates are recognised by the data, not by a registry of processed files.** The request object
carries the partner's request id as its unique key, written in the same transaction: a second request
with that id is answered as a duplicate, a concurrent twin fails on the key, and a delivery that rolled
back leaves no trace and is processed again. A separate repository of delivered files would key the
same fact by file name and size, which a corrected file changes and a re-sent request does not.
- **SQL against the same database belongs in `redb.Context`**, not in a `sql:` endpoint inside the
block: that endpoint opens a second connection while redb's is still open, and two open connections
in one transaction make it a distributed transaction, which fails on SQL Server and aborts at commit on
PostgreSQL. Outside a transaction, as in the outbox and report routes, `sql:` is the right tool.
- **No parallel branches in one transaction.** Work running at the same time on the transaction's
connection, as a parallel `Split` or `Multicast` inside the block would, is refused; open the
transaction inside each branch instead.
- The default policy is `Required`, `ReadCommitted`, 30 seconds. Pass a `TransactionPolicy` to
`.Transacted(...)` when a block needs more.
## Requests on hold
A product starts as a **draft**. A request for it is not the partner's mistake, so it is neither
rejected nor failed: it is recorded with the status `OnHold`, the partner's file is accepted as usual
(the SFTP file moves to `.done`, an AS2 sender gets a positive MDN), and nothing is sent yet.
When the product is activated, the hub releases those requests on its own:
1. `set-product-status` changes the redb product and writes a row of the EF Core status journal, in one
transaction.
2. After it commits, `release-held-requests` finds the requests on hold for the product and reads each
one's file back from the archive.
3. Each file goes through the request route again, in a transaction of its own. The registration
recognises the release and decides the **same** request object again, against the product and the
quota as they are now.
A released request is no longer on hold, so a second activation call finds nothing to release, while a
release that rolled back left the request on hold and the next call retries it. A failure stops the batch
and reaches the caller; the requests not released stay on hold.
Activate the draft product from a web page, curl or anything else that speaks HTTP:
```bash
curl -X PUT http://localhost:8090/api/products/04607005550001/status \
-H "Content-Type: application/json" \
-d '{"status":"Active","changedBy":"alice"}'
# {"gtin":"04607005550001","status":"Active","outcome":"Changed","requestsReleased":1}
```
The REST DSL declares the operation, binds the JSON body and serves an OpenAPI document at
`/api/products/openapi.json`:
```csharp
this.Rest("/api/products", o => { o.Port = settings.ApiPort; o.BindingMode = RestBindingMode.Json; })
.Put("/{gtin}/status").Consumes("application/json").Type()
.To(RouteUris.SetProductStatus);
```
Code in the same process calls the same endpoint with a `ProducerTemplate`. The debug host does that
for the console command `status 04607005550001 Active` (`SerialNumbers.Worker/ProductConsole.cs`):
```csharp
using var producer = new ProducerTemplate(hub);
producer.Start();
var message = new Message(new ProductStatusChange(status, ChangedBy: "console"));
message.Headers[SerialHeaders.Gtin] = gtin;
Console.WriteLine(await producer.RequestBody(RouteUris.SetProductStatus, message, stopping));
```
## EF Core on the redb connection
The status journal is an EF Core `DbContext` (`Catalog/CatalogAuditDbContext.cs`), written in the same
transaction as the redb product (`Catalog/ProductCatalog.cs`):
```csharp
product.Props.Status = change.Status;
await redb.SaveAsync(product, ct);
await using var journal = CatalogAuditDbContext.On(await redb.Context.Db.GetUnderlyingConnectionAsync(ct));
journal.StatusChanges.Add(record);
await journal.SaveChangesAsync(ct);
```
`CatalogAuditDbContext.On` builds the context with `UseSqlServer(connection, contextOwnsConnection: false)`.
Inside `.Transacted()`, `GetUnderlyingConnectionAsync` returns the connection the transaction holds; the
connection is already enlisted, so EF Core writes into the same transaction and `SaveChanges` opens no
transaction of its own. Three rules keep it that way:
- EF Core uses exactly this connection, never one of its own.
- EF Core and redb use the connection one after the other, never at the same time.
- It runs inside `.Transacted()`. `ProductCatalog` refuses to run outside a transaction, where the two
writes would commit separately.
This works on SQL Server and PostgreSQL. On SQLite the transaction is not an enlistment but a transaction
object redb begins itself, and EF Core does not join it.
The EF Core version is set in `Directory.Build.props`. Its SQL Server provider has to accept the
Microsoft.Data.SqlClient version redb.MSSql and the Tsak worker ship.
## Serial numbers that cannot be guessed
Serial numbers on medicines are checked at the pharmacy against the agency the authorization holder
reports them to, so they must not be guessable. The hub gives every number a block of its own: the i-th
number of a request is a random value between `(first + i) * 10000 + 1` and `(first + i + 1) * 10000`,
one chance in 10 000 to guess it. The randomness comes from `CRYPT_GEN_RANDOM`, the cryptographic
generator of SQL Server, and one `INSERT ... SELECT ... FROM GENERATE_SERIES(...)` writes all 30 000 rows
(`Services/SerialNumberAllocator.cs`). Blocks never overlap, so two numbers cannot collide.
The response lists every number:
```xml
ACME-2026-000104607001234567Accepted30000000000007315000000012094
...
```
## Seeing how messages flow
Every stage writes a log line: a file received over SFTP or AS2, archived, recognised, decided and
queued, released, delivered. The SFTP inbound route uses the richer form that adds headers to the entry:
```csharp
.Log()
.Message("${header.serials.partner}: received ${header.serials.fileName} over SFTP")
.Header(SftpHeaders.FileLength)
.EndLog()
```
`.MessageHistory()` on the intake and request routes times every step. The trace lives in the exchange,
so a step has to print it: the parked-message handler in `ExceptionRouteBuilder` logs it with
`.Log(MessageHistory.Format, LogLevel.Warning)`, and the same line at the end of the request route prints
the path of every request at `Debug`. History is off globally (`RouteEngineOptions.EnableMessageHistory`)
and switched on per route, because timing every step costs time.
In a processor of your own, take the logger from the exchange's context:
`exchange.Context.GetService()`. If you create a `RouteContext` yourself, pass it an
`ILoggerFactory`; without one the `.Log` steps write nothing and the routes keep working.
Under Tsak each route has a page with the messages in flight, counters, errors and per-endpoint
statistics, and the worker has a live log viewer with a level filter and search.
## Configuration
The module reads its settings the way a Tsak module does: from the properties of its route context.
| Where | What |
|---|---|
| `SerialNumbers.Core/SerialNumbers.Core.config.json` | Module defaults, shipped in the package: archive folder, SFTP host and user, AS2 id and port, product API port, report folder and schedule |
| `Tsak:Contexts:serial-numbers:Override` in the worker's `appsettings.json` | Values of one environment, the last word. The debug host sets local folders, the SFTP container and a report every minute here |
| `ConnectionStrings:MSSql` of the worker | The SQL Server database of the hub: redb objects, flat tables and the EF Core journal. Under Tsak it is redb's database only with `Tsak:Redb:Provider` set to `mssql` (see [Run it under Tsak](#run-it-under-tsak)) |
| `Sftp:Password`, `Sftp:Passwords:`, `As2:CertificatePassword` in the `Override` section | Secrets: environment variables on the worker (`Tsak__Contexts__serial-numbers__Override__Sftp__Password`), never in a file that ships. See `SerialNumbers.deploy/.env.example` |
The Tsak worker merges `Tsak:Contexts:default`, `Tsak:Contexts:serial-numbers`, the module's config file
and the `Override` section in that order and sets every root key as a context property (a section
becomes a dictionary); `ModuleSettings.FromContext` reads them back. Route builders take nothing through
their constructors: in `Configure()` they read the settings, and the partner list `InitRoute` loaded from
redb, through `Context`. `SerialNumbers.Worker` builds the same layers from its own `appsettings.json`
(`ContextConfiguration.cs`), so an environment variable such as
`Tsak__Contexts__serial-numbers__Override__Report__Cron` or `ConnectionStrings__MSSql` works the same way
in both.
The AS2 endpoints and the product API share the process's HTTP servers, one per port. The host
registers them with `services.AddRedbRouteHttpHosting()`: the Tsak worker does, and so does the debug host.
## What each sample does
| File | Path through the hub | Result |
|---|---|---|
| `acme/SNREQ_ACME_0001.xml` | SFTP, valid | Accepted, 30 000 serial numbers, response over SFTP |
| `acme/SNREQ_ACME_0002_over_limit.xml` | SFTP, above the per-request limit | Rejected `QuantityOutOfRange` |
| `acme/SNREQ_ACME_0003_unknown_product.xml` | SFTP, GTIN not in the catalog | Rejected `UnknownProduct` |
| `acme/SNREQ_ACME_0004_duplicate.xml` | SFTP, request id already seen | Rejected `DuplicateRequest`, in a response file of its own |
| `acme/SNREQ_ACME_0005_schema_violation.xml` | SFTP, breaks the XSD | Recorded as Invalid, no response |
| `acme/SNREQ_ACME_0006_broken.xml` | SFTP, not well-formed XML | Recorded as Invalid, no response |
| `acme/SNREQ_ACME_0007_draft_product.xml` | SFTP, the product is a draft | On hold, no response; activate the product and it is accepted |
| `acme/PIF_ACME_0001.xml` | SFTP, a message type with no route | Parked by the context-wide `OnException` |
| `globex/SNREQ_GLOBEX_0001.xml` | AS2, valid | Accepted, response over AS2 |
| `globex/SNREQ_GLOBEX_0002_quota.xml` | AS2, over the yearly quota | Rejected `AnnualQuotaExhausted` |
## Failures, and who deals with them
| Failure | Handled by | Outcome |
|---|---|---|
| Not well-formed XML | `Choice()` branch in the intake | Archived, recorded as Invalid |
| Schema violation | `DoTry` / `DoCatch` | Archived, recorded as Invalid |
| Message type without a route | `OnException().Handled(true)` | Archived, recorded as Parked |
| Business rejection | `Choice()` in the transaction | A normal response with the reason |
| Product is a draft | the policy decides `OnHold` | Recorded, nothing sent, released when the product is activated |
| Same request delivered twice | unique key of the request object, checked in the transaction | Answered as a duplicate, nothing issued |
| Database or network down | nothing, on purpose | Rolled back; the SFTP file stays for the next poll, an AS2 sender gets a negative MDN |
| The same failure on every poll | SFTP consumer backoff | After three failed polls in a row the next ten are skipped |
| A release fails | nothing, on purpose | That request rolls back and stays on hold, the batch stops, the API call fails; call it again |
| Partner unreachable on delivery | `Sql.Poll(...).OnFailure(...)` | The outbox row counts the attempt and is retried |
A handled exception is a success for the consumer: the SFTP file moves to `.done`, an AS2 sender gets
a positive MDN. That is why the context-wide handler catches one specific exception, and technical
failures are left unhandled.
The SFTP consumer's backoff is declared on the endpoint:
```csharp
Sftp.Directory(partner.SftpInboundFolder!)
.Delay(2000)
.MoveTo(".done")
.BackoffErrorThreshold(3)
.BackoffMultiplier(10)
.BackoffOnFailedExchanges()
```
`BackoffErrorThreshold` and `BackoffMultiplier` work as in Apache Camel: a poll that could not run, for
example because the server is down, counts as failed. `BackoffOnFailedExchanges()` goes further than
Camel: a poll in which every file failed in the route, as they do while the database is down, counts as
failed too, and a poll with one successful file is a success.
## Scheduled work
`QuotaReportRouteBuilder` starts from `Cron.Schedule("reports/quota-usage", ...)`: Quartz.NET fires the
route, no message has to arrive. It sums the allocation ledger with `Sql.Execute(...)`, looks up the
annual quota of each product in redb and writes a CSV file:
```
gtin,product,requests,issued,annual_quota,remaining,used_percent
04607001234567,"Paracetamol 500 mg, 20 tablets",1,30000,10000000,9970000,0.3
04607009990001,"Vitamin D3 drops, 10 ml",1,30000,40000,10000,75.0
```
- The schedule is `Report:Cron` (Quartz format, seconds first; the module ships `0 0 6 * * ?`, every
day at 06:00), read in `Report:TimeZone` (`UTC`). The debug host overrides it to every minute.
- `Stateful()` keeps two runs from overlapping when one takes longer than the interval.
- Under Tsak the route runs on the worker's shared Quartz scheduler. A Tsak cluster keeps that scheduler
on the database job store with `quartz.jobStore.clustered=true` (the worker logs a critical error
otherwise), and a clustered Quartz fires each trigger on one node.
## Debug, then deploy
`SerialNumbers.Worker` awaits `SerialNumbers.Core.InitRoute.main(ctx)`, the same entry point the Tsak
worker calls, so breakpoints in routes and services work as in any console app. `main` is async:
```csharp
public static async Task main(IRouteContext context)
```
Tsak accepts this form and the synchronous `IRouteContext main(IRouteContext context)`; a `main` of any
other shape is reported as an error when the module loads. To deploy:
```powershell
./SerialNumbers.deploy/pack-tpkg.ps1
# -> SerialNumbers.deploy/output/SerialNumbers.tpkg
```
The package carries the module's two DLLs and EF Core; redb, redb.Route and SqlClient come from the
worker's shared libraries. Copy it into the worker's `modules/` folder and configure the worker as the
next section describes. Partners are read when the module starts: after adding a partner, reload the
module.
## Run it under Tsak
Needs a Tsak worker 4.1.0, the version the module is built against; a 4.0.1 worker still recognises the
async `main`, while anything earlier skips the module without loading it.
`SerialNumbers.deploy/docker-compose.tsak.yml` runs the whole thing locally with the Tsak stack image, the
worker and its dashboard in one container. From the demo folder:
```bash
cp SerialNumbers.deploy/.env.example SerialNumbers.deploy/.env # fill in the four Tsak values
docker compose -f SerialNumbers.deploy/docker-compose.tsak.yml up -d sqlserver sftp
dotnet run --project SerialNumbers.Worker -- seed
pwsh SerialNumbers.deploy/pack-tpkg.ps1
docker compose -f SerialNumbers.deploy/docker-compose.tsak.yml up -d tsak
```
`.env` holds the worker's API secret, the dashboard's service key, the key's hash (the command that computes
it is in `.env.example`) and the dashboard's admin password; it stays out of Git. Copy a sample into
`runtime/sftp/acme/to-hub/`; the response arrives in `runtime/sftp/acme/from-hub/`. The dashboard is at
http://localhost:8085, the product API at http://localhost:8090. The ports are published on 127.0.0.1 only.
What the worker needs, whichever way you run it:
- **The worker's default redb runs on SQL Server.** The module uses the worker's default redb, the
unnamed one every route step gets through `ProcessWithRedb(...)`. The worker builds it from
`Tsak:Redb:Provider` (`mssql`, `postgres` or `sqlite`; the worker ships `sqlite`) and the matching
connection string, `ConnectionStrings:MSSql` for `mssql`. Set both `Tsak__Redb__Provider=mssql` and
`ConnectionStrings__MSSql`: the connection string alone leaves the provider on SQLite, and the module's
SQL Server script fails there with `near "IF": syntax error`. With `Tsak:Storage:Type=Redb`, as in the
compose file, Tsak keeps its own state in the same database, which is fine for this demo. The compose
file also sets `Tsak__Redb__PropsSaveStrategy=ChangeTracking`: a request is written several times over
its life, and this way each save writes only what changed instead of rewriting every property. It needs
the Pro tier, which is free and which `Tsak__Redb__UsePro=true` turns on.
- **The database exists before the first start.** redb creates its tables, not the database.
`SerialNumbers.Worker seed` creates it, together with the demo partners and products, the AS2
certificates and the ACME SFTP folders, which nothing else creates under Tsak. Without partners the
module starts with no inbound routes and files wait in the folder.
- **Addresses as the worker sees them.** Inside a container network the SFTP server is `sftp:22`, not
`localhost:2222`, and the certificate, archive and report folders are paths inside the container.
- **The AS2 partner is simulated only by the debug host.** Under Tsak, exchange files over SFTP.
Everything that differs per environment goes into `Tsak:Contexts:serial-numbers:Override`, usually as
environment variables of the worker (`SerialNumbers.deploy/.env.example`).
When a module does not start, the reason is the exception logged with `Failed to initialize module`; on a
4.0.0 worker it is the inner exception of a `TargetInvocationException`. A line saying the context started
with 0 endpoints right after it means the context is running without the module.
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Catalog/CatalogAuditDbContext.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Catalog/CatalogAuditDbContext.cs
----
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace SerialNumbers.Core.Catalog;
/// One row of the product status journal.
public sealed class ProductStatusChangeRecord
{
public long Id { get; set; }
public string Gtin { get; set; } = "";
public string FromStatus { get; set; } = "";
public string ToStatus { get; set; } = "";
public string ChangedBy { get; set; } = "";
public DateTime ChangedAt { get; set; }
}
///
/// The product status journal as an EF Core model: the part of a data model an existing application
/// keeps in EF Core, next to redb. The table itself is created by Database/schema.sql.
///
public sealed class CatalogAuditDbContext(DbContextOptions options) : DbContext(options)
{
public DbSet StatusChanges => Set();
///
/// A context on an open connection it does not own: disposing the context leaves the connection
/// to redb. Inside .Transacted() that connection is the one the route's transaction holds,
/// so what the context saves commits or rolls back together with the redb objects.
///
public static CatalogAuditDbContext On(DbConnection connection) =>
new(new DbContextOptionsBuilder()
.UseSqlServer(connection, contextOwnsConnection: false)
.Options);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(entity =>
{
entity.ToTable("product_status_changes", "dbo");
entity.HasKey(e => e.Id);
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Gtin).HasColumnName("gtin").HasMaxLength(14).IsUnicode(false);
entity.Property(e => e.FromStatus).HasColumnName("from_status").HasMaxLength(16).IsUnicode(false);
entity.Property(e => e.ToStatus).HasColumnName("to_status").HasMaxLength(16).IsUnicode(false);
entity.Property(e => e.ChangedBy).HasColumnName("changed_by").HasMaxLength(128);
entity.Property(e => e.ChangedAt).HasColumnName("changed_at");
});
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Catalog/ProductCatalog.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Catalog/ProductCatalog.cs
----
using Microsoft.EntityFrameworkCore;
using redb.Core;
using redb.Route.Abstractions;
using redb.Route.Http;
using SerialNumbers.Domain.Entities;
using SerialNumbers.Domain.Services;
namespace SerialNumbers.Core.Catalog;
///
/// A product's status change: the redb object and a row of the EF Core status journal, written in the
/// transaction the route opens with .Transacted().
///
public static class ProductCatalog
{
public static async Task ChangeStatusAsync(IRedbService redb, IExchange exchange, CancellationToken ct)
{
// EF Core joins the transaction through the connection redb holds for it. Outside a transaction
// the two writes would commit separately, so that is refused instead of silently allowed.
if (System.Transactions.Transaction.Current is null)
throw new InvalidOperationException("A product status change must run inside .Transacted().");
var gtin = exchange.In.GetHeader(SerialHeaders.Gtin) ?? "";
if (exchange.In.Body is not ProductStatusChange change || !ProductStatuses.IsKnown(change.Status))
{
Refuse(exchange, 400,
$"The status must be {ProductStatuses.Draft}, {ProductStatuses.Active} or {ProductStatuses.Obsolete}.");
return;
}
var product = await redb.Query()
.WhereRedb(o => o.ValueUnique == gtin)
.FirstOrDefaultAsync();
if (product is null)
{
Refuse(exchange, 404, $"There is no product with GTIN {gtin}.");
return;
}
await using var journal = CatalogAuditDbContext.On(await redb.Context.Db.GetUnderlyingConnectionAsync(ct));
if (product.Props.Status == change.Status)
{
// Nothing to write. Requests on hold are still on hold, so calling the API again retries a
// release that failed.
exchange.In.Headers[SerialHeaders.ProductChange] = ProductChangeOutcomes.Unchanged;
}
else
{
var record = new ProductStatusChangeRecord
{
Gtin = gtin,
FromStatus = product.Props.Status,
ToStatus = change.Status,
ChangedBy = string.IsNullOrWhiteSpace(change.ChangedBy) ? "api" : change.ChangedBy,
ChangedAt = DateTime.UtcNow,
};
product.Props.Status = change.Status;
await redb.SaveAsync(product, ct);
journal.StatusChanges.Add(record);
await journal.SaveChangesAsync(ct);
exchange.In.Headers[SerialHeaders.ProductChange] = ProductChangeOutcomes.Changed;
}
exchange.In.Headers[SerialHeaders.ProductStatus] = change.Status;
}
/// The answer of the API, once the requests on hold have been released.
public static void Respond(IExchange exchange) =>
exchange.In.Body = new ProductStatusResult(
exchange.In.GetHeader(SerialHeaders.Gtin)!,
exchange.In.GetHeader(SerialHeaders.ProductStatus)!,
exchange.In.GetHeader(SerialHeaders.ProductChange)!,
exchange.In.GetHeader(SerialHeaders.HeldCount));
private static void Refuse(IExchange exchange, int statusCode, string error)
{
exchange.In.Headers[SerialHeaders.ProductChange] = ProductChangeOutcomes.Refused;
exchange.In.Headers[HttpHeaders.ResponseCode] = statusCode;
exchange.In.Body = new ApiError(error);
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Catalog/ProductStatusApi.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Catalog/ProductStatusApi.cs
----
namespace SerialNumbers.Core.Catalog;
///
/// The body of PUT /api/products/{gtin}/status, for example
/// {"status":"Active","changedBy":"alice"}.
///
public sealed record ProductStatusChange(string Status, string? ChangedBy);
/// The answer to a status change.
/// One of .
/// Requests on hold sent through the request route again; 0 unless the product is active.
public sealed record ProductStatusResult(string Gtin, string Status, string Outcome, int RequestsReleased);
/// The answer to a refused status change: an unknown product or status.
public sealed record ApiError(string Error);
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Database/SqlScripts.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Database/SqlScripts.cs
----
namespace SerialNumbers.Core.Database;
/// SQL scripts compiled into the module as resources.
public static class SqlScripts
{
/// Creates the flat tables when they are missing. Safe to run on every start.
public static readonly string Schema = Load("schema.sql");
private static string Load(string fileName)
{
var name = $"{typeof(SqlScripts).Namespace}.{fileName}";
using var stream = typeof(SqlScripts).Assembly.GetManifestResourceStream(name)
?? throw new InvalidOperationException($"Embedded SQL script '{name}' was not found.");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Database/schema.sql
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/demo/SerialNumbersDemo/SerialNumbers.Core/Database/schema.sql
----
-- Flat tables of the demo, next to the redb tables in the same SQL Server database.
-- Business entities (partners, products, messages, requests, responses) are redb objects.
-- These tables hold what is volume rather than model: tens of thousands of serial numbers per
-- request, the yearly allocation ledger the quota is checked against, and the outbox. The product
-- status journal is the table of an EF Core model (Catalog/CatalogAuditDbContext.cs).
-- Every statement is idempotent: the module runs this script on each start.
-- GENERATE_SERIES, used by the allocation, needs SQL Server 2022 or later.
-- The next free block of serial values per product. Block b covers b * 10000 + 1 .. (b + 1) * 10000,
-- and every issued serial number takes one random value from a block of its own.
IF OBJECT_ID(N'dbo.serial_blocks', N'U') IS NULL
CREATE TABLE dbo.serial_blocks (
gtin varchar(14) NOT NULL PRIMARY KEY,
next_block bigint NOT NULL
);
IF OBJECT_ID(N'dbo.serial_allocations', N'U') IS NULL
CREATE TABLE dbo.serial_allocations (
id bigint IDENTITY(1, 1) PRIMARY KEY,
gtin varchar(14) NOT NULL,
partner_code nvarchar(64) NOT NULL,
request_id nvarchar(64) NOT NULL,
request_object_id bigint NOT NULL,
first_block bigint NOT NULL,
quantity int NOT NULL,
allocation_year int NOT NULL,
allocated_at datetime2 NOT NULL CONSTRAINT DF_serial_allocations_allocated_at DEFAULT SYSUTCDATETIME()
);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_serial_allocations_gtin_year')
CREATE INDEX IX_serial_allocations_gtin_year
ON dbo.serial_allocations (gtin, allocation_year) INCLUDE (quantity);
IF OBJECT_ID(N'dbo.serial_numbers', N'U') IS NULL
CREATE TABLE dbo.serial_numbers (
gtin varchar(14) NOT NULL,
serial_value bigint NOT NULL,
allocation_id bigint NOT NULL,
state varchar(16) NOT NULL CONSTRAINT DF_serial_numbers_state DEFAULT 'Allocated',
CONSTRAINT PK_serial_numbers PRIMARY KEY (gtin, serial_value)
);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_serial_numbers_allocation')
CREATE INDEX IX_serial_numbers_allocation ON dbo.serial_numbers (allocation_id) INCLUDE (serial_value);
IF OBJECT_ID(N'dbo.outbox', N'U') IS NULL
CREATE TABLE dbo.outbox (
id bigint IDENTITY(1, 1) PRIMARY KEY,
partner_code nvarchar(64) NOT NULL,
response_object_id bigint NOT NULL,
created_at datetime2 NOT NULL CONSTRAINT DF_outbox_created_at DEFAULT SYSUTCDATETIME(),
sent_at datetime2 NULL,
attempts int NOT NULL CONSTRAINT DF_outbox_attempts DEFAULT 0,
last_error nvarchar(2000) NULL
);
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_outbox_pending')
CREATE INDEX IX_outbox_pending ON dbo.outbox (id) WHERE sent_at IS NULL;
IF OBJECT_ID(N'dbo.product_status_changes', N'U') IS NULL
CREATE TABLE dbo.product_status_changes (
id bigint IDENTITY(1, 1) PRIMARY KEY,
gtin varchar(14) NOT NULL,
from_status varchar(16) NOT NULL,
to_status varchar(16) NOT NULL,
changed_by nvarchar(128) NOT NULL,
changed_at datetime2 NOT NULL
);
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Infrastructure/ExceptionRouteBuilder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Infrastructure/ExceptionRouteBuilder.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Core;
using redb.Route.RedbCore.Extensions;
using SerialNumbers.Core.Services;
namespace SerialNumbers.Core.Infrastructure;
///
/// Exception handlers for the whole context: an OnException declared in any route builder
/// wraps every route of the module.
///
/// Only for a failure whose right outcome is "take the message and record it": a handled
/// exception is a success for the consumer, so the SFTP file moves to .done and an AS2
/// sender gets a positive MDN. A catch-all OnException<Exception>().Handled(true)
/// is right for an HTTP API, where it turns any error into an error response, and wrong for
/// file and message consumers, where it would acknowledge a message the database never saw.
/// Technical failures are left unhandled on purpose: the transaction rolls back and the file
/// stays with the partner for the next poll.
///
///
public sealed class ExceptionRouteBuilder : RouteBuilder
{
protected override void Configure()
{
OnException()
.Handled(true)
.ProcessWithRedb(IntakeRecorder.RecordParkedAsync)
.Log("${header.serials.partner}: ${header.serials.fileName} parked, " +
"no route for message type ${header.serials.messageType}", LogLevel.Warning)
// The steps the message went through before it was parked, with their timings. Collected by
// .MessageHistory() on the intake and request routes; without a step that prints it the trace
// stays inside the exchange.
.Log(MessageHistory.Format, LogLevel.Warning);
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Infrastructure/UnsupportedMessageTypeException.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Infrastructure/UnsupportedMessageTypeException.cs
----
namespace SerialNumbers.Core.Infrastructure;
///
/// A well-formed message of a type this module has no route for (a production information file,
/// for example). Not a failure of the hub: the file is archived and parked for later.
///
public sealed class UnsupportedMessageTypeException : Exception
{
public UnsupportedMessageTypeException()
: base("The message type has no route in this module.")
{
}
public UnsupportedMessageTypeException(string message)
: base(message)
{
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/InitRoute.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/InitRoute.cs
----
using System.Data.Common;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Route.Abstractions;
using redb.Route.As2;
using redb.Route.Core;
using redb.Route.File;
using redb.Route.Http;
using redb.Route.Quartz;
using redb.Route.RedbCore.Extensions;
using redb.Route.Sftp;
using redb.Route.Sql;
using redb.Route.Sql.Connection;
using SerialNumbers.Core.Database;
using SerialNumbers.Core.Infrastructure;
using SerialNumbers.Core.Routes.Catalog;
using SerialNumbers.Core.Routes.Inbound;
using SerialNumbers.Core.Routes.Outbound;
using SerialNumbers.Core.Routes.Processing;
using SerialNumbers.Core.Routes.Reports;
using SerialNumbers.Core.Services;
using SerialNumbers.Domain.Entities;
using SerialNumbers.Domain.Services;
namespace SerialNumbers.Core;
///
/// Tsak module entry point. The worker finds it by convention (a public static class
/// InitRoute with a main(IRouteContext) method, synchronous or, as here, returning
/// Task<IRouteContext>) and awaits it when the module loads; the debug host
/// SerialNumbers.Worker calls the same method, so the route code exists once.
///
/// The order matters: components, then connections, then the database, then the routes. Partners
/// are read once here: each gets its own connection factory and its own inbound and delivery routes,
/// so a new partner is new data plus a module reload, not new code.
///
///
public static class InitRoute
{
public static async Task main(IRouteContext context)
{
var settings = ModuleSettings.FromContext(context);
var logger = context.GetService()?.CreateLogger("SerialNumbers");
var services = context.GetServiceProvider()
?? throw new InvalidOperationException("The route context has no service provider; redb is not available.");
// One HTTP server per port for the whole process, shared by the AS2 endpoints and the product API.
// The host registers it: the Tsak worker does, and so does the debug host (AddRedbRouteHttpHosting).
var httpServers = services.GetRequiredService();
context.AddComponent(new SftpComponent());
context.AddComponent(new FileComponent());
context.AddComponent(new SqlComponent());
context.AddComponent(new As2Component { ServerManager = httpServers });
if (!context.HasComponent("http"))
context.AddComponent(new HttpComponent { ServerManager = httpServers });
context.AddComponent(new CronComponent());
// The sql: component reads the outbox from the same database redb lives in.
DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance);
context.AddToRegistry(RegistryNames.SerialsDatabase, (ISqlConnectionFactory)new SqlConnectionFactory(
new SqlConnectionOptions
{
ConnectionString = settings.SqlConnectionString,
ProviderName = "Microsoft.Data.SqlClient",
}));
var partners = await PrepareDatabaseAsync(services);
RegisterPartnerConnections(context, settings, partners);
// Route builders run Configure() when the context starts and read the settings and the
// partners from the context there, so they take nothing through their constructors.
context.SetProperty(ContextProperties.Partners, partners);
var routes = (RouteContext)context;
routes.AddRoutes(new ExceptionRouteBuilder());
routes.AddRoutes(new SftpInboundRouteBuilder());
routes.AddRoutes(new As2InboundRouteBuilder());
routes.AddRoutes(new IntakeRouteBuilder());
routes.AddRoutes(new SerialNumberRequestRouteBuilder());
routes.AddRoutes(new ProductStatusRouteBuilder());
routes.AddRoutes(new ReleaseHeldRequestsRouteBuilder());
routes.AddRoutes(new OutboxRouteBuilder());
routes.AddRoutes(new DeliveryRouteBuilder());
routes.AddRoutes(new QuotaReportRouteBuilder());
logger?.LogInformation("SerialNumbers module ready: {Partners} partners, archive at {Archive}, product API on port {ApiPort}",
partners.Count, settings.ArchiveDirectory, settings.ApiPort);
return context;
}
///
/// Schemes, flat tables and the partner list, through a scope of our own: the bootstrap
/// connection goes back to the pool as soon as this is done instead of staying checked out for
/// the life of the context.
///
/// The here, like the one every ProcessWithRedb step gets, is the
/// host's default redb, registered in its DI container. Under Tsak its provider is
/// Tsak:Redb:Provider; the schema script below is T-SQL, so the worker runs it on mssql.
///
///
private static async Task> PrepareDatabaseAsync(IServiceProvider services)
{
await using var scope = services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
await redb.SyncSchemeAsync();
await redb.SyncSchemeAsync();
await redb.SyncSchemeAsync();
await redb.SyncSchemeAsync();
await redb.SyncSchemeAsync();
await redb.Context.ExecuteAsync(SqlScripts.Schema);
var partners = await redb.Query().ToListAsync();
return partners.Select(o => o.Props).ToList();
}
/// One named connection factory per partner. Routes reference it by the partner code.
private static void RegisterPartnerConnections(IRouteContext context, ModuleSettings settings, IReadOnlyList partners)
{
var hubCertificate = partners.Any(p => p.Transport == Transports.As2)
? As2Certificates.LoadHub(settings.As2CertificateDirectory, settings.As2CertificatePassword)
: null;
foreach (var partner in partners)
{
if (partner.Transport == Transports.As2)
{
context.AddToRegistry(partner.Code, new As2ConnectionFactory
{
OurCertificate = hubCertificate,
PartnerCertificate = As2Certificates.LoadPartner(settings.As2CertificateDirectory, partner.Code),
As2From = settings.As2HubId,
As2To = partner.As2Id!,
PartnerUrl = partner.As2Url!,
Sign = true,
Encrypt = true,
SignedMdn = true,
MdnMode = As2MdnMode.Sync,
RequireValidMdn = true,
});
}
else
{
context.AddToRegistry(partner.Code, new SftpConnectionFactory
{
Host = settings.SftpHost,
Port = settings.SftpPort,
Username = settings.SftpUsername,
Password = settings.SftpPasswordFor(partner.Code),
});
}
}
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/SerialNumberRequest.xsd
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/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/SerialNumberRequest.xsd
----
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/SerialNumberRequestXml.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/SerialNumberRequestXml.cs
----
using System.Xml.Serialization;
namespace SerialNumbers.Core.Integration.Xml;
///
/// The wire format of a serial number request, exactly as the partner sends it.
/// Validated against SerialNumberRequest.xsd before it is deserialized.
///
[XmlRoot("SerialNumberRequest")]
public sealed class SerialNumberRequestXml
{
[XmlElement("RequestId")]
public string RequestId { get; set; } = "";
[XmlElement("Gtin")]
public string Gtin { get; set; } = "";
[XmlElement("Quantity")]
public int Quantity { get; set; }
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/SerialNumberResponseXml.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/SerialNumberResponseXml.cs
----
using System.Xml.Serialization;
namespace SerialNumbers.Core.Integration.Xml;
/// The wire format of the response sent back to the partner.
[XmlRoot("SerialNumberResponse")]
public sealed class SerialNumberResponseXml
{
[XmlElement("RequestId")]
public string RequestId { get; set; } = "";
[XmlElement("Gtin")]
public string Gtin { get; set; } = "";
/// Accepted or Rejected.
[XmlElement("Status")]
public string Status { get; set; } = "";
[XmlElement("Reason")]
public string? Reason { get; set; }
[XmlElement("Quantity")]
public int Quantity { get; set; }
/// Every issued serial number, twelve digits each. Empty for a rejection.
[XmlArray("SerialNumbers")]
[XmlArrayItem("SerialNumber")]
public List SerialNumbers { get; set; } = [];
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/XmlMessageInspector.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/XmlMessageInspector.cs
----
using System.Xml;
namespace SerialNumbers.Core.Integration.Xml;
/// Reads just enough of an incoming file to route it.
public static class XmlMessageInspector
{
private static readonly XmlReaderSettings Settings = new()
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
IgnoreWhitespace = true,
};
///
/// The local name of the root element, or null when the content is not well-formed
/// XML. The null is the answer, not a lost error: the intake route records such a file
/// as Invalid, with this reason, and keeps it in the archive.
///
/// The whole document is read, not just its start: a file cut off at the end has a perfectly
/// good root element, and only reading to the last byte tells it from a valid one.
///
///
public static string? RootElementName(string? content)
{
if (string.IsNullOrWhiteSpace(content))
return null;
try
{
using var reader = XmlReader.Create(new StringReader(content), Settings);
if (reader.MoveToContent() != XmlNodeType.Element)
return null;
var root = reader.LocalName;
while (reader.Read())
{
}
return root;
}
catch (XmlException)
{
return null;
}
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/XmlSchemas.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Integration/Xml/XmlSchemas.cs
----
namespace SerialNumbers.Core.Integration.Xml;
/// The XSD schemas of the partner messages, compiled into the module as resources.
public static class XmlSchemas
{
public static readonly string SerialNumberRequest = Load("SerialNumberRequest.xsd");
private static string Load(string fileName)
{
var name = $"{typeof(XmlSchemas).Namespace}.{fileName}";
using var stream = typeof(XmlSchemas).Assembly.GetManifestResourceStream(name)
?? throw new InvalidOperationException($"Embedded schema '{name}' was not found.");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/ModuleSettings.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/ModuleSettings.cs
----
using System.Globalization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
namespace SerialNumbers.Core;
///
/// Everything the module needs from outside, read once when the module loads.
///
/// Settings come from the route context. The Tsak worker merges Tsak:Contexts:default,
/// Tsak:Contexts:{context}, this module's SerialNumbers.Core.config.json and
/// Tsak:Contexts:{context}:Override, and sets every root key as a context property; a section
/// arrives as a dictionary.
/// Passwords arrive the same way, through the Override layer: environment variables on the
/// worker such as Tsak__Contexts__serial-numbers__Override__Sftp__Password. They are never
/// written into the config file that ships with the module.
/// The connection string is the worker's own ConnectionStrings:MSSql, the one its default
/// redb uses when Tsak:Redb:Provider is mssql: the flat tables live in the database redb
/// lives in, so it is configured in one place.
///
///
public sealed record ModuleSettings(
string SqlConnectionString,
string ArchiveDirectory,
string SftpHost,
int SftpPort,
string SftpUsername,
string SftpPassword,
IDictionary? SftpPartnerPasswords,
int As2ReceivePort,
string As2HubId,
string As2CertificateDirectory,
string As2CertificatePassword,
string ReportDirectory,
string ReportSchedule,
string ReportTimeZone,
int ApiPort)
{
/// The connection string of the worker's redb database.
public const string ConnectionStringName = "MSSql";
public static ModuleSettings FromContext(IRouteContext context)
{
var config = new ContextSections(context);
var archive = config.Section("Archive");
var sftp = config.Section("Sftp");
var as2 = config.Section("As2");
var report = config.Section("Report");
var api = config.Section("Api");
var configuration = context.GetService()
?? context.GetServiceProvider()?.GetService()
?? throw new InvalidOperationException("The route context has no IConfiguration; the connection string cannot be read.");
return new(
SqlConnectionString: configuration.GetConnectionString(ConnectionStringName)
?? throw new InvalidOperationException($"ConnectionStrings:{ConnectionStringName} is not set on the worker."),
ArchiveDirectory: FullPath(config.Value(archive, "Archive", "Directory")),
SftpHost: config.Value(sftp, "Sftp", "Host"),
SftpPort: int.Parse(config.Value(sftp, "Sftp", "Port"), CultureInfo.InvariantCulture),
SftpUsername: config.Value(sftp, "Sftp", "Username"),
SftpPassword: config.Value(sftp, "Sftp", "Password"),
SftpPartnerPasswords: sftp.TryGetValue("Passwords", out var own) ? own as IDictionary : null,
As2ReceivePort: int.Parse(config.Value(as2, "As2", "ReceivePort"), CultureInfo.InvariantCulture),
As2HubId: config.Value(as2, "As2", "Id"),
As2CertificateDirectory: FullPath(config.Value(as2, "As2", "CertificateDirectory")),
As2CertificatePassword: config.Value(as2, "As2", "CertificatePassword"),
ReportDirectory: FullPath(config.Value(report, "Report", "Directory")),
// Quartz cron format: seconds first.
ReportSchedule: config.Value(report, "Report", "Cron"),
// The zone the schedule is read in: an IANA id such as Europe/Berlin.
ReportTimeZone: config.Value(report, "Report", "TimeZone"),
// The port of the product API (REST).
ApiPort: int.Parse(config.Value(api, "Api", "Port"), CultureInfo.InvariantCulture));
}
///
/// The SFTP password for one partner: Sftp:Passwords:{code} when it is set, the shared
/// Sftp:Password otherwise. In the demo every partner lives on the same SFTP server; in
/// production each partner usually has its own server and credentials.
///
public string SftpPasswordFor(string partnerCode) =>
SftpPartnerPasswords is not null
&& SftpPartnerPasswords.TryGetValue(partnerCode, out var own)
&& Convert.ToString(own, CultureInfo.InvariantCulture) is { Length: > 0 } password
? password
: SftpPassword;
/// Relative paths resolve against the worker's current directory.
private static string FullPath(string path) => Path.GetFullPath(path).Replace('\\', '/');
private sealed class ContextSections(IRouteContext context)
{
public IDictionary Section(string name) =>
context.GetProperty>(name)
?? throw Missing(name);
public string Value(IDictionary section, string sectionName, string key) =>
section.TryGetValue(key, out var value) && Convert.ToString(value, CultureInfo.InvariantCulture) is { Length: > 0 } text
? text
: throw Missing($"{sectionName}:{key}");
private InvalidOperationException Missing(string key) => new(
$"{key} is not configured for context '{context.ContextId}': set it in SerialNumbers.Core.config.json, " +
$"or, for a secret or a value of one environment, in Tsak:Contexts:{context.ContextId}:Override.");
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Names.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Names.cs
----
using redb.Route.Abstractions;
using SerialNumbers.Domain.Entities;
namespace SerialNumbers.Core;
/// Exchange headers the routes of this module set and read.
public static class SerialHeaders
{
public const string Partner = "serials.partner";
public const string Transport = "serials.transport";
public const string FileName = "serials.fileName";
public const string ArchivePath = "serials.archivePath";
/// Root element of the XML; absent when the file is not well-formed XML.
public const string MessageType = "serials.messageType";
public const string RequestId = "serials.requestId";
///
/// Set by the request registration: Accepted, Rejected or OnHold, or
/// when a release finds the request decided already.
///
public const string Decision = "serials.decision";
///
/// The object id of a request on hold whose archived file is sent through the request route again.
/// Absent for a file a partner delivered.
///
public const string ReleaseOf = "serials.releaseOf";
/// File name of the quota report, stamped with the time the schedule fired.
public const string ReportFileName = "serials.reportFileName";
/// The GTIN in the path of the product API, /api/products/{gtin}/status.
public const string Gtin = "gtin";
/// The status a product has after the status change.
public const string ProductStatus = "serials.productStatus";
/// One of .
public const string ProductChange = "serials.productChange";
/// How many requests on hold a product activation found.
public const string HeldCount = "serials.heldCount";
}
/// Exchange properties that carry redb objects between the steps of one transaction.
public static class SerialProperties
{
public const string Request = "serials.request";
public const string Response = "serials.response";
}
/// Internal endpoints that join the routes of the module.
public static class RouteUris
{
public const string Intake = "direct:intake";
public const string SerialNumberRequest = "direct:serial-number-request";
/// Changes a product's status: called by the REST API and by the debug host's console.
public const string SetProductStatus = "direct:set-product-status";
public const string ReleaseHeldRequests = "direct:release-held-requests";
public static string Delivery(string partnerCode) => $"direct:deliver-{partnerCode}";
/// as a template resolved per exchange from the outbox row.
public const string DeliveryForOutboxRow = "direct:deliver-${header.partner_code}";
}
/// What a status change did.
public static class ProductChangeOutcomes
{
public const string Changed = "Changed";
public const string Unchanged = "Unchanged";
/// Unknown product or status: answered with an error, nothing written.
public const string Refused = "Refused";
}
/// Outcomes of the request route that are not a decision on the request.
public static class ReleaseOutcomes
{
/// A release found the request no longer on hold: a concurrent release got there first.
public const string AlreadyDecided = "AlreadyDecided";
}
///
/// Properties the module adds to its route context, next to the configuration Tsak put there. Route
/// builders read both in Configure() through Context.
///
public static class ContextProperties
{
/// The partners read from redb when the module loads; inbound and delivery routes are built per partner.
public const string Partners = "serials.partners";
public static IReadOnlyList PartnersOf(IRouteContext context) =>
context.GetProperty>(Partners)
?? throw new InvalidOperationException("The partner list is not in the route context; InitRoute.main puts it there before the routes are built.");
}
/// Names of the objects registered in the route context registry.
public static class RegistryNames
{
/// The sql: data source: the same SQL Server database redb lives in.
public const string SerialsDatabase = "serials";
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Catalog/ProductStatusRouteBuilder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Catalog/ProductStatusRouteBuilder.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http.Rest;
using redb.Route.RedbCore.Extensions;
using SerialNumbers.Core.Catalog;
namespace SerialNumbers.Core.Routes.Catalog;
///
/// Changing a product's status, from a web page or from code in the same process.
///
/// A web UI calls PUT /api/products/{gtin}/status with {"status":"Active","changedBy":"alice"}.
/// The REST DSL turns the path parameter into the gtin header, binds the JSON body to
/// and serves an OpenAPI document at /api/products/openapi.json.
/// Code in the same process sends the same message to direct:set-product-status with a
/// ProducerTemplate, as the debug host's console does.
///
/// The redb product and the row of the EF Core status journal are written in one transaction. Only after
/// it commits are the requests on hold released, each in a transaction of its own.
///
public sealed class ProductStatusRouteBuilder : RouteBuilder
{
protected override void Configure()
{
var settings = ModuleSettings.FromContext(Context!);
this.Rest("/api/products", o => { o.Port = settings.ApiPort; o.BindingMode = RestBindingMode.Json; })
.Put("/{gtin}/status").Consumes("application/json").Type()
.To(RouteUris.SetProductStatus);
From(RouteUris.SetProductStatus)
.RouteId("set-product-status")
.Transacted()
.ProcessWithRedb(ProductCatalog.ChangeStatusAsync)
.EndTransaction()
.Choice()
.When(e => e.In.GetHeader(SerialHeaders.ProductChange) == ProductChangeOutcomes.Refused)
.Log("Product status change for ${header.gtin} refused: ${body}", LogLevel.Warning)
.Otherwise()
.Log("${header.gtin}: product status ${header.serials.productStatus} (${header.serials.productChange})")
.To(RouteUris.ReleaseHeldRequests)
.Process(e => ProductCatalog.Respond(e))
.EndChoice();
}
}
Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Catalog/ReleaseHeldRequestsRouteBuilder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Catalog/ReleaseHeldRequestsRouteBuilder.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.RedbCore.Extensions;
using SerialNumbers.Core.Services;
namespace SerialNumbers.Core.Routes.Catalog;
///
/// Releases the requests that waited for a product to be activated. The partner sends nothing again:
/// each request's file is read back from the archive and goes through the request route, where the
/// request is decided against the product and the quota as they are now.
///
/// One request at a time, each in the request route's own transaction. A request that was released is
/// no longer on hold, so a second activation call finds nothing to release. A failure stops the batch
/// and reaches the caller; the requests not released stay on hold, and calling the API again releases
/// them.
///
///
public sealed class ReleaseHeldRequestsRouteBuilder : RouteBuilder
{
protected override void Configure()
{
var settings = ModuleSettings.FromContext(Context!);
From(RouteUris.ReleaseHeldRequests)
.RouteId("release-held-requests")
.ProcessWithRedb(HeldRequests.FindAsync)
.Log("${header.gtin}: ${header.serials.heldCount} request(s) on hold to release")
.Split(e => (IEnumerable