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.0 enable enable false 4.3.0 false 10.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-0001 04607001234567 Accepted 30000 000000007315 000000012094 ... ``` ## 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)e.In.Body!) .Process((e, ct) => HeldRequests.LoadArchivedFileAsync(e, settings.ArchiveDirectory, ct)) .Log("${header.serials.partner}: releasing request ${header.serials.requestId} from ${header.serials.archivePath}") .To(RouteUris.SerialNumberRequest) .EndSplit(); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Inbound/As2InboundRouteBuilder.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/Inbound/As2InboundRouteBuilder.cs ---- using redb.Route.As2; using redb.Route.As2.Fluent; using redb.Route.Core; using SerialNumbers.Core.Services; using SerialNumbers.Domain.Entities; using SerialNumbers.Domain.Services; namespace SerialNumbers.Core.Routes.Inbound; /// /// One AS2 receive endpoint per AS2 partner, all on one port and told apart by the path. The /// connector decrypts and verifies the message against the partner's certificates and answers /// with a signed MDN: positive when the route completes, negative when it fails, so a partner /// whose message could not be stored knows to send it again. /// public sealed class As2InboundRouteBuilder : RouteBuilder { protected override void Configure() { var settings = ModuleSettings.FromContext(Context!); foreach (var partner in ContextProperties.PartnersOf(Context!).Where(p => p.Transport == Transports.As2)) { var code = partner.Code; From(As2.Receive($"/as2/{code}") .Host("0.0.0.0") .Port(settings.As2ReceivePort) .ConnectionFactory(code)) // certificates and the agreed profile live in the registry .RouteId($"as2-inbound-{code}") .SetHeader(SerialHeaders.Partner, code) .SetHeader(SerialHeaders.Transport, Transports.As2) .SetHeader(SerialHeaders.FileName, e => ArchivePaths.FromAs2MessageId(e.In.GetHeader(As2Headers.MessageId))) .Log("${header.serials.partner}: received ${header.serials.fileName} over AS2") .To(RouteUris.Intake); } } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Inbound/SftpInboundRouteBuilder.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/Inbound/SftpInboundRouteBuilder.cs ---- using redb.Route.Core; using redb.Route.Sftp; using SerialNumbers.Domain.Entities; using SerialNumbers.Domain.Services; namespace SerialNumbers.Core.Routes.Inbound; /// /// One SFTP consumer per partner that exchanges files over SFTP. The route only receives: it names /// the partner, identifies the file and hands it to the common intake. /// public sealed class SftpInboundRouteBuilder : RouteBuilder { protected override void Configure() { foreach (var partner in ContextProperties.PartnersOf(Context!).Where(p => p.Transport == Transports.Sftp)) { var code = partner.Code; // One consumer per partner, because a partner is a separate host and account. Several // directories of ONE partner are a different matter: do not add a route per directory, since // each one holds its own connection and partners often allow a single concurrent session. // Poll their common parent instead and let the path filters pick the directories out: // .Recursive().AntInclude("TYPE_A/outbox/*.xml,TYPE_B/outbox/*.xml") // FilterDirectory decides per directory before it is listed, so the ones left out cost nothing. From(Sftp.Directory(partner.SftpInboundFolder!) .ConnectionFactory(code) // host and credentials live in the registry, not here .Include("*.xml") .Delay(2000) .MoveTo(".done") // after success only; a failed file stays for the next poll // Poll less often while failures repeat: after three failed polls in a row the next ten // are skipped. A poll fails when the server cannot be reached and, with // BackoffOnFailedExchanges, also when every file it picked up failed, as it does // while the database is down. .BackoffErrorThreshold(3) .BackoffMultiplier(10) .BackoffOnFailedExchanges()) .RouteId($"sftp-inbound-{code}") .SetHeader(SerialHeaders.Partner, code) .SetHeader(SerialHeaders.Transport, Transports.Sftp) .SetHeader(SerialHeaders.FileName, Header(SftpHeaders.FileName)) .Log() .Message("${header.serials.partner}: received ${header.serials.fileName} over SFTP") .Header(SftpHeaders.FileLength) .EndLog() .To(RouteUris.Intake); } } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Outbound/DeliveryRouteBuilder.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/Outbound/DeliveryRouteBuilder.cs ---- using redb.Route.As2.Fluent; using redb.Route.Core; using redb.Route.Sftp; using SerialNumbers.Domain.Entities; using SerialNumbers.Domain.Services; namespace SerialNumbers.Core.Routes.Outbound; /// /// One delivery endpoint per partner, over the transport the partner agreed on. The outbox route /// does not know how a partner is reached; it calls direct:deliver-{partner}. /// public sealed class DeliveryRouteBuilder : RouteBuilder { protected override void Configure() { foreach (var partner in ContextProperties.PartnersOf(Context!)) { var route = From(RouteUris.Delivery(partner.Code)).RouteId($"deliver-{partner.Code}"); if (partner.Transport == Transports.As2) { // Signed, encrypted, and the partner's signed MDN must confirm it (RequireValidMdn). route.To(As2.Send(partner.As2Url!).ConnectionFactory(partner.Code)); } else { // Written under a temporary name and renamed when complete, so the partner never // picks up a half-written file. route.To(Sftp.Directory(partner.SftpOutboundFolder!) .ConnectionFactory(partner.Code) .FileName("${header.serials.fileName}") .TempFileName("${header.serials.fileName}.part")); } } } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Outbound/OutboxRouteBuilder.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/Outbound/OutboxRouteBuilder.cs ---- using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Route.Sql; using SerialNumbers.Core.Services; namespace SerialNumbers.Core.Routes.Outbound; /// /// Delivers queued responses. The sql: consumer polls the outbox; every row is one exchange. /// /// A delivered row is marked sent; a failed one counts the attempt and keeps the error, and is tried /// again on the next poll, up to ten times. The row is marked after the delivery, so a crash between /// the two sends the file once more: at-least-once, the partner recognises a repeat by the file name. /// /// public sealed class OutboxRouteBuilder : RouteBuilder { protected override void Configure() { From(Sql.Poll("SELECT TOP (20) id, partner_code, response_object_id FROM dbo.outbox " + "WHERE sent_at IS NULL AND attempts < 10 ORDER BY id") .DataSource(Constant(RegistryNames.SerialsDatabase)) .Delay(2000) .OnSuccess("UPDATE dbo.outbox SET sent_at = SYSUTCDATETIME(), attempts = attempts + 1, last_error = NULL WHERE id = :#id") .OnFailure("UPDATE dbo.outbox SET attempts = attempts + 1, last_error = LEFT(:#redbError, 2000) WHERE id = :#id")) .RouteId("outbox") .ProcessWithRedb(ResponseRenderer.RenderAsync) .Marshal("application/xml") .ToD(RouteUris.DeliveryForOutboxRow) .Log("${header.partner_code}: delivered ${header.serials.fileName}"); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Processing/IntakeRouteBuilder.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/Processing/IntakeRouteBuilder.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.File; using redb.Route.RedbCore.Extensions; using SerialNumbers.Core.Infrastructure; using SerialNumbers.Core.Integration.Xml; using SerialNumbers.Core.Services; namespace SerialNumbers.Core.Routes.Processing; /// /// The common intake for every transport: archive the raw file first, then route it by what it is. /// public sealed class IntakeRouteBuilder : RouteBuilder { protected override void Configure() { var settings = ModuleSettings.FromContext(Context!); From(RouteUris.Intake) .RouteId("intake") .MessageHistory() .ConvertBody() // The raw copy goes to the archive before anything can fail on its content. .SetHeader(SerialHeaders.ArchivePath, e => ArchivePaths.For( e.In.GetHeader(SerialHeaders.Partner)!, e.In.GetHeader(SerialHeaders.FileName)!, DateTimeOffset.UtcNow)) .To(FileDsl.Write(settings.ArchiveDirectory).FileName("${header.serials.archivePath}")) .Log("${header.serials.partner}: ${header.serials.fileName} archived as ${header.serials.archivePath}") .SetHeader(SerialHeaders.MessageType, e => XmlMessageInspector.RootElementName(e.In.Body as string)) .Choice() .When(e => e.In.GetHeader(SerialHeaders.MessageType) is null) .ProcessWithRedb(IntakeRecorder.RecordInvalidAsync) .Log("${header.serials.partner}: ${header.serials.fileName} is not well-formed XML, recorded as Invalid", LogLevel.Warning) .When(XPath("/SerialNumberRequest")) .Log("${header.serials.partner}: ${header.serials.fileName} is a serial number request") .To(RouteUris.SerialNumberRequest) .Otherwise() // Handled context-wide by ExceptionRouteBuilder: archived, recorded, parked. .ThrowException("The message type has no route in this module.") .EndChoice(); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Processing/SerialNumberRequestRouteBuilder.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/Processing/SerialNumberRequestRouteBuilder.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Route.Validation; using SerialNumbers.Core.Integration.Xml; using SerialNumbers.Core.Services; using SerialNumbers.Domain.Services; namespace SerialNumbers.Core.Routes.Processing; /// /// A serial number request from validation to a queued response. /// /// Schema and deserialization in DoTry: a schema violation is the partner's error, recorded /// as Invalid and closed. The file is archived, nothing is retried. /// One transaction, .Transacted(), for everything the request writes: the message record, /// the request, the serial numbers, the response and the outbox row. A repeated delivery needs no /// separate registry of processed files: the request carries the partner's request id as its unique /// key, so the second one is answered as a duplicate and a delivery that rolled back leaves no trace /// and is processed again. /// The business decision is a branch, not an exception: a rejection is a normal answer, and a /// request for a draft product waits on hold with nothing sent. /// /// A technical failure (database, network) is not handled here on purpose: the transaction rolls back, /// the consumer sees the failure, and the file stays in the partner folder for the next poll. /// public sealed class SerialNumberRequestRouteBuilder : RouteBuilder { protected override void Configure() { From(RouteUris.SerialNumberRequest) .RouteId("serial-number-request") // Every step is timed; when a message fails, the log shows the path it took. .MessageHistory() .DoTry() .ValidateXsd(XmlSchemas.SerialNumberRequest) .Unmarshal("application/xml") .DoCatch() .ProcessWithRedb(IntakeRecorder.RecordInvalidAsync) .Log("${header.serials.partner}: ${header.serials.fileName} violates the schema, recorded as Invalid", LogLevel.Warning) .Stop() .EndTryCatch() .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() // Logged after the commit: the line says what has happened, not what was about to. .Choice() .When(e => DecisionOf(e) == MessageStatuses.OnHold) .Log("${header.serials.partner}: request ${header.serials.requestId} is on hold until its product is activated") .When(e => DecisionOf(e) == ReleaseOutcomes.AlreadyDecided) .Log("${header.serials.partner}: request ${header.serials.requestId} was decided by another release, nothing to do") .Otherwise() .Log("${header.serials.partner}: request ${header.serials.requestId} ${header.serials.decision}, response queued") .EndChoice() // The path the request took, step by step, with timings. Collected by .MessageHistory() above // and printed here, at Debug: raise the level of this module to see it for every request. .Log(MessageHistory.Format, LogLevel.Debug); } private static string? DecisionOf(IExchange exchange) => exchange.In.GetHeader(SerialHeaders.Decision); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Routes/Reports/QuotaReportRouteBuilder.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/Reports/QuotaReportRouteBuilder.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.File; using redb.Route.Quartz; using redb.Route.RedbCore.Extensions; using redb.Route.Sql; using SerialNumbers.Core.Services; namespace SerialNumbers.Core.Routes.Reports; /// /// A route nothing has to arrive for: Quartz fires it on a cron schedule. Each run sums this year's /// allocation ledger per product, sets it against the product's annual quota and writes a CSV file. /// /// Stateful() keeps two runs from overlapping when one takes longer than the interval. The /// schedule is read in , so "06:00" means the same hour on /// every server, whatever its local clock says. /// /// public sealed class QuotaReportRouteBuilder : RouteBuilder { protected override void Configure() { var settings = ModuleSettings.FromContext(Context!); From(Cron.Schedule("reports/quota-usage", settings.ReportSchedule) .TimeZone(settings.ReportTimeZone) .Stateful()) .RouteId("quota-report") .To(Sql.Execute("SELECT gtin, COUNT(*) AS requests, SUM(CAST(quantity AS bigint)) AS issued " + "FROM dbo.serial_allocations WHERE allocation_year = YEAR(SYSUTCDATETIME()) " + "GROUP BY gtin ORDER BY gtin") .DataSource(Constant(RegistryNames.SerialsDatabase))) .Choice() .When(e => e.In.GetHeader(SqlHeaders.RowCount) == 0) .Log("Quota report skipped: nothing allocated this year") .Otherwise() .ProcessWithRedb(QuotaReport.RenderCsvAsync) .SetHeader(SerialHeaders.ReportFileName, _ => $"quota_usage_{DateTime.UtcNow:yyyyMMdd_HHmmss}.csv") .To(FileDsl.Write(settings.ReportDirectory).FileName("${header.serials.reportFileName}")) .Log("Quota report written: ${header.serials.reportFileName}") .EndChoice(); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/SerialNumbers.Core.config.json 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/SerialNumbers.Core.config.json ---- { "ContextName": "serial-numbers", "AutoStart": true, "Archive": { "Directory": "data/serials/archive" }, "Sftp": { "Host": "localhost", "Port": 22, "Username": "serials" }, "As2": { "Id": "SERIALS-HUB", "ReceivePort": 4080, "CertificateDirectory": "data/serials/certs" }, "Api": { "Port": 8090 }, "Report": { "Directory": "data/serials/reports", "Cron": "0 0 6 * * ?", "TimeZone": "UTC" } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/SerialNumbers.Core.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/SerialNumbers.Core.csproj ---- SerialNumbers.Core Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/ArchivePaths.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/Services/ArchivePaths.cs ---- namespace SerialNumbers.Core.Services; /// Names of files in the archive and in partner folders. public static class ArchivePaths { /// /// {partner}/{yyyy}/{MM}/{dd}/{HHmmssfff}_{file}. The time prefix keeps every delivery, /// including a partner re-sending a file under the same name: nothing is ever overwritten. /// public static string For(string partnerCode, string fileName, DateTimeOffset receivedAt) => $"{Safe(partnerCode)}/{receivedAt:yyyy}/{receivedAt:MM}/{receivedAt:dd}/{receivedAt:HHmmssfff}_{Safe(fileName)}"; /// A file name for a message that arrived over AS2 and has none: its Message-ID. public static string FromAs2MessageId(string? messageId) => Safe(string.IsNullOrWhiteSpace(messageId) ? Guid.NewGuid().ToString("N") : messageId.Trim('<', '>')) + ".xml"; /// /// SNRESP_{requestId}_{responseId}.xml. The request id alone is not enough: a partner that /// sends a request id twice gets two responses, and the rejection of the repeat must not overwrite /// the original acceptance. A delivery retried from the outbox keeps its name. /// public static string ResponseFileName(string requestId, long responseObjectId) => $"SNRESP_{Safe(requestId)}_{responseObjectId}.xml"; private static string Safe(string value) => string.Concat(value.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_' ? c : '_')); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/As2Certificates.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/Services/As2Certificates.cs ---- using System.Security.Cryptography.X509Certificates; namespace SerialNumbers.Core.Services; /// /// AS2 key material from a directory: hub.pfx is the hub's own certificate with its private /// key (signs what we send, decrypts what we receive), {partner}.cer is each partner's /// public certificate (encrypts what we send, verifies what we receive). /// public static class As2Certificates { public static X509Certificate2 LoadHub(string directory, string password) => X509CertificateLoader.LoadPkcs12FromFile( Path.Combine(directory, "hub.pfx"), password, X509KeyStorageFlags.Exportable); public static X509Certificate2 LoadPartner(string directory, string partnerCode) => X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, $"{partnerCode}.cer")); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/HeldRequests.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/Services/HeldRequests.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using SerialNumbers.Domain.Entities; using SerialNumbers.Domain.Services; namespace SerialNumbers.Core.Services; /// A request on hold, with what it takes to send its archived file through the request route again. public sealed record HeldRequest( long RequestObjectId, string RequestId, string PartnerCode, string Transport, string FileName, string MessageType, string ArchivePath); /// /// Releasing requests on hold when their product becomes active. Nothing is asked of the partner: the file /// they sent is in the archive, and it goes through the request route once more. /// public static class HeldRequests { /// The requests on hold for the product in the exchange, when the product is now active. public static async Task FindAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { var held = new List(); if (exchange.In.GetHeader(SerialHeaders.ProductStatus) == ProductStatuses.Active) { var gtin = exchange.In.GetHeader(SerialHeaders.Gtin)!; var requests = await redb.Query() .Where(r => r.Gtin == gtin && r.Status == MessageStatuses.OnHold) .ToListAsync(); if (requests.Count > 0) { // The inbound messages of all of them in one query, not one per request. var messageIds = requests.Select(MessageIdOf).ToHashSet(); var messages = await redb.Query() .WhereRedb(o => messageIds.Contains(o.Id)) .ToListAsync(); var messageById = messages.ToDictionary(m => m.Id, m => m.Props); foreach (var request in requests.OrderBy(r => r.Id)) { var message = messageById[MessageIdOf(request)]; held.Add(new HeldRequest( request.Id, request.Props.RequestId, message.PartnerCode, message.Transport, message.FileName, message.MessageType ?? "", message.ArchivePath)); } } } exchange.In.Body = held; exchange.In.Headers[SerialHeaders.HeldCount] = held.Count; } /// /// Puts the archived file of one request on hold into the exchange, with the headers the inbound /// routes set for a delivered file, and marks it as the release of that request. /// public static async Task LoadArchivedFileAsync(IExchange exchange, string archiveDirectory, CancellationToken ct) { var held = (HeldRequest)exchange.In.Body!; exchange.In.Body = await File.ReadAllTextAsync(Path.Combine(archiveDirectory, held.ArchivePath), ct); var headers = exchange.In.Headers; headers[SerialHeaders.Partner] = held.PartnerCode; headers[SerialHeaders.Transport] = held.Transport; headers[SerialHeaders.FileName] = held.FileName; headers[SerialHeaders.MessageType] = held.MessageType; headers[SerialHeaders.ArchivePath] = held.ArchivePath; headers[SerialHeaders.RequestId] = held.RequestId; headers[SerialHeaders.ReleaseOf] = held.RequestObjectId; } private static long MessageIdOf(RedbObject request) => request.Props.Message?.Id ?? throw new InvalidOperationException($"Request object {request.Id} has no inbound message."); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/IntakeRecorder.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/Services/IntakeRecorder.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using SerialNumbers.Domain.Entities; using SerialNumbers.Domain.Services; namespace SerialNumbers.Core.Services; /// Writes the record of a delivered file. public static class IntakeRecorder { /// The file is broken XML or violates the schema. public static async Task RecordInvalidAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { var reason = exchange.Exception?.Message ?? "The file is not well-formed XML."; await redb.SaveAsync(Create(exchange, MessageStatuses.Invalid, reason), ct); } /// A well-formed message this module has no route for. public static async Task RecordParkedAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { var type = exchange.In.GetHeader(SerialHeaders.MessageType); await redb.SaveAsync(Create(exchange, MessageStatuses.Parked, $"No route for message type '{type}'."), ct); } /// The record built from the headers the inbound routes set. public static RedbObject Create(IExchange exchange, string status, string? error) { var partner = exchange.In.GetHeader(SerialHeaders.Partner) ?? ""; var fileName = exchange.In.GetHeader(SerialHeaders.FileName) ?? ""; return new RedbObject { name = $"{partner}/{fileName}", Props = new InboundMessage { PartnerCode = partner, Transport = exchange.In.GetHeader(SerialHeaders.Transport) ?? "", FileName = fileName, MessageType = exchange.In.GetHeader(SerialHeaders.MessageType), ArchivePath = exchange.In.GetHeader(SerialHeaders.ArchivePath) ?? "", ReceivedAt = DateTimeOffset.UtcNow, Status = status, Error = error, }, }; } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/OutboxWriter.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/Services/OutboxWriter.cs ---- using redb.Core; namespace SerialNumbers.Core.Services; /// /// The outbox: a table row per response to deliver. Written inside the request transaction and /// read by the outbox route with the sql: component, so a response is either committed and /// queued, or neither. /// public static class OutboxWriter { public static async Task EnqueueAsync(IRedbService redb, string partnerCode, long responseObjectId, CancellationToken ct) => await redb.Context.ExecuteAsync( "INSERT INTO dbo.outbox (partner_code, response_object_id) VALUES ($1, $2)", [partnerCode, responseObjectId], ct); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/QuotaReport.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/Services/QuotaReport.cs ---- using System.Globalization; using System.Text; using redb.Core; using redb.Route.Abstractions; using SerialNumbers.Domain.Entities; namespace SerialNumbers.Core.Services; /// /// The quota usage report: what the allocation ledger says was issued this year, set against the /// annual quota of each product. The numbers come from a flat table, the quotas from redb objects. /// public static class QuotaReport { public const string CsvHeader = "gtin,product,requests,issued,annual_quota,remaining,used_percent"; public static async Task RenderCsvAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { // The sql: producer leaves the result set in the body, one dictionary per row. var rows = (List>)exchange.In.Body!; var gtins = rows.Select(r => (string)r["gtin"]!).ToList(); // One query for every product in the report, not one per row. var products = await redb.Query() .Where(p => gtins.Contains(p.Gtin)) .ToListAsync(); var byGtin = products.ToDictionary(o => o.Props.Gtin, o => o.Props); var csv = new StringBuilder().AppendLine(CsvHeader); foreach (var row in rows) { var gtin = (string)row["gtin"]!; var requests = Convert.ToInt64(row["requests"], CultureInfo.InvariantCulture); var issued = Convert.ToInt64(row["issued"], CultureInfo.InvariantCulture); csv.Append(gtin).Append(','); if (byGtin.TryGetValue(gtin, out var product)) { var remaining = product.AnnualQuota - issued; var usedPercent = product.AnnualQuota == 0 ? 0m : 100m * issued / product.AnnualQuota; csv.Append(Quote(product.Name)).Append(',') .Append(requests).Append(',') .Append(issued).Append(',') .Append(product.AnnualQuota).Append(',') .Append(remaining).Append(',') .Append(usedPercent.ToString("0.0", CultureInfo.InvariantCulture)); } else { // Allocated once, no longer in the catalog: the numbers stay, the quota columns are empty. csv.Append(",").Append(requests).Append(',').Append(issued).Append(",,,"); } csv.AppendLine(); } exchange.In.Body = csv.ToString(); exchange.In.ContentType = "text/csv"; } private static string Quote(string value) => value.IndexOfAny([',', '"', '\n', '\r']) < 0 ? value : $"\"{value.Replace("\"", "\"\"")}\""; } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/ResponseRenderer.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/Services/ResponseRenderer.cs ---- using redb.Core; using redb.Route.Abstractions; using SerialNumbers.Core.Integration.Xml; using SerialNumbers.Domain.Entities; namespace SerialNumbers.Core.Services; /// Turns an outbox row into the XML response the partner receives. public static class ResponseRenderer { public static async Task RenderAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { // The sql: consumer copies the columns of the polled row into headers. var responseId = Convert.ToInt64(exchange.In.Headers["response_object_id"]); var response = await redb.LoadAsync(responseId, cancellationToken: ct) ?? throw new InvalidOperationException($"Response object {responseId} was not found."); var props = response.Props; var xml = new SerialNumberResponseXml { RequestId = props.RequestId, Gtin = props.Gtin, Status = props.Accepted ? "Accepted" : "Rejected", Reason = props.RejectionReason, Quantity = props.Quantity, }; if (props.AllocationId is long allocationId) { var serials = await SerialNumberAllocator.SerialNumbersOfAsync(redb, allocationId, ct); xml.SerialNumbers = serials.Select(s => s.ToString("D12")).ToList(); } exchange.In.Body = xml; exchange.In.Headers[SerialHeaders.FileName] = ArchivePaths.ResponseFileName(props.RequestId, responseId); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/SerialNumberAllocator.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/Services/SerialNumberAllocator.cs ---- using redb.Core; using SerialNumbers.Domain.Entities; namespace SerialNumbers.Core.Services; /// /// Serial numbers and the quota ledger, as plain SQL through redb.Context. Inside the request /// route's .Transacted() block it runs on the transaction's connection, so the numbers, the /// ledger row and the redb objects of the request commit or roll back together. /// /// Parameters are written $1, $2...: redb maps them to the provider's own syntax. /// /// public static class SerialNumberAllocator { /// /// The size of the block each serial number is drawn from: one chance in 10 000 to guess a /// number, as the verification service of a medicines agency expects. /// public const int BlockSize = 10_000; /// /// Quantity already allocated for the GTIN this year. The range lock (UPDLOCK, HOLDLOCK) holds /// until the transaction ends, so two requests for one product cannot both pass the quota check. /// public static async Task AllocatedThisYearAsync(IRedbService redb, string gtin, int year, CancellationToken ct) => await redb.Context.ExecuteScalarAsync( """ SELECT COALESCE(SUM(CAST(quantity AS bigint)), 0) FROM dbo.serial_allocations WITH (UPDLOCK, HOLDLOCK) WHERE gtin = $1 AND allocation_year = $2 """, [gtin, year], ct); /// /// Reserves one block per serial number, writes the ledger row and one row per serial number, /// and returns the id of the allocation. /// /// The numbers are not consecutive: the i-th number is a random value from its own block /// ((first + i) * 10000 + 1 .. (first + i + 1) * 10000), taken from /// CRYPT_GEN_RANDOM, the cryptographic generator of SQL Server. Blocks never overlap, so /// two numbers cannot collide, and the whole set is written by one statement however large it is. /// /// public static async Task AllocateAsync( IRedbService redb, SerialNumberRequest request, long requestObjectId, int year, CancellationToken ct) { var firstBlock = await redb.Context.ExecuteScalarAsync( """ IF NOT EXISTS (SELECT 1 FROM dbo.serial_blocks WITH (UPDLOCK, HOLDLOCK) WHERE gtin = $1) INSERT INTO dbo.serial_blocks (gtin, next_block) VALUES ($1, 0); UPDATE dbo.serial_blocks SET next_block = next_block + $2 OUTPUT deleted.next_block WHERE gtin = $1; """, [request.Gtin, request.Quantity], ct); var allocationId = await redb.Context.ExecuteScalarAsync( """ INSERT INTO dbo.serial_allocations (gtin, partner_code, request_id, request_object_id, first_block, quantity, allocation_year) OUTPUT inserted.id VALUES ($1, $2, $3, $4, $5, $6, $7); """, [request.Gtin, request.PartnerCode, request.RequestId, requestObjectId, firstBlock, request.Quantity, year], ct); // CRYPT_GEN_RANDOM(4) is evaluated per row; as bigint it is 0 .. 2^32 - 1, and modulo 10 000 // it is an offset inside the block. await redb.Context.ExecuteAsync( """ INSERT INTO dbo.serial_numbers (gtin, serial_value, allocation_id) SELECT $1, (CAST($3 AS bigint) + s.value) * $5 + 1 + CAST(CRYPT_GEN_RANDOM(4) AS bigint) % $5, $2 FROM GENERATE_SERIES(CAST(0 AS bigint), CAST($4 AS bigint) - 1) AS s; """, [request.Gtin, allocationId, firstBlock, request.Quantity, BlockSize], ct); return allocationId; } /// The serial numbers of an allocation, in block order. public static Task> SerialNumbersOfAsync(IRedbService redb, long allocationId, CancellationToken ct) => redb.Context.QueryScalarListAsync( "SELECT serial_value FROM dbo.serial_numbers WHERE allocation_id = $1 ORDER BY serial_value", [allocationId], ct); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/Services/SerialRequestService.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/Services/SerialRequestService.cs ---- using System.Globalization; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using SerialNumbers.Core.Integration.Xml; using SerialNumbers.Domain.Entities; using SerialNumbers.Domain.Services; namespace SerialNumbers.Core.Services; /// /// The steps of a serial number request. Each one is a ProcessWithRedb step inside the request /// route's .Transacted() block, so they either all commit or leave no trace. /// public static class SerialRequestService { /// /// Records the message and the request and takes the decision, or, for the release of a request on /// hold, decides that request again. Sets the header the route /// branches on. /// public static async Task RegisterAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Headers.TryGetValue(SerialHeaders.ReleaseOf, out var releaseOf) && releaseOf is not null) { await ResumeAsync(redb, exchange, Convert.ToInt64(releaseOf, CultureInfo.InvariantCulture), ct); return; } var xml = (SerialNumberRequestXml)exchange.In.Body!; var partner = exchange.In.GetHeader(SerialHeaders.Partner)!; var product = await ProductAsync(redb, xml.Gtin); var earlier = await redb.Query() .Where(r => r.PartnerCode == partner && r.RequestId == xml.RequestId) .Take(1) .ToListAsync(); var isDuplicate = earlier.Count > 0; var allocatedThisYear = await AllocatedThisYearAsync(redb, product, ct); var decision = SerialRequestPolicy.Decide(product?.Props, xml.Quantity, allocatedThisYear, isDuplicate); var messageId = await redb.SaveAsync(IntakeRecorder.Create(exchange, decision.Status, error: decision.RejectionReason), ct); var request = new RedbObject { name = $"{partner}/{xml.RequestId}", // The partner's request id is unique per partner. A concurrent twin fails on this key, // rolls back and is answered as a duplicate when the file is picked up again. ValueUnique = isDuplicate ? null : $"{partner}/{xml.RequestId}", Props = new SerialNumberRequest { RequestId = xml.RequestId, PartnerCode = partner, Gtin = xml.Gtin, Quantity = xml.Quantity, Status = decision.Status, RejectionReason = decision.RejectionReason, Message = new RedbObject { id = messageId }, }, }; await redb.SaveAsync(request, ct); exchange.Properties[SerialProperties.Request] = request; exchange.In.Headers[SerialHeaders.RequestId] = xml.RequestId; exchange.In.Headers[SerialHeaders.Decision] = decision.Status; } /// Accepted: reserves the serial numbers and writes the response. public static async Task AllocateAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = RequestOf(exchange); var allocationId = await SerialNumberAllocator.AllocateAsync(redb, request.Props, request.Id, DateTime.UtcNow.Year, ct); var response = ResponseTo(request); response.Props.Accepted = true; response.Props.AllocationId = allocationId; await redb.SaveAsync(response, ct); exchange.Properties[SerialProperties.Response] = response; } /// Rejected: writes a response carrying the reason. public static async Task RejectAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = RequestOf(exchange); var response = ResponseTo(request); response.Props.Accepted = false; response.Props.RejectionReason = request.Props.RejectionReason; await redb.SaveAsync(response, ct); exchange.Properties[SerialProperties.Response] = response; } /// Puts the response into the outbox, in the same transaction as everything above. public static async Task QueueResponseAsync(IRedbService redb, IExchange exchange, CancellationToken ct) { var response = (RedbObject)exchange.Properties[SerialProperties.Response]!; await OutboxWriter.EnqueueAsync(redb, response.Props.PartnerCode, response.Id, ct); } /// /// The release of a request on hold: the same request object is decided again, against the /// product and the quota as they are now. No new request, no new message record. /// private static async Task ResumeAsync(IRedbService redb, IExchange exchange, long requestObjectId, CancellationToken ct) { var request = await redb.LoadAsync(requestObjectId, cancellationToken: ct) ?? throw new InvalidOperationException($"Request object {requestObjectId} was not found."); exchange.In.Headers[SerialHeaders.RequestId] = request.Props.RequestId; if (request.Props.Status != MessageStatuses.OnHold) { exchange.In.Headers[SerialHeaders.Decision] = ReleaseOutcomes.AlreadyDecided; return; } var product = await ProductAsync(redb, request.Props.Gtin); var allocatedThisYear = await AllocatedThisYearAsync(redb, product, ct); var decision = SerialRequestPolicy.Decide(product?.Props, request.Props.Quantity, allocatedThisYear, isDuplicate: false); if (decision.Status != MessageStatuses.OnHold) { request.Props.Status = decision.Status; request.Props.RejectionReason = decision.RejectionReason; await redb.SaveAsync(request, ct); // Saved after the request, so the message record ends with the new status. var messageId = request.Props.Message?.Id ?? throw new InvalidOperationException($"Request object {requestObjectId} has no inbound message."); var message = await redb.LoadAsync(messageId, cancellationToken: ct) ?? throw new InvalidOperationException($"Inbound message object {messageId} was not found."); message.Props.Status = decision.Status; message.Props.Error = decision.RejectionReason; await redb.SaveAsync(message, ct); } exchange.Properties[SerialProperties.Request] = request; exchange.In.Headers[SerialHeaders.Decision] = decision.Status; } /// The GTIN is the product's unique key: a system-field lookup, no Props scan. private static Task?> ProductAsync(IRedbService redb, string gtin) => redb.Query() .WhereRedb(o => o.ValueUnique == gtin) .FirstOrDefaultAsync(); /// /// What was allocated this year, for an active product only. The read takes the range lock that keeps /// two requests from passing the quota together; a request that waits or is rejected does not need it. /// private static async Task AllocatedThisYearAsync(IRedbService redb, RedbObject? product, CancellationToken ct) => product?.Props.Status == ProductStatuses.Active ? await SerialNumberAllocator.AllocatedThisYearAsync(redb, product.Props.Gtin, DateTime.UtcNow.Year, ct) : 0; private static RedbObject RequestOf(IExchange exchange) => (RedbObject)exchange.Properties[SerialProperties.Request]!; private static RedbObject ResponseTo(RedbObject request) => new() { name = $"{request.Props.PartnerCode}/{request.Props.RequestId}", Props = new SerialNumberResponse { RequestId = request.Props.RequestId, PartnerCode = request.Props.PartnerCode, Gtin = request.Props.Gtin, Quantity = request.Props.Quantity, Request = new RedbObject { id = request.Id }, }, }; } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Core/manifest.json 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/manifest.json ---- { "Name": "SerialNumbers", "Version": "1.1.0", "EntryPoints": ["SerialNumbers.Core.dll"], "Dependencies": [] } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Entities/InboundMessage.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.Domain/Entities/InboundMessage.cs ---- using redb.Core.Attributes; namespace SerialNumbers.Domain.Entities; /// /// Every file a partner sent, whatever became of it. The raw bytes live in the file archive /// (); this object is the record of what the hub made of them. /// Nothing is ever deleted. /// [RedbScheme(Name = "SerialNumbers.InboundMessage")] public sealed class InboundMessage { public string PartnerCode { get; set; } = ""; public string Transport { get; set; } = ""; public string FileName { get; set; } = ""; /// The root element of the XML, when it could be read. public string? MessageType { get; set; } /// Path of the raw copy, relative to the archive root. public string ArchivePath { get; set; } = ""; public DateTimeOffset ReceivedAt { get; set; } /// One of . public string Status { get; set; } = ""; /// Why the message was not processed, for Invalid and Parked messages. public string? Error { get; set; } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Entities/Partner.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.Domain/Entities/Partner.cs ---- using redb.Core.Attributes; using SerialNumbers.Domain.Services; namespace SerialNumbers.Domain.Entities; /// /// A trading partner. The code is also the object's unique key (ValueUnique), so two /// partners can never share one. Adding a partner is adding data: the module registers one /// connection factory and one set of routes per partner when it starts. /// [RedbScheme(Name = "SerialNumbers.Partner")] public sealed class Partner { public string Code { get; set; } = ""; public string Name { get; set; } = ""; /// or . public string Transport { get; set; } = Transports.Sftp; /// SFTP folder the partner drops its requests into. public string? SftpInboundFolder { get; set; } /// SFTP folder the hub delivers responses to. public string? SftpOutboundFolder { get; set; } /// The partner's AS2 identifier. public string? As2Id { get; set; } /// The partner's AS2 endpoint the hub posts responses to. public string? As2Url { get; set; } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Entities/Product.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.Domain/Entities/Product.cs ---- using redb.Core.Attributes; using SerialNumbers.Domain.Services; namespace SerialNumbers.Domain.Entities; /// /// A product serial numbers are issued for. The GTIN is also the object's unique key /// (ValueUnique), which is what the request lookup goes through. /// [RedbScheme(Name = "SerialNumbers.Product")] public sealed class Product { public string Gtin { get; set; } = ""; public string Name { get; set; } = ""; /// /// One of . A new product starts as a draft: requests for it wait /// until someone activates it. /// public string Status { get; set; } = ProductStatuses.Draft; /// The largest quantity a single request may ask for. public int MaxPerRequest { get; set; } /// How many serial numbers may be issued for this product in one calendar year. public long AnnualQuota { get; set; } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Entities/SerialNumberRequest.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.Domain/Entities/SerialNumberRequest.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace SerialNumbers.Domain.Entities; /// A partner's request for serial numbers, with the decision taken on it. [RedbScheme(Name = "SerialNumbers.Request")] public sealed class SerialNumberRequest { /// The partner's own identifier of the request. public string RequestId { get; set; } = ""; public string PartnerCode { get; set; } = ""; public string Gtin { get; set; } = ""; public int Quantity { get; set; } /// /// , or /// . A request on hold is decided again when its product is activated. /// public string Status { get; set; } = ""; /// One of when rejected. public string? RejectionReason { get; set; } /// The inbound message this request came in. public RedbObject? Message { get; set; } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Entities/SerialNumberResponse.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.Domain/Entities/SerialNumberResponse.cs ---- using redb.Core.Attributes; using redb.Core.Models.Entities; namespace SerialNumbers.Domain.Entities; /// /// The answer to a request, as it is sent back. The individual serial numbers are rows of the /// serial_numbers table (a request can carry tens of thousands of them); an accepted response /// points at their allocation. /// [RedbScheme(Name = "SerialNumbers.Response")] public sealed class SerialNumberResponse { public string RequestId { get; set; } = ""; public string PartnerCode { get; set; } = ""; public string Gtin { get; set; } = ""; public bool Accepted { get; set; } /// One of when rejected. public string? RejectionReason { get; set; } public int Quantity { get; set; } /// The serial_allocations row the numbers of an accepted response belong to. public long? AllocationId { get; set; } public RedbObject? Request { get; set; } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/SerialNumbers.Domain.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/SerialNumbers.Domain.csproj ---- SerialNumbers.Domain Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Services/MessageStatuses.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.Domain/Services/MessageStatuses.cs ---- namespace SerialNumbers.Domain.Services; /// What happened to an inbound message, and to the request it carried. public static class MessageStatuses { /// A serial number request was read and answered with numbers. public const string Accepted = "Accepted"; /// A serial number request was read and answered with a rejection. public const string Rejected = "Rejected"; /// /// A serial number request for a product that is still a draft. Nothing is sent yet: the request /// is decided again when the product is activated. /// public const string OnHold = "OnHold"; /// The file is not a valid message: broken XML or a schema violation. public const string Invalid = "Invalid"; /// A valid message of a type this hub does not process yet. Kept for later. public const string Parked = "Parked"; } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Services/ProductStatuses.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.Domain/Services/ProductStatuses.cs ---- namespace SerialNumbers.Domain.Services; /// Where a product is in its life. public static class ProductStatuses { /// Being set up. Requests for it are put on hold, not rejected: the partner did nothing wrong. public const string Draft = "Draft"; /// Serial numbers are issued for it. public const string Active = "Active"; /// No longer produced. Requests for it are rejected. public const string Obsolete = "Obsolete"; public static bool IsKnown(string? status) => status is Draft or Active or Obsolete; } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Services/RejectionReasons.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.Domain/Services/RejectionReasons.cs ---- namespace SerialNumbers.Domain.Services; /// Why a serial number request was rejected. Sent back to the partner as is. public static class RejectionReasons { public const string UnknownProduct = "UnknownProduct"; public const string ProductObsolete = "ProductObsolete"; public const string QuantityOutOfRange = "QuantityOutOfRange"; public const string AnnualQuotaExhausted = "AnnualQuotaExhausted"; public const string DuplicateRequest = "DuplicateRequest"; } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Services/SerialRequestPolicy.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.Domain/Services/SerialRequestPolicy.cs ---- using SerialNumbers.Domain.Entities; namespace SerialNumbers.Domain.Services; /// The decision on a request: one of , with the reason of a rejection. public sealed record RequestDecision(string Status, string? RejectionReason) { public static readonly RequestDecision Accept = new(MessageStatuses.Accepted, null); public static readonly RequestDecision Hold = new(MessageStatuses.OnHold, null); public static RequestDecision Reject(string reason) => new(MessageStatuses.Rejected, reason); } /// /// The business decision on a serial number request, as a pure function: no database, no route. /// The caller gathers the facts (the product, what was already allocated this year, whether the /// request id was seen before) and gets back the decision. /// public static class SerialRequestPolicy { public static RequestDecision Decide(Product? product, int quantity, long allocatedThisYear, bool isDuplicate) { if (isDuplicate) return RequestDecision.Reject(RejectionReasons.DuplicateRequest); if (product is null) return RequestDecision.Reject(RejectionReasons.UnknownProduct); switch (product.Status) { case ProductStatuses.Obsolete: return RequestDecision.Reject(RejectionReasons.ProductObsolete); case ProductStatuses.Draft: case ProductStatuses.Active: break; default: throw new InvalidOperationException( $"Product {product.Gtin} has the status '{product.Status}', which is not one of the known product statuses."); } if (quantity <= 0 || quantity > product.MaxPerRequest) return RequestDecision.Reject(RejectionReasons.QuantityOutOfRange); // A draft is our side of the story: the request waits. The quota is checked when the product is // activated and the request is decided again, against what has been allocated by then. if (product.Status == ProductStatuses.Draft) return RequestDecision.Hold; if (allocatedThisYear + quantity > product.AnnualQuota) return RequestDecision.Reject(RejectionReasons.AnnualQuotaExhausted); return RequestDecision.Accept; } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Domain/Services/Transports.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.Domain/Services/Transports.cs ---- namespace SerialNumbers.Domain.Services; /// How a partner exchanges files with the hub. public static class Transports { public const string Sftp = "Sftp"; public const string As2 = "As2"; } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/ContextConfiguration.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.Worker/ContextConfiguration.cs ---- using Microsoft.Extensions.Configuration; using redb.Route.Abstractions; namespace SerialNumbers.Worker; /// /// The context configuration the way the Tsak worker builds it, in miniature. Each layer deep-merges /// over the previous one, later layers win: /// /// Tsak:Contexts:default of the host configuration, /// Tsak:Contexts:{context}, /// the module's {Module}.config.json, /// Tsak:Contexts:{context}:Override, the operator's last word. /// /// Every root key then becomes a property of the route context; a section becomes a dictionary. The /// real worker also reads a module's context.json and per-context Contexts blocks inside /// the module files; this module uses neither. /// public static class ContextConfiguration { /// The context a module asks for, from its ContextName. public static string ContextNameOf(string moduleConfigPath) => new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build()["ContextName"] ?? throw new InvalidOperationException($"{moduleConfigPath} has no ContextName."); public static IDictionary Build(IConfiguration host, string contextName, string moduleConfigPath) { var config = NewDictionary(); Merge(config, Read(host.GetSection("Tsak:Contexts:default"), skipReserved: true)); Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}"), skipReserved: true)); Merge(config, Read(new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build(), skipReserved: false)); Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}:Override"), skipReserved: false)); return config; } public static void ApplyTo(IRouteContext context, IDictionary config) { foreach (var (key, value) in config) { if (value is not null) context.SetProperty(key, value); } } private static Dictionary Read(IConfiguration section, bool skipReserved) { var result = NewDictionary(); foreach (var child in section.GetChildren()) { // A context section carries the module list and the Override layer next to the settings. if (skipReserved && (child.Key.Equals("Modules", StringComparison.OrdinalIgnoreCase) || child.Key.Equals("Override", StringComparison.OrdinalIgnoreCase))) continue; result[child.Key] = child.GetChildren().Any() ? Read(child, skipReserved: false) : child.Value; } return result; } private static void Merge(IDictionary target, IDictionary layer) { foreach (var (key, value) in layer) { if (value is IDictionary nested && target.TryGetValue(key, out var existing) && existing is IDictionary current) Merge(current, nested); else target[key] = value; } } private static Dictionary NewDictionary() => new(StringComparer.OrdinalIgnoreCase); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/DemoCertificates.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.Worker/DemoCertificates.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace SerialNumbers.Worker; /// /// Self-signed AS2 certificates for the demo: one pair for the hub, one for the simulated partner /// GLOBEX. Each side keeps its private key (.pfx) and hands the other side its public /// certificate (.cer). Real partners exchange certificates issued for the partnership. /// public static class DemoCertificates { public static void EnsureCreated(string directory, string password) { Directory.CreateDirectory(directory); EnsurePair(directory, "hub", "SERIALS-HUB", password); EnsurePair(directory, "globex", "GLOBEX", password); } private static void EnsurePair(string directory, string name, string commonName, string password) { var pfxPath = Path.Combine(directory, $"{name}.pfx"); var cerPath = Path.Combine(directory, $"{name}.cer"); if (File.Exists(pfxPath) && File.Exists(cerPath)) return; using var rsa = RSA.Create(2048); var request = new CertificateRequest($"CN={commonName}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5)); File.WriteAllBytes(pfxPath, certificate.Export(X509ContentType.Pkcs12, password)); File.WriteAllBytes(cerPath, certificate.Export(X509ContentType.Cert)); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/DemoData.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.Worker/DemoData.cs ---- using redb.Core; using redb.Core.Models.Entities; using SerialNumbers.Domain.Entities; using SerialNumbers.Domain.Services; namespace SerialNumbers.Worker; /// /// The demo's reference data: two partners and three products. Idempotent: an object whose unique /// key already exists is left as it is. /// public static class DemoData { public static async Task SeedAsync(IRedbService redb) { await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await EnsurePartnerAsync(redb, new Partner { Code = "acme", Name = "ACME Manufacturing", Transport = Transports.Sftp, SftpInboundFolder = "/upload/acme/to-hub", SftpOutboundFolder = "/upload/acme/from-hub", }); await EnsurePartnerAsync(redb, new Partner { Code = "globex", Name = "Globex Pharma", Transport = Transports.As2, As2Id = "GLOBEX", As2Url = "http://localhost:4081/as2/globex-inbox", }); await EnsureProductAsync(redb, new Product { Gtin = "04607001234567", Name = "Paracetamol 500 mg, 20 tablets", Status = ProductStatuses.Active, MaxPerRequest = 50_000, AnnualQuota = 10_000_000, }); // A small yearly quota, so the second GLOBEX sample runs into it. await EnsureProductAsync(redb, new Product { Gtin = "04607009990001", Name = "Vitamin D3 drops, 10 ml", Status = ProductStatuses.Active, MaxPerRequest = 30_000, AnnualQuota = 40_000, }); // Not activated yet: requests for it wait on hold until someone changes its status. await EnsureProductAsync(redb, new Product { Gtin = "04607005550001", Name = "Ibuprofen 200 mg, 10 capsules", Status = ProductStatuses.Draft, MaxPerRequest = 20_000, AnnualQuota = 1_000_000, }); } private static async Task EnsurePartnerAsync(IRedbService redb, Partner partner) { var existing = await redb.Query().WhereRedb(o => o.ValueUnique == partner.Code).FirstOrDefaultAsync(); if (existing is null) await redb.SaveAsync(new RedbObject { name = partner.Name, ValueUnique = partner.Code, Props = partner }); } private static async Task EnsureProductAsync(IRedbService redb, Product product) { var existing = await redb.Query().WhereRedb(o => o.ValueUnique == product.Gtin).FirstOrDefaultAsync(); if (existing is null) await redb.SaveAsync(new RedbObject { name = product.Name, ValueUnique = product.Gtin, Props = product }); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/DemoDatabase.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.Worker/DemoDatabase.cs ---- using Microsoft.Data.SqlClient; namespace SerialNumbers.Worker; /// Creates the demo database when the SQL Server does not have it yet. public static class DemoDatabase { public static async Task EnsureCreatedAsync(string connectionString) { var target = new SqlConnectionStringBuilder(connectionString); var database = target.InitialCatalog; var master = new SqlConnectionStringBuilder(connectionString) { InitialCatalog = "master" }; await using var connection = new SqlConnection(master.ConnectionString); await connection.OpenAsync(); await using var command = connection.CreateCommand(); command.CommandText = """ IF DB_ID(@name) IS NULL BEGIN DECLARE @sql nvarchar(400) = N'CREATE DATABASE ' + QUOTENAME(@name); EXEC (@sql); END """; command.Parameters.AddWithValue("@name", database); await command.ExecuteNonQueryAsync(); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/PartnerSimulator.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.Worker/PartnerSimulator.cs ---- using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.Logging; using Renci.SshNet; using redb.Route.As2; using redb.Route.As2.Fluent; using redb.Route.Core; using redb.Route.File; using redb.Route.Sftp; using SerialNumbers.Core; namespace SerialNumbers.Worker; /// /// Two trading partners, built from redb.Route like the hub itself, in a context of their own. They /// connect to the hub with the hub's own settings: same SFTP server, same certificate folder. /// /// ACME uploads the files dropped into its outbox to the hub's SFTP folder and downloads the responses. /// GLOBEX sends the files dropped into its outbox to the hub over AS2 and receives the responses over AS2. /// /// public static class PartnerSimulator { public static RouteContext Create(IServiceProvider services, ModuleSettings hub, string partnersDirectory) { var context = new RouteContext(services, contextId: "partners", loggerFactory: (ILoggerFactory?)services.GetService(typeof(ILoggerFactory))); context.AddComponent(new FileComponent()); context.AddComponent(new SftpComponent()); context.AddComponent(new As2Component()); context.AddToRegistry("acme-side", new SftpConnectionFactory { Host = hub.SftpHost, Port = hub.SftpPort, Username = hub.SftpUsername, Password = hub.SftpPasswordFor("acme"), }); context.AddToRegistry("globex-side", new As2ConnectionFactory { OurCertificate = X509CertificateLoader.LoadPkcs12FromFile( Path.Combine(hub.As2CertificateDirectory, "globex.pfx"), hub.As2CertificatePassword, X509KeyStorageFlags.Exportable), PartnerCertificate = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(hub.As2CertificateDirectory, "hub.cer")), As2From = "GLOBEX", As2To = hub.As2HubId, Sign = true, Encrypt = true, SignedMdn = true, MdnMode = As2MdnMode.Sync, }); string Folder(params string[] parts) => Path.Combine([partnersDirectory, .. parts]).Replace('\\', '/'); context.AddRoutes(r => { r.From(FileDsl.Read(Folder("acme", "outbox")).Include("*.xml").Delay(1000).MoveTo(".sent")) .RouteId("acme-upload") .To(Sftp.Directory("/upload/acme/to-hub") .ConnectionFactory("acme-side") .FileName("${header.redbFile.Name}") .TempFileName("${header.redbFile.Name}.part")) .Log("ACME uploaded ${header.redbFile.Name} over SFTP"); r.From(Sftp.Directory("/upload/acme/from-hub").ConnectionFactory("acme-side").Include("*.xml").Delay(2000).Delete()) .RouteId("acme-download") .To(FileDsl.Write(Folder("acme", "inbox")).FileName("${header.redbSftp.Name}")) .Log("ACME received ${header.redbSftp.Name}"); r.From(FileDsl.Read(Folder("globex", "outbox")).Include("*.xml").Delay(1000).MoveTo(".sent")) .RouteId("globex-send") .Process(e => e.In.ContentType = "application/xml") .To(As2.Send($"http://localhost:{hub.As2ReceivePort}/as2/globex").ConnectionFactory("globex-side")) .Log("GLOBEX sent ${header.redbFile.Name} over AS2"); r.From(As2.Receive("/as2/globex-inbox").Host("0.0.0.0").Port(4081).ConnectionFactory("globex-side")) .RouteId("globex-receive") .SetHeader("responseFile", e => $"SNRESP_{DateTime.UtcNow:yyyyMMdd_HHmmssfff}.xml") .To(FileDsl.Write(Folder("globex", "inbox")).FileName("${header.responseFile}")) .Log("GLOBEX received ${header.responseFile} over AS2"); }); foreach (var partner in new[] { "acme", "globex" }) { Directory.CreateDirectory(Path.Combine(partnersDirectory, partner, "outbox")); Directory.CreateDirectory(Path.Combine(partnersDirectory, partner, "inbox")); } EnsureAcmeSftpFolders(hub); return context; } /// /// On a real SFTP server the partner's folders are set up once, with the account. The hub treats a /// missing inbound folder as a misconfiguration and logs every poll of it, so the demo creates them /// before anything starts, and seed creates them before the module runs under Tsak. /// public static void EnsureAcmeSftpFolders(ModuleSettings hub) { using var sftp = new SftpClient(hub.SftpHost, hub.SftpPort, hub.SftpUsername, hub.SftpPasswordFor("acme")); sftp.Connect(); foreach (var folder in new[] { "/upload/acme", "/upload/acme/to-hub", "/upload/acme/from-hub" }) { if (!sftp.Exists(folder)) sftp.CreateDirectory(folder); } sftp.Disconnect(); } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/ProductConsole.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.Worker/ProductConsole.cs ---- using redb.Route.Core; using SerialNumbers.Core; using SerialNumbers.Core.Catalog; namespace SerialNumbers.Worker; /// /// Product status changes typed into the console, for example status 04607005550001 Active. /// /// A command goes through a to direct:set-product-status, the /// endpoint the REST API calls: code running in the same process as the routes uses them exactly as a /// web page does over HTTP, and gets the same answer back. /// /// public static class ProductConsole { public static Task RunAsync(RouteContext hub, CancellationToken stopping) => Task.Run(async () => { using var producer = new ProducerTemplate(hub); producer.Start(); while (!stopping.IsCancellationRequested) { var line = Console.ReadLine(); if (line is null) return; // no console input, for example when started without a terminal var words = line.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (words.Length == 0) continue; if (words is not ["status", var gtin, var status]) { Console.WriteLine("Usage: status "); continue; } var message = new Message(new ProductStatusChange(status, ChangedBy: "console")); message.Headers[SerialHeaders.Gtin] = gtin; try { // ProductStatusResult, or ApiError for an unknown product or status. Console.WriteLine(await producer.RequestBody(RouteUris.SetProductStatus, message, stopping)); } catch (Exception ex) when (ex is not OperationCanceledException) { // The route logged the failure; the console shows it and keeps reading commands. Console.WriteLine($"The status change failed: {ex.Message}"); } } }, stopping); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/Program.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.Worker/Program.cs ---- // ============================================================================ // SerialNumbers.Worker: the debug host of the SerialNumbers module. // // 1) reads its own configuration: appsettings.json, then environment variables, // 2) creates the demo database and brings redb up on SQL Server with two partners and three products, // 3) builds the context configuration the way the Tsak worker does (module config file, then the // Override section of appsettings.json) and sets it on the route context, // 4) awaits SerialNumbers.Core.InitRoute.main(ctx), the method the Tsak worker calls, // 5) starts two simulated partners next to the hub: ACME on SFTP, GLOBEX on AS2, // 6) reads product status commands from the console and sends them through a ProducerTemplate. // // Then drop a file from samples/ into runtime/partners//outbox and watch it travel. // // "dotnet run --project SerialNumbers.Worker -- seed" stops after the database, the demo data, the AS2 // certificates and the SFTP folders: what the module needs before it runs under Tsak. // ============================================================================ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.Route.Core; using redb.Route.Http; using SerialNumbers.Core; namespace SerialNumbers.Worker; public static class Program { /// /// No arguments: run the hub and the simulated partners. seed: prepare what the module needs /// before it runs under Tsak (the database, the demo partners and products, the AS2 certificates and /// the ACME SFTP folders), then exit. /// public static async Task Main(string[] args) { var seedOnly = args is ["seed"]; if (args.Length > 0 && !seedOnly) throw new ArgumentException($"Unknown arguments '{string.Join(' ', args)}'. Run without arguments, or with 'seed'."); // Environment variables win over the file, as on the Tsak worker: // ConnectionStrings__MSSql, Tsak__Contexts__serial-numbers__Override__Report__Cron, ... var configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables() .Build(); var sqlConnection = configuration.GetConnectionString(ModuleSettings.ConnectionStringName) ?? throw new InvalidOperationException($"ConnectionStrings:{ModuleSettings.ConnectionStringName} is not set."); await DemoDatabase.EnsureCreatedAsync(sqlConnection); var services = new ServiceCollection(); services.AddSingleton(configuration); services.AddLogging(b => b .AddSimpleConsole(o => { o.SingleLine = true; o.TimestampFormat = "HH:mm:ss "; }) .SetMinimumLevel(LogLevel.Information)); // The tier and the save strategy the module gets under Tsak, so the debug host behaves the same: // Pro (free through redb 4.x, no license key) and ChangeTracking, which writes only the properties // that changed instead of rewriting all of them on every save. services.AddRedbPro(o => o .UseMsSql(sqlConnection) .Configure(c => c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking)); // The HTTP servers of the process, one per port, as the Tsak worker registers them. services.AddRedbRouteHttpHosting(); await using var provider = services.BuildServiceProvider(); await using (var scope = provider.CreateAsyncScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); // the Tsak worker does this on boot await DemoData.SeedAsync(redb); } // The context, its configuration and its logger factory, as the Tsak worker hands them over. var moduleConfig = Path.Combine(AppContext.BaseDirectory, "SerialNumbers.Core.config.json"); var contextName = ContextConfiguration.ContextNameOf(moduleConfig); var hub = new RouteContext(provider, contextName, provider.GetRequiredService()); ContextConfiguration.ApplyTo(hub, ContextConfiguration.Build(configuration, contextName, moduleConfig)); var settings = ModuleSettings.FromContext(hub); DemoCertificates.EnsureCreated(settings.As2CertificateDirectory, settings.As2CertificatePassword); if (seedOnly) { PartnerSimulator.EnsureAcmeSftpFolders(settings); await hub.DisposeAsync(); Console.WriteLine($"Seeded: database '{new Microsoft.Data.SqlClient.SqlConnectionStringBuilder(sqlConnection).InitialCatalog}', " + $"demo partners and products, AS2 certificates in {settings.As2CertificateDirectory}, ACME SFTP folders."); return; } await SerialNumbers.Core.InitRoute.main(hub); // <- the exact method the Tsak worker calls var partnersDirectory = Path.GetFullPath(configuration["Demo:PartnersDirectory"] ?? "runtime/partners"); var partners = PartnerSimulator.Create(provider, settings, partnersDirectory); await hub.Start(); await partners.Start(); Console.WriteLine(); Console.WriteLine("SerialNumbers hub is running."); Console.WriteLine($" ACME (SFTP): drop a file into {Path.Combine(partnersDirectory, "acme", "outbox")}"); Console.WriteLine($" GLOBEX (AS2): drop a file into {Path.Combine(partnersDirectory, "globex", "outbox")}"); Console.WriteLine($" Responses arrive in {Path.Combine(partnersDirectory, "", "inbox")}"); Console.WriteLine($" Product API: PUT http://localhost:{settings.ApiPort}/api/products//status {{\"status\":\"Active\",\"changedBy\":\"you\"}}"); Console.WriteLine($" Console: status <{ProductStatusNames}>"); Console.WriteLine("Ctrl+C to exit."); Console.WriteLine(); using var stopping = new CancellationTokenSource(); _ = ProductConsole.RunAsync(hub, stopping.Token); var stop = new TaskCompletionSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.TrySetResult(); }; await stop.Task; await stopping.CancelAsync(); await partners.DisposeAsync(); await hub.DisposeAsync(); } private const string ProductStatusNames = "Draft|Active|Obsolete"; } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/SerialNumbers.Worker.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/SerialNumbers.Worker.csproj ---- Exe SerialNumbers.Worker Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Worker/appsettings.json 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.Worker/appsettings.json ---- { "ConnectionStrings": { "MSSql": "Server=localhost,1433;Database=serials_demo;User Id=sa;Password=Demo_Passw0rd;TrustServerCertificate=true" }, "Tsak": { "Contexts": { "serial-numbers": { "Override": { "Archive": { "Directory": "runtime/archive" }, "Sftp": { "Port": 2222, "Username": "testuser", "Password": "secret" }, "As2": { "CertificateDirectory": "runtime/certs", "CertificatePassword": "demo" }, "Report": { "Directory": "runtime/reports", "Cron": "0 * * * * ?" } } } } }, "Demo": { "PartnersDirectory": "runtime/partners" } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/Beans/SerialBeans.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.Xml/Beans/SerialBeans.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using SerialNumbers.Core.Services; namespace SerialNumbers.Xml.Beans; /// /// The bridge between the markup and the module's services. A route calls /// bean:#name?method=X, and the bean invoker accepts (IExchange) or /// (IExchange, CancellationToken) - so every method here is that shape and hands the /// exchange to the service unchanged. The redb instance is the exchange's own, the same one /// ProcessWithRedb resolves in the C# spelling: one connection per exchange, enlisted in /// the transaction the route opened. /// public sealed class SerialRequestBeans { public Task Register(IExchange exchange, CancellationToken ct) => SerialRequestService.RegisterAsync(Redb(exchange), exchange, ct); public Task Allocate(IExchange exchange, CancellationToken ct) => SerialRequestService.AllocateAsync(Redb(exchange), exchange, ct); public Task Reject(IExchange exchange, CancellationToken ct) => SerialRequestService.RejectAsync(Redb(exchange), exchange, ct); public Task QueueResponse(IExchange exchange, CancellationToken ct) => SerialRequestService.QueueResponseAsync(Redb(exchange), exchange, ct); internal static IRedbService Redb(IExchange exchange) => exchange.ServiceProvider?.GetService() ?? throw new InvalidOperationException( "The exchange carries no IRedbService: the module must run in a host that registers redb (the Tsak worker does)."); } /// What the intake records when a file cannot be processed. public sealed class IntakeBeans { public Task RecordInvalid(IExchange exchange, CancellationToken ct) => IntakeRecorder.RecordInvalidAsync(SerialRequestBeans.Redb(exchange), exchange, ct); public Task RecordParked(IExchange exchange, CancellationToken ct) => IntakeRecorder.RecordParkedAsync(SerialRequestBeans.Redb(exchange), exchange, ct); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/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.Xml/InitRoute.cs ---- using redb.Route.Abstractions; namespace SerialNumbers.Xml; /// /// The module bootstrap Tsak calls before the artifacts load (main(IRouteContext)). It does /// what markup cannot: AS2 certificates are X509 objects loaded from files, the demo database is /// created and seeded, and the partner list comes from redb. Everything that IS expressible - /// components, the sql: data source, the SFTP partner connection and the /// beans - is declared in context.xml instead, so the file says what the module is made of. /// public static class InitRoute { public static Task main(IRouteContext context) => Core.InitRoute.main(context); } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/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/SerialNumbers.Xml/README.md ---- # SerialNumbers.Xml — the same integration, spelled in XML This is the module next door, `SerialNumbers.Core`, with one difference: the flow lives in `context.xml` and `routes/*.route.xml` instead of `RouteBuilder` classes. The domain, the services, the database and the worker are the same code — nothing was rewritten to make the markup possible. | Path | What | |---|---| | `routes/*.route.xml` | the routes: intake, request, outbox, delivery, reports | | `context.xml` | the objects the routes reference by name: the beans the routes call | | `Beans/SerialBeans.cs` | ten wrappers: a route says `bean:#serial-requests?method=Register`, the wrapper hands the exchange to the service | | `InitRoute.cs` | the module bootstrap — the part markup cannot express (see below) | | `resources/` | `SerialNumberRequest.xsd`, resolved from the package root by `` | | `config/SerialNumbers.Xml.config.json` | module identity and the settings the routes read as `{{placeholders}}` | ## What XML buys, and what it costs **Buys.** The pipeline is readable without a compiler: what `` encloses is what commits together, and the branch names of a `` are the decision table. The package deploys as a `.tpkg` the worker hot-reloads, and the graph editor of the VS Code extension draws it as it is. **Costs.** Two things the C# spelling does that markup does not: 1. **Partner topology.** `SerialNumbers.Core` generates one SFTP consumer and one delivery route *per partner read from the database*. Markup is static, so here every partner is written out: `acme` over SFTP, `globex` over AS2. Choose by how partners change — by deploy, or at runtime. 2. **The module bootstrap.** The demo database is created and seeded from code, and this module reuses the C# module's `InitRoute.main` for it - which also registers the components, the `sql:` data source and the partner connections. Those four are declarable (see below); they stay in code only while the bootstrap is shared. That boundary is the point of this demo: markup describes the flow, code provides what has to be code. Certificates used to belong to the second group and no longer do. A `` takes a nested anonymous ``, and `factoryMethod=` calls a static creator, so an AS2 partner is declarable in full - key material included: ```xml ``` ## Build and deploy dotnet build -p:PackRouteOnBuild=true -p:Version=1.0.0 # -> pkg/serial-numbers-xml-1.0.0.tpkg, checked by the Ф5.4 gate against the build output Drop the `.tpkg` into the worker's `modules/`. Run it INSTEAD of the C# module, not beside it: both read the same demo database, so they share its partners and their SFTP folders and would race for the same files. Everything else is already distinct - context name, API port (8091), AS2 port (4082), archive and report folders - so switching spellings is dropping one `.tpkg` and removing the other. Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/SerialNumbers.Xml.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/SerialNumbers.Xml.csproj ---- SerialNumbers.Xml serial-numbers-xml serial-numbers-xml true Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/config/SerialNumbers.Xml.config.json 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.Xml/config/SerialNumbers.Xml.config.json ---- { "//": "L4 (in-package): module identity and the settings the routes read as {{placeholders}}. Secrets arrive from the worker's Override layer, never from here.", "ContextName": "serial-numbers-xml", "AutoStart": true, "Archive": { "Directory": "data/serials-xml/archive" }, "Sftp": { "Host": "localhost", "Port": 22, "Username": "serials" }, "As2": { "Id": "SERIALS-HUB", "ReceivePort": 4082, "CertificateDirectory": "data/serials-xml/certs" }, "Api": { "Port": 8091 }, "Report": { "Directory": "data/serials-xml/reports", "Cron": "0 0 6 * * ?", "TimeZone": "UTC" } } Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/context.xml 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.Xml/context.xml ---- Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/resources/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.Xml/resources/SerialNumberRequest.xsd ---- Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.Xml/routes/serial-number-request.route.xml 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.Xml/routes/serial-number-request.route.xml ---- ${header.serials.partner}: ${header.serials.fileName} violates the schema, recorded as Invalid ${header.serials.partner}: request ${header.serials.requestId} is on hold until its product is activated ${header.serials.partner}: request ${header.serials.requestId} was decided by another release, nothing to do ${header.serials.partner}: request ${header.serials.requestId} ${header.serials.decision}, response queued ${messageHistory()} Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.deploy/docker-compose.dev.yml 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.deploy/docker-compose.dev.yml ---- # Local infrastructure for the demo: SQL Server and an SFTP server. # The debug host's settings (SerialNumbers.Worker/appsettings.json) match these values. # # docker compose -f SerialNumbers.deploy/docker-compose.dev.yml up -d services: sqlserver: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Demo_Passw0rd" ports: - "1433:1433" sftp: image: atmoz/sftp:latest # user:password:uid:gid:directory - the partner folders are created under /upload command: testuser:secret:::upload ports: - "2222:22" Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.deploy/docker-compose.tsak.yml 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.deploy/docker-compose.tsak.yml ---- # The demo on Tsak: SQL Server, an SFTP server and the Tsak stack image (worker and dashboard in one container). # # From the demo folder: # cp SerialNumbers.deploy/.env.example SerialNumbers.deploy/.env # then fill in the Tsak values # docker compose -f SerialNumbers.deploy/docker-compose.tsak.yml up -d sqlserver sftp # dotnet run --project SerialNumbers.Worker -- seed # database, demo data, AS2 certificates, SFTP folders # pwsh SerialNumbers.deploy/pack-tpkg.ps1 # -> SerialNumbers.deploy/output/SerialNumbers.tpkg # docker compose -f SerialNumbers.deploy/docker-compose.tsak.yml up -d tsak # # Then copy a sample into runtime/sftp/acme/to-hub/; the response arrives in runtime/sftp/acme/from-hub/. # Dashboard: http://localhost:8085 (admin and TSAK_WEB_ADMIN_PASSWORD). Product API: http://localhost:8090/api/products. services: sqlserver: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_SA_PASSWORD: "Demo_Passw0rd" ports: - "1433:1433" sftp: image: atmoz/sftp:latest # user:password:uid:gid:directory - the partner folders are created under /upload command: testuser:secret:::upload ports: - "2222:22" volumes: # The partner's side of SFTP on the host: runtime/sftp/acme/to-hub and runtime/sftp/acme/from-hub. # On Linux the folder must be writable by the container's user. - ../runtime/sftp:/home/testuser/upload tsak: image: ghcr.io/redbase-app/redb-tsak-stack:${TSAK_VERSION:-4.3.0-net10} restart: unless-stopped depends_on: - sqlserver - sftp ports: - "127.0.0.1:9090:9090" # worker API - "127.0.0.1:8085:8085" # dashboard - "127.0.0.1:8090:8090" # the module's product API environment: # The module works in the worker's default (unnamed) redb. Its provider is Tsak:Redb:Provider, and the # module's schema script is written for SQL Server, so: mssql, with ConnectionStrings:MSSql. The worker # ships sqlite so that it starts out of the box; the connection string alone does not change the # provider. Storage:Type=Redb keeps Tsak's own state in the same database. The database itself is # created by "SerialNumbers.Worker seed": redb creates its tables, not the database. - ConnectionStrings__MSSql=Server=sqlserver;Database=serials_demo;User Id=sa;Password=Demo_Passw0rd;TrustServerCertificate=true - Tsak__Storage__Type=Redb - Tsak__Redb__Provider=mssql - Tsak__Redb__UsePro=true # Saves only the properties that actually changed instead of rewriting all of them: a request is # written several times over its life, and so is a product. Needs the Pro tier above, which is free. - Tsak__Redb__PropsSaveStrategy=ChangeTracking - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Cluster__ApiEndpoint=http://tsak:9090 - Tsak__Cluster__NodeId=serials-1 # The worker's API requires a key; the dashboard in the same container calls it with the service key. # The worker stores only the key's hash: HMAC-SHA256 of the key with Tsak:Auth:Secret (see .env.example). - Tsak__Auth__Enabled=true - Tsak__Auth__Secret=${TSAK_AUTH_SECRET:?TSAK_AUTH_SECRET required} - Tsak__Auth__Keys__0__Id=svc-tsak-web - Tsak__Auth__Keys__0__KeyHash=${TSAK_WEB_API_KEY_HASH:?TSAK_WEB_API_KEY_HASH required} - Tsak__Auth__Keys__0__Name=tsak-web-dashboard - Tsak__Auth__Keys__0__Roles=admin - Tsak__Web__AdminLogin=admin - Tsak__Web__AdminPassword=${TSAK_WEB_ADMIN_PASSWORD:?TSAK_WEB_ADMIN_PASSWORD required} - Tsak__Web__ServiceApiKey=${TSAK_WEB_API_KEY:?TSAK_WEB_API_KEY required} - Tsak__Web__Mode=cluster # The module's settings: the Override layer of its context. Secrets go here, never into the module's # config file, which is loaded after Tsak:Contexts and would win over a plain context value. - Tsak__Contexts__serial-numbers__Override__Archive__Directory=/data/archive - Tsak__Contexts__serial-numbers__Override__Report__Directory=/data/reports - Tsak__Contexts__serial-numbers__Override__Report__Cron=0 * * * * ? # Inside the compose network the SFTP server is "sftp" on port 22, not localhost:2222. - Tsak__Contexts__serial-numbers__Override__Sftp__Host=sftp - Tsak__Contexts__serial-numbers__Override__Sftp__Port=22 - Tsak__Contexts__serial-numbers__Override__Sftp__Username=testuser - Tsak__Contexts__serial-numbers__Override__Sftp__Password=secret # The certificates "SerialNumbers.Worker seed" wrote, and their password. - Tsak__Contexts__serial-numbers__Override__As2__CertificateDirectory=/data/certs - Tsak__Contexts__serial-numbers__Override__As2__CertificatePassword=demo volumes: - ./output:/app/modules - ../runtime/certs:/data/certs:ro - ../runtime/tsak/archive:/data/archive - ../runtime/tsak/reports:/data/reports - ../runtime/tsak/logs:/app/worker/Logs Path: redb-route/demo/SerialNumbersDemo/SerialNumbers.deploy/pack-tpkg.ps1 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.deploy/pack-tpkg.ps1 ---- #!/usr/bin/env pwsh <# .SYNOPSIS Builds SerialNumbers.Core and packs it into SerialNumbers.tpkg for a Tsak worker. .DESCRIPTION The package holds the manifest, the module config, the two DLLs of the demo (SerialNumbers.Core.dll, the entry point, and SerialNumbers.Domain.dll) and EF Core, which the module uses for the product status journal. redb, redb.Route, their connectors and Microsoft.Data.SqlClient already ship in the worker's shared libraries, so they stay out of the package and EF Core runs on the worker's SqlClient, the one redb uses. .EXAMPLE ./pack-tpkg.ps1 ./pack-tpkg.ps1 -Configuration Debug #> param( [ValidateSet("Debug", "Release")] [string]$Configuration = "Release" ) $ErrorActionPreference = "Stop" $root = Resolve-Path (Join-Path $PSScriptRoot "..") $core = Join-Path $root "SerialNumbers.Core" $publish = Join-Path ([IO.Path]::GetTempPath()) "serialnumbers-publish" $staging = Join-Path ([IO.Path]::GetTempPath()) "serialnumbers-tpkg" $output = Join-Path $PSScriptRoot "output" $package = Join-Path $output "SerialNumbers.tpkg" # publish, not build: a class library's build output does not contain its NuGet dependencies. if (Test-Path $publish) { Remove-Item -Recurse -Force $publish } dotnet publish (Join-Path $core "SerialNumbers.Core.csproj") -c $Configuration -o $publish --nologo if ($LASTEXITCODE -ne 0) { throw "Publish of SerialNumbers.Core failed." } if (Test-Path $staging) { Remove-Item -Recurse -Force $staging } New-Item -ItemType Directory -Force $staging | Out-Null New-Item -ItemType Directory -Force $output | Out-Null Copy-Item (Join-Path $core "manifest.json") $staging Copy-Item (Join-Path $core "SerialNumbers.Core.config.json") $staging Copy-Item (Join-Path $publish "SerialNumbers.Core.dll") $staging Copy-Item (Join-Path $publish "SerialNumbers.Domain.dll") $staging $efCore = Get-ChildItem $publish -Filter "Microsoft.EntityFrameworkCore*.dll" if ($efCore.Count -eq 0) { throw "EF Core assemblies were not found in $publish." } $efCore | Copy-Item -Destination $staging if (Test-Path $package) { Remove-Item -Force $package } Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory($staging, $package) Write-Host "Packed $package" Path: redb-route/demo/SerialNumbersDemo/samples/acme/PIF_ACME_0001.xml 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/samples/acme/PIF_ACME_0001.xml ---- B-2026-0917 04607001234567 2026-09-17 000000007315 000000012094 000000028861 000000031402 Path: redb-route/demo/SerialNumbersDemo/samples/acme/SNREQ_ACME_0001.xml 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/samples/acme/SNREQ_ACME_0001.xml ---- ACME-2026-0001 04607001234567 30000 Path: redb-route/demo/SerialNumbersDemo/samples/acme/SNREQ_ACME_0002_over_limit.xml 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/samples/acme/SNREQ_ACME_0002_over_limit.xml ---- ACME-2026-0002 04607001234567 60000 Path: redb-route/demo/SerialNumbersDemo/samples/acme/SNREQ_ACME_0003_unknown_product.xml 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/samples/acme/SNREQ_ACME_0003_unknown_product.xml ---- ACME-2026-0003 04600000000000 1000 Path: redb-route/demo/SerialNumbersDemo/samples/acme/SNREQ_ACME_0004_duplicate.xml 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/samples/acme/SNREQ_ACME_0004_duplicate.xml ---- ACME-2026-0001 04607001234567 30000 Path: redb-route/demo/SerialNumbersDemo/samples/acme/SNREQ_ACME_0005_schema_violation.xml 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/samples/acme/SNREQ_ACME_0005_schema_violation.xml ---- ACME-2026-0005 4607001 many Path: redb-route/demo/SerialNumbersDemo/samples/acme/SNREQ_ACME_0006_broken.xml 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/samples/acme/SNREQ_ACME_0006_broken.xml ---- ACME-2026-0006 04607001234567 100 Path: redb-route/demo/SerialNumbersDemo/samples/acme/SNREQ_ACME_0007_draft_product.xml 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/samples/acme/SNREQ_ACME_0007_draft_product.xml ---- ACME-2026-0007 04607005550001 5000 Path: redb-route/demo/SerialNumbersDemo/samples/globex/SNREQ_GLOBEX_0001.xml 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/samples/globex/SNREQ_GLOBEX_0001.xml ---- GLOBEX-7001 04607009990001 30000 Path: redb-route/demo/SerialNumbersDemo/samples/globex/SNREQ_GLOBEX_0002_quota.xml 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/samples/globex/SNREQ_GLOBEX_0002_quota.xml ---- GLOBEX-7002 04607009990001 20000